go_access_token/main.go
2022-10-30 13:45:03 +00:00

45 lines
1001 B
Go

package accessToken
import (
"errors"
"fmt"
"regexp"
)
func Generate(prefix string, secret string) (string, error) {
if len(prefix) != 3 {
return "", errors.New("prefix is not 3 characters long")
}
randomString, err := randomBase62String(30)
if err != nil {
return "", err
}
firstPart := fmt.Sprintf("%s_%s", prefix, randomString)
checksum, err := getChecksum(firstPart + secret)
if err != nil {
return "", err
}
return firstPart + checksum, nil
}
func Validate(token string, secret string) (bool, error) {
exp := regexp.MustCompile("([abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{3})_([0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{30})([0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{6})")
if !exp.Match([]byte(token)) {
return false, errors.New("wrong token format")
}
checksum, err := getChecksum(token[:len(token)-6] + secret)
if err != nil {
return false, err
}
return token[len(token)-6:] == checksum, nil
}