github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/charset/utils.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "fmt" 19 "strings" 20 ) 21 22 // TokenChars characters allowed in base64 encoded string. 23 const TokenChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/-_=" 24 25 // ContainsTokenCharset checks if a string contains non-base64 encoding 26 // characters. 27 func ContainsTokenCharset(s string) bool { 28 dots := 0 29 for _, c := range s { 30 if !strings.ContainsRune(TokenChars, c) { 31 return false 32 } 33 // Match dot 34 if c == 46 { 35 dots++ 36 } 37 } 38 if dots != 2 { 39 return false 40 } 41 return true 42 } 43 44 // ContainsInvalidChars returns error if the provided string contains 45 // characters outside of the allowed character set. 46 func ContainsInvalidChars(charset, s string) error { 47 for i, c := range s { 48 if !strings.Contains(charset, strings.ToLower(string(c))) && 49 !strings.Contains(charset, strings.ToUpper(string(c))) { 50 return fmt.Errorf("string %s contains forbidden character %d, pos: %d", s, c, i) 51 } 52 } 53 return nil 54 } 55 56 // ContainsValidCharset returns error if the provided string contains 57 // characters outside of the provided character set. 58 func ContainsValidCharset(charset, s string) error { 59 for i, c := range s { 60 if !strings.Contains(charset, string(c)) { 61 return fmt.Errorf("string %s contains forbidden character %d, pos: %d", s, c, i) 62 } 63 } 64 return nil 65 }