go-cook/internal/handlers/v1/jwt.go

102 lines
2.1 KiB
Go
Raw Normal View History

2024-03-31 18:09:24 -07:00
package v1
import (
"errors"
"strings"
"time"
"git.jamestombleson.com/jtom38/go-cook/internal/domain"
2024-04-05 17:50:29 -07:00
2024-03-31 18:09:24 -07:00
"github.com/golang-jwt/jwt/v5"
)
type JwtToken struct {
Exp time.Time `json:"exp"`
Iss string `json:"iss"`
Authorized bool `json:"authorized"`
UserName string `json:"username"`
Scopes []string `json:"scopes"`
jwt.RegisteredClaims
}
func (j JwtToken) IsValid(scope string) error {
err := j.hasExpired()
if err != nil {
return err
}
err = j.hasScope(scope)
if err != nil {
return err
}
return nil
}
func (j JwtToken) hasExpired() error {
// Check to see if the token has expired
hasExpired := j.Exp.Compare(time.Now())
if hasExpired == -1 {
return errors.New(ErrJwtExpired)
}
return nil
}
func (j JwtToken) hasScope(scope string) error {
// they have the scope to access everything, so let them pass.
if strings.Contains(domain.ScopeAll, scope) {
return nil
}
for _, s := range j.Scopes {
if strings.Contains(s, scope) {
return nil
}
}
return errors.New(ErrJwtScopeMissing)
}
2024-04-13 11:54:54 -07:00
func (h *Handler) generateJwt(username, issuer string) (string, error) {
2024-03-31 18:09:24 -07:00
secret := []byte(h.Config.JwtSecret)
2024-04-13 11:54:54 -07:00
// Anyone who wants to decrypt the key needs to use the same method
2024-03-31 18:09:24 -07:00
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["exp"] = time.Now().Add(10 * time.Minute)
claims["authorized"] = true
claims["username"] = username
2024-04-13 11:54:54 -07:00
claims["iss"] = issuer
2024-03-31 18:09:24 -07:00
var scopes []string
scopes = append(scopes, domain.ScopeRecipeRead)
claims["scopes"] = scopes
tokenString, err := token.SignedString(secret)
if err != nil {
return "", err
}
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
2024-04-03 16:11:46 -07:00
var scopes []string
scopes = append(scopes, domain.ScopeAll)
claims["scopes"] = scopes
2024-03-31 18:09:24 -07:00
tokenString, err := token.SignedString(secret)
if err != nil {
return "", err
}
return tokenString, nil
}