small improvement to creating a jwt logic

This commit is contained in:
James Tombleson 2024-04-21 10:28:21 -07:00
parent e7f706b6e7
commit 8482afed8d

View File

@ -57,40 +57,28 @@ func (j JwtToken) hasScope(scope string) error {
} }
func (h *Handler) generateJwt(username, issuer string) (string, error) { func (h *Handler) generateJwt(username, issuer string) (string, error) {
return h.generateJwtWithExp(username, issuer, time.Now().Add(10 * time.Minute))
}
func (h *Handler) generateJwtWithExp(username, issuer string, expiresAt time.Time) (string, error) {
secret := []byte(h.Config.JwtSecret) secret := []byte(h.Config.JwtSecret)
// Anyone who wants to decrypt the key needs to use the same method // Anyone who wants to decrypt the key needs to use the same method
token := jwt.New(jwt.SigningMethodHS256) token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims) claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute) claims["exp"] = expiresAt
claims["authorized"] = true claims["authorized"] = true
claims["username"] = username claims["username"] = username
claims["iss"] = issuer claims["iss"] = issuer
var scopes []string var scopes []string
scopes = append(scopes, domain.ScopeRecipeRead) if (username == "admin") {
claims["scopes"] = scopes scopes = append(scopes, domain.ScopeAll)
claims["scopes"] = scopes
tokenString, err := token.SignedString(secret) } else {
if err != nil { scopes = append(scopes, domain.ScopeRecipeRead)
return "", err claims["scopes"] = scopes
} }
return tokenString, nil
}
func (h *Handler) generateAdminJwt(username string) (string, error) {
secret := []byte(h.Config.JwtSecret)
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute)
claims["authorized"] = true
claims["username"] = username
var scopes []string
scopes = append(scopes, domain.ScopeAll)
claims["scopes"] = scopes
tokenString, err := token.SignedString(secret) tokenString, err := token.SignedString(secret)
if err != nil { if err != nil {