package tokenTools import ( "crypto/rand" "fmt" jwt "github.com/dgrijalva/jwt-go" "golang.org/x/crypto/bcrypt" ) var hmacSecret []byte // GenerateSecret generate the secret to verify JWTs func GenerateSecret() []byte { b := make([]byte, 32) rand.Read(b) return b } // InitJWTService generate the secret to verify JWTs and store it in memory func InitTokenToolsService() { hmacSecret = GenerateSecret() fmt.Println("InitJWTService", hmacSecret) // TODO: This needs to be replaced with reading rsa keys, there needs to be a automatic generation of these if they do not exist } // Validate a jwt tokenstring func Validate(Token string) (bool, jwt.Token) { if len(hmacSecret) < 32 { panic("No Secret initialized") } token, err := jwt.Parse(Token, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } return hmacSecret, nil }) if err == nil && token.Valid { fmt.Println("Token is valid") return true, *token } fmt.Println("Token Validation failed") return false, *token } // CreateToken create a new jwt token with the provided claims func CreateToken(Claims jwt.MapClaims) string { // Create a new token object, specifying signing method and the claims // you would like it to contain. token := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims) // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSecret) if err != nil { fmt.Println(err.Error()) } return tokenString } func HashPassword(password string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) return string(bytes), err } func CheckPasswordHash(password, hash string) bool { // Interestingly this function costs around 800ms err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil }