Bugfix: ensure that hmacsecret exists

This commit is contained in:
Lukas Bachschwell 2018-11-12 11:42:39 +01:00
parent 98f9e113d6
commit 4d857daf5d
2 changed files with 17 additions and 1 deletions

View File

@ -3,7 +3,7 @@ package main
import ( import (
_ "multitenantStack/routers" _ "multitenantStack/routers"
companydb "multitenantStack/services/companydb" companydb "multitenantStack/services/companydb"
tokenTools "multitenantStack/services/tokenTools" "multitenantStack/services/tokenTools"
"time" "time"
"github.com/astaxie/beego" "github.com/astaxie/beego"

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
) )
var hmacSecret []byte var hmacSecret []byte
@ -26,6 +27,10 @@ func InitTokenToolsService() {
// Validate a jwt tokenstring // Validate a jwt tokenstring
func Validate(Token string) (bool, jwt.Token) { 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) { token, err := jwt.Parse(Token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
@ -60,3 +65,14 @@ func CreateToken(Claims jwt.MapClaims) string {
return tokenString 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
}