Merge branch 'authorizerdev/authorizer:main' into main
This commit is contained in:
44
server/resolvers/enable_access.go
Normal file
44
server/resolvers/enable_access.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/db"
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
"github.com/authorizerdev/authorizer/server/token"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
)
|
||||
|
||||
// EnableAccessResolver is a resolver for enabling user access
|
||||
func EnableAccessResolver(ctx context.Context, params model.UpdateAccessInput) (*model.Response, error) {
|
||||
gc, err := utils.GinContextFromContext(ctx)
|
||||
var res *model.Response
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
if !token.IsSuperAdmin(gc) {
|
||||
return res, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
user, err := db.Provider.GetUserByID(params.UserID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
user.RevokedTimestamp = nil
|
||||
|
||||
user, err = db.Provider.UpdateUser(user)
|
||||
if err != nil {
|
||||
log.Println("error updating user:", err)
|
||||
return res, err
|
||||
}
|
||||
|
||||
res = &model.Response{
|
||||
Message: `user access enabled successfully`,
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
@@ -54,6 +54,7 @@ func EnvResolver(ctx context.Context) (*model.Env, error) {
|
||||
disableBasicAuthentication := store.BoolEnv[constants.EnvKeyDisableBasicAuthentication]
|
||||
disableMagicLinkLogin := store.BoolEnv[constants.EnvKeyDisableMagicLinkLogin]
|
||||
disableLoginPage := store.BoolEnv[constants.EnvKeyDisableLoginPage]
|
||||
disableSignUp := store.BoolEnv[constants.EnvKeyDisableSignUp]
|
||||
roles := store.SliceEnv[constants.EnvKeyRoles]
|
||||
defaultRoles := store.SliceEnv[constants.EnvKeyDefaultRoles]
|
||||
protectedRoles := store.SliceEnv[constants.EnvKeyProtectedRoles]
|
||||
@@ -94,6 +95,7 @@ func EnvResolver(ctx context.Context) (*model.Env, error) {
|
||||
DisableBasicAuthentication: &disableBasicAuthentication,
|
||||
DisableMagicLinkLogin: &disableMagicLinkLogin,
|
||||
DisableLoginPage: &disableLoginPage,
|
||||
DisableSignUp: &disableSignUp,
|
||||
Roles: roles,
|
||||
ProtectedRoles: protectedRoles,
|
||||
DefaultRoles: defaultRoles,
|
||||
|
@@ -43,7 +43,7 @@ func ForgotPasswordResolver(ctx context.Context, params model.ForgotPasswordInpu
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
redirectURL := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
|
||||
redirectURL := utils.GetAppURL(gc) + "/reset-password"
|
||||
if params.RedirectURI != nil {
|
||||
redirectURL = *params.RedirectURI
|
||||
}
|
||||
|
60
server/resolvers/generate_jwt_keys.go
Normal file
60
server/resolvers/generate_jwt_keys.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/crypto"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
"github.com/authorizerdev/authorizer/server/token"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
)
|
||||
|
||||
// GenerateJWTKeysResolver mutation to generate new jwt keys
|
||||
func GenerateJWTKeysResolver(ctx context.Context, params model.GenerateJWTKeysInput) (*model.GenerateJWTKeysResponse, error) {
|
||||
gc, err := utils.GinContextFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !token.IsSuperAdmin(gc) {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
clientID := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyClientID)
|
||||
if crypto.IsHMACA(params.Type) {
|
||||
secret, _, err := crypto.NewHMACKey(params.Type, clientID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &model.GenerateJWTKeysResponse{
|
||||
Secret: &secret,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if crypto.IsRSA(params.Type) {
|
||||
_, privateKey, publicKey, _, err := crypto.NewRSAKey(params.Type, clientID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &model.GenerateJWTKeysResponse{
|
||||
PrivateKey: &privateKey,
|
||||
PublicKey: &publicKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
if crypto.IsECDSA(params.Type) {
|
||||
_, privateKey, publicKey, _, err := crypto.NewECDSAKey(params.Type, clientID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &model.GenerateJWTKeysResponse{
|
||||
PrivateKey: &privateKey,
|
||||
PublicKey: &publicKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid algorithm")
|
||||
}
|
135
server/resolvers/invite_members.go
Normal file
135
server/resolvers/invite_members.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/db"
|
||||
"github.com/authorizerdev/authorizer/server/db/models"
|
||||
emailservice "github.com/authorizerdev/authorizer/server/email"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
"github.com/authorizerdev/authorizer/server/token"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
)
|
||||
|
||||
// InviteMembersResolver resolver to invite members
|
||||
func InviteMembersResolver(ctx context.Context, params model.InviteMemberInput) (*model.Response, error) {
|
||||
gc, err := utils.GinContextFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !token.IsSuperAdmin(gc) {
|
||||
return nil, errors.New("unauthorized")
|
||||
}
|
||||
|
||||
// this feature is only allowed if email server is configured
|
||||
if envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableEmailVerification) {
|
||||
return nil, errors.New("email sending is disabled")
|
||||
}
|
||||
|
||||
if envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableBasicAuthentication) && envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableMagicLinkLogin) {
|
||||
return nil, errors.New("either basic authentication or magic link login is required")
|
||||
}
|
||||
|
||||
// filter valid emails
|
||||
emails := []string{}
|
||||
for _, email := range params.Emails {
|
||||
if utils.IsValidEmail(email) {
|
||||
emails = append(emails, email)
|
||||
}
|
||||
}
|
||||
|
||||
if len(emails) == 0 {
|
||||
return nil, errors.New("no valid emails found")
|
||||
}
|
||||
|
||||
// TODO: optimise to use like query instead of looping through emails and getting user individually
|
||||
// for each emails check if emails exists in db
|
||||
newEmails := []string{}
|
||||
for _, email := range emails {
|
||||
_, err := db.Provider.GetUserByEmail(email)
|
||||
if err != nil {
|
||||
log.Printf("%s user not found. inviting user.", email)
|
||||
newEmails = append(newEmails, email)
|
||||
} else {
|
||||
log.Println("%s user already exists. skipping.", email)
|
||||
}
|
||||
}
|
||||
|
||||
if len(newEmails) == 0 {
|
||||
return nil, errors.New("all emails already exist")
|
||||
}
|
||||
|
||||
// invite new emails
|
||||
for _, email := range newEmails {
|
||||
|
||||
user := models.User{
|
||||
Email: email,
|
||||
Roles: strings.Join(envstore.EnvStoreObj.GetSliceStoreEnvVariable(constants.EnvKeyDefaultRoles), ","),
|
||||
}
|
||||
hostname := utils.GetHost(gc)
|
||||
verifyEmailURL := hostname + "/verify_email"
|
||||
appURL := utils.GetAppURL(gc)
|
||||
|
||||
redirectURL := appURL
|
||||
if params.RedirectURI != nil {
|
||||
redirectURL = *params.RedirectURI
|
||||
}
|
||||
|
||||
_, nonceHash, err := utils.GenerateNonce()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
verificationToken, err := token.CreateVerificationToken(email, constants.VerificationTypeForgotPassword, hostname, nonceHash, redirectURL)
|
||||
if err != nil {
|
||||
log.Println(`error generating token`, err)
|
||||
}
|
||||
|
||||
verificationRequest := models.VerificationRequest{
|
||||
Token: verificationToken,
|
||||
ExpiresAt: time.Now().Add(time.Minute * 30).Unix(),
|
||||
Email: email,
|
||||
Nonce: nonceHash,
|
||||
RedirectURI: redirectURL,
|
||||
}
|
||||
|
||||
// use magic link login if that option is on
|
||||
if !envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableMagicLinkLogin) {
|
||||
user.SignupMethods = constants.SignupMethodMagicLinkLogin
|
||||
verificationRequest.Identifier = constants.VerificationTypeMagicLinkLogin
|
||||
} else {
|
||||
// use basic authentication if that option is on
|
||||
user.SignupMethods = constants.SignupMethodBasicAuth
|
||||
verificationRequest.Identifier = constants.VerificationTypeForgotPassword
|
||||
|
||||
verifyEmailURL = appURL + "/setup-password"
|
||||
|
||||
}
|
||||
|
||||
user, err = db.Provider.AddUser(user)
|
||||
if err != nil {
|
||||
log.Printf("error inviting user: %s, err: %v", email, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = db.Provider.AddVerificationRequest(verificationRequest)
|
||||
if err != nil {
|
||||
log.Printf("error inviting user: %s, err: %v", email, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go emailservice.InviteEmail(email, verificationToken, verifyEmailURL, redirectURL)
|
||||
}
|
||||
|
||||
return &model.Response{
|
||||
Message: fmt.Sprintf("%d user(s) invited successfully.", len(newEmails)),
|
||||
}, nil
|
||||
}
|
@@ -36,6 +36,10 @@ func LoginResolver(ctx context.Context, params model.LoginInput) (*model.AuthRes
|
||||
return res, fmt.Errorf(`user with this email not found`)
|
||||
}
|
||||
|
||||
if user.RevokedTimestamp != nil {
|
||||
return res, fmt.Errorf(`user access has been revoked`)
|
||||
}
|
||||
|
||||
if !strings.Contains(user.SignupMethods, constants.SignupMethodBasicAuth) {
|
||||
return res, fmt.Errorf(`user has not signed up email & password`)
|
||||
}
|
||||
|
@@ -43,8 +43,11 @@ func MagicLinkLoginResolver(ctx context.Context, params model.MagicLinkLoginInpu
|
||||
|
||||
// find user with email
|
||||
existingUser, err := db.Provider.GetUserByEmail(params.Email)
|
||||
|
||||
if err != nil {
|
||||
if envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableSignUp) {
|
||||
return res, fmt.Errorf(`signup is disabled for this instance`)
|
||||
}
|
||||
|
||||
user.SignupMethods = constants.SignupMethodMagicLinkLogin
|
||||
// define roles for new user
|
||||
if len(params.Roles) > 0 {
|
||||
@@ -67,6 +70,10 @@ func MagicLinkLoginResolver(ctx context.Context, params model.MagicLinkLoginInpu
|
||||
// 2. user has not signed up for one of the available role but trying to signup.
|
||||
// Need to modify roles in this case
|
||||
|
||||
if user.RevokedTimestamp != nil {
|
||||
return res, fmt.Errorf(`user access has been revoked`)
|
||||
}
|
||||
|
||||
// find the unassigned roles
|
||||
if len(params.Roles) <= 0 {
|
||||
inputRoles = envstore.EnvStoreObj.GetSliceStoreEnvVariable(constants.EnvKeyDefaultRoles)
|
||||
@@ -123,7 +130,7 @@ func MagicLinkLoginResolver(ctx context.Context, params model.MagicLinkLoginInpu
|
||||
if params.Scope != nil && len(params.Scope) > 0 {
|
||||
redirectURLParams = redirectURLParams + "&scope=" + strings.Join(params.Scope, " ")
|
||||
}
|
||||
redirectURL := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
|
||||
redirectURL := utils.GetAppURL(gc)
|
||||
if params.RedirectURI != nil {
|
||||
redirectURL = *params.RedirectURI
|
||||
}
|
||||
|
@@ -35,6 +35,10 @@ func ResetPasswordResolver(ctx context.Context, params model.ResetPasswordInput)
|
||||
return res, fmt.Errorf(`passwords don't match`)
|
||||
}
|
||||
|
||||
if !utils.IsValidPassword(params.Password) {
|
||||
return res, fmt.Errorf(`password is not valid. It needs to be at least 6 characters long and contain at least one number, one uppercase letter, one lowercase letter and one special character`)
|
||||
}
|
||||
|
||||
// verify if token exists in db
|
||||
hostname := utils.GetHost(gc)
|
||||
claim, err := token.ParseJWTToken(params.Token, hostname, verificationRequest.Nonce, verificationRequest.Email)
|
||||
|
49
server/resolvers/revoke_access.go
Normal file
49
server/resolvers/revoke_access.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/db"
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
"github.com/authorizerdev/authorizer/server/sessionstore"
|
||||
"github.com/authorizerdev/authorizer/server/token"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
)
|
||||
|
||||
// RevokeAccessResolver is a resolver for revoking user access
|
||||
func RevokeAccessResolver(ctx context.Context, params model.UpdateAccessInput) (*model.Response, error) {
|
||||
gc, err := utils.GinContextFromContext(ctx)
|
||||
var res *model.Response
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
if !token.IsSuperAdmin(gc) {
|
||||
return res, fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
user, err := db.Provider.GetUserByID(params.UserID)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
user.RevokedTimestamp = &now
|
||||
|
||||
user, err = db.Provider.UpdateUser(user)
|
||||
if err != nil {
|
||||
log.Println("error updating user:", err)
|
||||
return res, err
|
||||
}
|
||||
|
||||
go sessionstore.DeleteAllUserSession(fmt.Sprintf("%x", user.ID))
|
||||
|
||||
res = &model.Response{
|
||||
Message: `user access revoked successfully`,
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
@@ -2,7 +2,9 @@ package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/cookie"
|
||||
@@ -25,13 +27,15 @@ func SessionResolver(ctx context.Context, params *model.SessionQueryInput) (*mod
|
||||
|
||||
sessionToken, err := cookie.GetSession(gc)
|
||||
if err != nil {
|
||||
return res, err
|
||||
log.Println("error getting session token:", err)
|
||||
return res, errors.New("unauthorized")
|
||||
}
|
||||
|
||||
// get session from cookie
|
||||
claims, err := token.ValidateBrowserSession(gc, sessionToken)
|
||||
if err != nil {
|
||||
return res, err
|
||||
log.Println("session validation failed:", err)
|
||||
return res, errors.New("unauthorized")
|
||||
}
|
||||
userID := claims.Subject
|
||||
user, err := db.Provider.GetUserByID(userID)
|
||||
|
@@ -28,13 +28,22 @@ func SignupResolver(ctx context.Context, params model.SignUpInput) (*model.AuthR
|
||||
return res, err
|
||||
}
|
||||
|
||||
if envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableSignUp) {
|
||||
return res, fmt.Errorf(`signup is disabled for this instance`)
|
||||
}
|
||||
|
||||
if envstore.EnvStoreObj.GetBoolStoreEnvVariable(constants.EnvKeyDisableBasicAuthentication) {
|
||||
return res, fmt.Errorf(`basic authentication is disabled for this instance`)
|
||||
}
|
||||
|
||||
if params.ConfirmPassword != params.Password {
|
||||
return res, fmt.Errorf(`password and confirm password does not match`)
|
||||
}
|
||||
|
||||
if !utils.IsValidPassword(params.Password) {
|
||||
return res, fmt.Errorf(`password is not valid. It needs to be at least 6 characters long and contain at least one number, one uppercase letter, one lowercase letter and one special character`)
|
||||
}
|
||||
|
||||
params.Email = strings.ToLower(params.Email)
|
||||
|
||||
if !utils.IsValidEmail(params.Email) {
|
||||
@@ -128,7 +137,10 @@ func SignupResolver(ctx context.Context, params model.SignUpInput) (*model.AuthR
|
||||
return res, err
|
||||
}
|
||||
verificationType := constants.VerificationTypeBasicAuthSignup
|
||||
redirectURL := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
|
||||
redirectURL := utils.GetAppURL(gc)
|
||||
if params.RedirectURI != nil {
|
||||
redirectURL = *params.RedirectURI
|
||||
}
|
||||
verificationToken, err := token.CreateVerificationToken(params.Email, verificationType, hostname, nonceHash, redirectURL)
|
||||
if err != nil {
|
||||
return res, err
|
||||
|
@@ -53,11 +53,19 @@ func UpdateEnvResolver(ctx context.Context, params model.UpdateEnvInput) (*model
|
||||
}
|
||||
|
||||
if isJWTUpdated {
|
||||
// use to reset when type is changed from rsa, edsa -> hmac or vice a versa
|
||||
defaultSecret := ""
|
||||
defaultPublicKey := ""
|
||||
defaultPrivateKey := ""
|
||||
// check if jwt secret is provided
|
||||
if crypto.IsHMACA(algo) {
|
||||
if params.JwtSecret == nil {
|
||||
return res, fmt.Errorf("jwt secret is required for HMAC algorithm")
|
||||
}
|
||||
|
||||
// reset public key and private key
|
||||
params.JwtPrivateKey = &defaultPrivateKey
|
||||
params.JwtPublicKey = &defaultPublicKey
|
||||
}
|
||||
|
||||
if crypto.IsRSA(algo) {
|
||||
@@ -65,6 +73,8 @@ func UpdateEnvResolver(ctx context.Context, params model.UpdateEnvInput) (*model
|
||||
return res, fmt.Errorf("jwt private and public key is required for RSA (PKCS1) / ECDSA algorithm")
|
||||
}
|
||||
|
||||
// reset the jwt secret
|
||||
params.JwtSecret = &defaultSecret
|
||||
_, err = crypto.ParseRsaPrivateKeyFromPemStr(*params.JwtPrivateKey)
|
||||
if err != nil {
|
||||
return res, err
|
||||
@@ -81,6 +91,8 @@ func UpdateEnvResolver(ctx context.Context, params model.UpdateEnvInput) (*model
|
||||
return res, fmt.Errorf("jwt private and public key is required for RSA (PKCS1) / ECDSA algorithm")
|
||||
}
|
||||
|
||||
// reset the jwt secret
|
||||
params.JwtSecret = &defaultSecret
|
||||
_, err = crypto.ParseEcdsaPrivateKeyFromPemStr(*params.JwtPrivateKey)
|
||||
if err != nil {
|
||||
return res, err
|
||||
|
@@ -134,7 +134,7 @@ func UpdateProfileResolver(ctx context.Context, params model.UpdateProfileInput)
|
||||
return res, err
|
||||
}
|
||||
verificationType := constants.VerificationTypeUpdateEmail
|
||||
redirectURL := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
|
||||
redirectURL := utils.GetAppURL(gc)
|
||||
verificationToken, err := token.CreateVerificationToken(newEmail, verificationType, hostname, nonceHash, redirectURL)
|
||||
if err != nil {
|
||||
log.Println(`error generating token`, err)
|
||||
|
@@ -106,7 +106,7 @@ func UpdateUserResolver(ctx context.Context, params model.UpdateUserInput) (*mod
|
||||
return res, err
|
||||
}
|
||||
verificationType := constants.VerificationTypeUpdateEmail
|
||||
redirectURL := envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
|
||||
redirectURL := utils.GetAppURL(gc)
|
||||
verificationToken, err := token.CreateVerificationToken(newEmail, verificationType, hostname, nonceHash, redirectURL)
|
||||
if err != nil {
|
||||
log.Println(`error generating token`, err)
|
||||
@@ -154,6 +154,8 @@ func UpdateUserResolver(ctx context.Context, params model.UpdateUserInput) (*mod
|
||||
return res, err
|
||||
}
|
||||
|
||||
createdAt := user.CreatedAt
|
||||
updatedAt := user.UpdatedAt
|
||||
res = &model.User{
|
||||
ID: params.ID,
|
||||
Email: user.Email,
|
||||
@@ -161,8 +163,8 @@ func UpdateUserResolver(ctx context.Context, params model.UpdateUserInput) (*mod
|
||||
GivenName: user.GivenName,
|
||||
FamilyName: user.FamilyName,
|
||||
Roles: strings.Split(user.Roles, ","),
|
||||
CreatedAt: &user.CreatedAt,
|
||||
UpdatedAt: &user.UpdatedAt,
|
||||
CreatedAt: &createdAt,
|
||||
UpdatedAt: &updatedAt,
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
86
server/resolvers/validate_jwt_token.go
Normal file
86
server/resolvers/validate_jwt_token.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package resolvers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
"github.com/authorizerdev/authorizer/server/sessionstore"
|
||||
"github.com/authorizerdev/authorizer/server/token"
|
||||
"github.com/authorizerdev/authorizer/server/utils"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
// ValidateJwtTokenResolver is used to validate a jwt token without its rotation
|
||||
// this can be used at API level (backend)
|
||||
// it can validate:
|
||||
// access_token
|
||||
// id_token
|
||||
// refresh_token
|
||||
func ValidateJwtTokenResolver(ctx context.Context, params model.ValidateJWTTokenInput) (*model.ValidateJWTTokenResponse, error) {
|
||||
gc, err := utils.GinContextFromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tokenType := params.TokenType
|
||||
if tokenType != "access_token" && tokenType != "refresh_token" && tokenType != "id_token" {
|
||||
return nil, errors.New("invalid token type")
|
||||
}
|
||||
|
||||
userID := ""
|
||||
nonce := ""
|
||||
// access_token and refresh_token should be validated from session store as well
|
||||
if tokenType == "access_token" || tokenType == "refresh_token" {
|
||||
savedSession := sessionstore.GetState(params.Token)
|
||||
if savedSession == "" {
|
||||
return &model.ValidateJWTTokenResponse{
|
||||
IsValid: false,
|
||||
}, nil
|
||||
}
|
||||
savedSessionSplit := strings.Split(savedSession, "@")
|
||||
nonce = savedSessionSplit[0]
|
||||
userID = savedSessionSplit[1]
|
||||
}
|
||||
|
||||
hostname := utils.GetHost(gc)
|
||||
var claimRoles []string
|
||||
var claims jwt.MapClaims
|
||||
|
||||
// we cannot validate sub and nonce in case of id_token as that token is not persisted in session store
|
||||
if userID != "" && nonce != "" {
|
||||
claims, err = token.ParseJWTToken(params.Token, hostname, nonce, userID)
|
||||
if err != nil {
|
||||
return &model.ValidateJWTTokenResponse{
|
||||
IsValid: false,
|
||||
}, nil
|
||||
}
|
||||
} else {
|
||||
claims, err = token.ParseJWTTokenWithoutNonce(params.Token, hostname)
|
||||
if err != nil {
|
||||
return &model.ValidateJWTTokenResponse{
|
||||
IsValid: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
claimRolesInterface := claims["roles"]
|
||||
roleSlice := utils.ConvertInterfaceToSlice(claimRolesInterface)
|
||||
for _, v := range roleSlice {
|
||||
claimRoles = append(claimRoles, v.(string))
|
||||
}
|
||||
|
||||
if params.Roles != nil && len(params.Roles) > 0 {
|
||||
for _, v := range params.Roles {
|
||||
if !utils.StringSliceContains(claimRoles, v) {
|
||||
return nil, fmt.Errorf(`unauthorized`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &model.ValidateJWTTokenResponse{
|
||||
IsValid: true,
|
||||
}, nil
|
||||
}
|
Reference in New Issue
Block a user