github.com/coreservice-io/utils@v0.3.0/token_util/token.go (about) 1 package token_util 2 3 import ( 4 "github.com/coreservice-io/utils/hash_util" 5 "github.com/coreservice-io/utils/rand_util" 6 ) 7 8 // never change this as widely used in different project 9 const salt_hash_round = 10000000 10 11 // never change this as widely used in different project 12 // never change this as md5 result is 32 len 13 // final token = raw_token+md5(raw_token+private_key)[0:16] 14 const raw_token_len = 16 //!!!!!important never change this 15 const md5_token_len = 16 //!!!!!important never change this 16 const final_token_len = raw_token_len + md5_token_len //!!!!!important never change this 17 18 const super_token_mark = "super" 19 20 type TokenUtil struct { 21 white_list_raw_token map[string]interface{} //raw whitelist token 22 private_key string 23 } 24 25 func NewTokenUtil(salt string) *TokenUtil { 26 27 pkey := salt 28 for i := 0; i < salt_hash_round; i++ { 29 pkey = hash_util.MD5HashString(pkey) 30 } 31 32 return &TokenUtil{ 33 white_list_raw_token: make(map[string]interface{}), 34 private_key: pkey, 35 } 36 } 37 38 // append raw whitelist token list 39 func (tutil *TokenUtil) AppendWhiteListToken(raw_tokens map[string]interface{}) { 40 for key, val := range raw_tokens { 41 tutil.white_list_raw_token[key] = val 42 } 43 } 44 45 // return nil if not found 46 func (tutil *TokenUtil) GetWhiteListToken(token string) interface{} { 47 if val, exist := tutil.white_list_raw_token[token]; exist { 48 return val 49 } else { 50 return nil 51 } 52 } 53 54 func (tutil *TokenUtil) GenToken() string { 55 raw_token := rand_util.GenRandStr(raw_token_len) 56 return raw_token + hash_util.MD5HashString(raw_token + tutil.private_key)[0:md5_token_len] 57 } 58 59 func (tutil *TokenUtil) GenSuperToken() string { 60 raw_token := rand_util.GenRandStr(raw_token_len) 61 return raw_token + hash_util.MD5HashString(super_token_mark + raw_token + tutil.private_key)[0:md5_token_len] 62 } 63 64 // return is_token,is_super_token 65 func (tutil *TokenUtil) CheckToken(token string) (bool, bool) { 66 67 //check whitelist 68 if _, exist := tutil.white_list_raw_token[token]; exist { 69 //len check 70 if len(token) != final_token_len { 71 return true, false 72 } 73 } 74 75 //len check 76 if len(token) != final_token_len { 77 return false, false 78 } 79 80 raw_token := token[0:raw_token_len] 81 md5_token := token[raw_token_len:] 82 83 //check super token 84 if md5_token == hash_util.MD5HashString(super_token_mark + raw_token + tutil.private_key)[0:md5_token_len] { 85 return true, true 86 } 87 88 if md5_token == hash_util.MD5HashString(raw_token + tutil.private_key)[0:md5_token_len] { 89 return true, false 90 } 91 92 return false, false 93 }