69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package controllers
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/beego/beego/v2/core/logs"
|
|
"github.com/dgrijalva/jwt-go"
|
|
)
|
|
|
|
const mySuperSecretKey = "jdnfksdmfksd"
|
|
|
|
func CreateToken(userId string) (string, error) {
|
|
var err error
|
|
//Creating Access Token
|
|
// os.Setenv("ACCESS_SECRET", "jdnfksdmfksd") //this should be in an env file
|
|
atClaims := jwt.MapClaims{}
|
|
atClaims["authorized"] = true
|
|
atClaims["user_id"] = userId
|
|
atClaims["exp"] = time.Now().UTC().Add(time.Hour * 15).Unix()
|
|
at := jwt.NewWithClaims(jwt.SigningMethodHS256, atClaims)
|
|
token, err := at.SignedString([]byte(mySuperSecretKey))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return token, nil
|
|
}
|
|
|
|
func IsValidToken(jwtToken string) (*jwt.Token, error) {
|
|
token, err := jwt.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
|
|
//TODO: Validate expected algorithm
|
|
return []byte(mySuperSecretKey), nil
|
|
})
|
|
|
|
var message string
|
|
|
|
if err == nil && token.Valid {
|
|
return token, nil
|
|
} else if ve, ok := err.(*jwt.ValidationError); ok {
|
|
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
|
|
message = "Token " + jwtToken + " is not even a token"
|
|
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
|
|
message = "Token is either expired or not active yet"
|
|
} else {
|
|
message = "Couldn't handle this token: " + err.Error()
|
|
}
|
|
}
|
|
|
|
logs.Debug(message)
|
|
return nil, errors.New(message)
|
|
}
|
|
|
|
func GetUsernameFromToken(token string) (string, error) {
|
|
|
|
tokenObj, err := IsValidToken(token)
|
|
if err != nil {
|
|
logs.Debug(err)
|
|
return "", err
|
|
}
|
|
|
|
if claims, ok := tokenObj.Claims.(jwt.MapClaims); ok {
|
|
return claims["user_id"].(string), nil
|
|
}
|
|
|
|
logs.Debug("Unknow JWT error")
|
|
return "", errors.New("Unknow JWT error")
|
|
|
|
}
|