authorizer/server/token/verification_token.go

52 lines
1.7 KiB
Go
Raw Normal View History

package token
2021-07-12 18:22:16 +00:00
import (
"time"
2021-07-23 16:27:44 +00:00
"github.com/authorizerdev/authorizer/server/constants"
2022-01-17 06:02:13 +00:00
"github.com/authorizerdev/authorizer/server/envstore"
2021-07-12 18:22:16 +00:00
"github.com/golang-jwt/jwt"
)
// VerificationRequestToken is the user info that is stored in the JWT of verification request
type VerificationRequestToken struct {
Email string `json:"email"`
Host string `json:"host"`
RedirectURL string `json:"redirect_url"`
2021-07-12 18:22:16 +00:00
}
2022-01-17 06:02:13 +00:00
// CustomClaim is the custom claim that is stored in the JWT of verification request
type CustomClaim struct {
2021-07-12 18:22:16 +00:00
*jwt.StandardClaims
TokenType string `json:"token_type"`
VerificationRequestToken
2021-07-12 18:22:16 +00:00
}
2022-01-17 06:02:13 +00:00
// CreateVerificationToken creates a verification JWT token
2022-01-31 06:05:24 +00:00
func CreateVerificationToken(email, tokenType, hostname string) (string, error) {
t := jwt.New(jwt.GetSigningMethod(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtType)))
2021-07-12 18:22:16 +00:00
t.Claims = &CustomClaim{
2021-07-12 18:22:16 +00:00
&jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Minute * 30).Unix(),
},
tokenType,
2022-01-31 06:05:24 +00:00
VerificationRequestToken{Email: email, Host: hostname, RedirectURL: envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)},
2021-07-12 18:22:16 +00:00
}
return t.SignedString([]byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)))
2021-07-12 18:22:16 +00:00
}
2022-01-17 06:02:13 +00:00
// VerifyVerificationToken verifies the verification JWT token
func VerifyVerificationToken(token string) (*CustomClaim, error) {
claims := &CustomClaim{}
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)), nil
})
if err != nil {
return claims, err
2021-07-12 18:22:16 +00:00
}
return claims, nil
2021-07-12 18:22:16 +00:00
}