authorizer/server/utils/auth_token.go

162 lines
4.6 KiB
Go
Raw Normal View History

package utils
import (
"encoding/json"
"fmt"
2021-07-15 09:43:00 +00:00
"log"
2021-12-31 11:33:37 +00:00
"net/url"
"os"
2021-07-15 09:43:00 +00:00
"strings"
"time"
2021-07-23 16:27:44 +00:00
"github.com/authorizerdev/authorizer/server/constants"
2022-01-21 08:04:04 +00:00
"github.com/authorizerdev/authorizer/server/db/models"
2022-01-17 06:02:13 +00:00
"github.com/authorizerdev/authorizer/server/envstore"
2021-07-15 09:43:00 +00:00
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
2021-10-29 16:11:47 +00:00
"github.com/robertkrimen/otto"
2021-12-31 08:58:00 +00:00
"golang.org/x/crypto/bcrypt"
)
2022-01-17 06:02:13 +00:00
// CreateAuthToken util to create JWT token, based on
// user information, roles config and CUSTOM_ACCESS_TOKEN_SCRIPT
2022-01-21 08:04:04 +00:00
func CreateAuthToken(user models.User, tokenType string, roles []string) (string, int64, error) {
t := jwt.New(jwt.GetSigningMethod(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtType)))
expiryBound := time.Hour
2022-01-17 06:02:13 +00:00
if tokenType == constants.TokenTypeRefreshToken {
2021-07-15 12:02:55 +00:00
// expires in 1 year
expiryBound = time.Hour * 8760
}
2021-07-15 12:02:55 +00:00
expiresAt := time.Now().Add(expiryBound).Unix()
2021-12-24 01:05:02 +00:00
resUser := GetResponseUserData(user)
userBytes, _ := json.Marshal(&resUser)
var userMap map[string]interface{}
json.Unmarshal(userBytes, &userMap)
claimKey := envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtRoleClaim)
customClaims := jwt.MapClaims{
2022-01-17 06:02:13 +00:00
"exp": expiresAt,
"iat": time.Now().Unix(),
"token_type": tokenType,
"allowed_roles": strings.Split(user.Roles, ","),
claimKey: roles,
}
for k, v := range userMap {
if k != "roles" {
customClaims[k] = v
}
}
// check for the extra access token script
2022-01-17 06:02:13 +00:00
accessTokenScript := os.Getenv(constants.EnvKeyCustomAccessTokenScript)
if accessTokenScript != "" {
2021-10-29 16:11:47 +00:00
vm := otto.New()
claimBytes, _ := json.Marshal(customClaims)
2021-10-29 16:11:47 +00:00
vm.Run(fmt.Sprintf(`
var user = %s;
var tokenPayload = %s;
var customFunction = %s;
var functionRes = JSON.stringify(customFunction(user, tokenPayload));
`, string(userBytes), string(claimBytes), accessTokenScript))
2021-10-29 16:11:47 +00:00
val, err := vm.Get("functionRes")
if err != nil {
log.Println("error getting custom access token script:", err)
} else {
extraPayload := make(map[string]interface{})
err = json.Unmarshal([]byte(fmt.Sprintf("%s", val)), &extraPayload)
if err != nil {
log.Println("error converting accessTokenScript response to map:", err)
} else {
for k, v := range extraPayload {
customClaims[k] = v
}
}
}
}
t.Claims = customClaims
token, err := t.SignedString([]byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)))
2021-07-15 12:02:55 +00:00
if err != nil {
return "", 0, err
}
2021-07-15 12:02:55 +00:00
return token, expiresAt, nil
}
2021-07-15 09:43:00 +00:00
2022-01-17 06:02:13 +00:00
// GetAuthToken helps in getting the JWT token from the
// request cookie or authorization header
2021-07-15 09:43:00 +00:00
func GetAuthToken(gc *gin.Context) (string, error) {
2021-07-27 12:16:02 +00:00
token, err := GetCookie(gc)
if err != nil || token == "" {
2021-07-15 09:43:00 +00:00
// try to check in auth header for cookie
auth := gc.Request.Header.Get("Authorization")
if auth == "" {
return "", fmt.Errorf(`unauthorized`)
2021-07-15 09:43:00 +00:00
}
token = strings.TrimPrefix(auth, "Bearer ")
}
return token, nil
}
2022-01-17 06:02:13 +00:00
// VerifyAuthToken helps in verifying the JWT token
func VerifyAuthToken(token string) (map[string]interface{}, error) {
var res map[string]interface{}
claims := jwt.MapClaims{}
2021-07-15 09:43:00 +00:00
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)), nil
2021-07-15 09:43:00 +00:00
})
if err != nil {
return res, err
2021-07-15 09:43:00 +00:00
}
// claim parses exp & iat into float 64 with e^10,
// but we expect it to be int64
// hence we need to assert interface and convert to int64
intExp := int64(claims["exp"].(float64))
intIat := int64(claims["iat"].(float64))
data, _ := json.Marshal(claims)
json.Unmarshal(data, &res)
res["exp"] = intExp
res["iat"] = intIat
return res, nil
2021-07-15 09:43:00 +00:00
}
2021-12-30 04:31:51 +00:00
2022-01-17 06:02:13 +00:00
// CreateAdminAuthToken creates the admin token based on secret key
func CreateAdminAuthToken(tokenType string, c *gin.Context) (string, error) {
return EncryptPassword(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret))
2021-12-30 04:31:51 +00:00
}
2021-12-31 08:22:10 +00:00
2022-01-17 06:02:13 +00:00
// GetAdminAuthToken helps in getting the admin token from the request cookie
2021-12-31 08:22:10 +00:00
func GetAdminAuthToken(gc *gin.Context) (string, error) {
token, err := GetAdminCookie(gc)
if err != nil || token == "" {
2022-01-09 12:05:37 +00:00
return "", fmt.Errorf("unauthorized")
2021-12-31 08:22:10 +00:00
}
2021-12-31 11:33:37 +00:00
// cookie escapes special characters like $
// hence we need to unescape before comparing
decodedValue, err := url.QueryUnescape(token)
if err != nil {
return "", err
}
err = bcrypt.CompareHashAndPassword([]byte(decodedValue), []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)))
2021-12-31 11:33:37 +00:00
log.Println("error comparing hash:", err)
if err != nil {
return "", fmt.Errorf(`unauthorized`)
}
2021-12-31 08:22:10 +00:00
return token, nil
}