multitenantStack/services/tokenTools/tokenTools.go

79 lines
1.9 KiB
Go
Raw Normal View History

package tokenTools
2018-11-07 10:10:51 +00:00
import (
"crypto/rand"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
2018-11-12 10:42:39 +00:00
"golang.org/x/crypto/bcrypt"
2018-11-07 10:10:51 +00:00
)
var hmacSecret []byte
// GenerateSecret generate the secret to verify JWTs
2018-11-07 10:10:51 +00:00
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() {
2018-11-07 10:10:51 +00:00
hmacSecret = GenerateSecret()
fmt.Println("InitJWTService", hmacSecret)
2018-11-07 10:10:51 +00:00
// 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
2018-11-07 10:10:51 +00:00
func Validate(Token string) (bool, jwt.Token) {
2018-11-12 10:42:39 +00:00
if len(hmacSecret) < 32 {
panic("No Secret initialized")
}
2018-11-07 10:10:51 +00:00
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 {
2018-11-07 10:10:51 +00:00
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
2018-11-07 10:10:51 +00:00
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
}
2018-11-12 10:42:39 +00:00
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
}