61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type Claims struct {
|
|
StaffID string `json:"staff_id"`
|
|
Name string `json:"name"`
|
|
Role string `json:"role"`
|
|
Permissions []string `json:"permissions"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// GenerateAccessToken bakes the role's permission set into the token at
|
|
// login time (see auth.Login, which looks it up via a join to roles) —
|
|
// RequirePermission then checks the claim directly, no DB round-trip per
|
|
// request. A role's permissions changing takes effect on the holder's next
|
|
// login, same tradeoff RequireRole's plain role string already had.
|
|
func GenerateAccessToken(staffID, name, role string, permissions []string) (string, error) {
|
|
secret := os.Getenv("JWT_SECRET")
|
|
exp, err := time.ParseDuration(os.Getenv("JWT_EXPIRES_IN"))
|
|
if err != nil {
|
|
exp = 12 * time.Hour
|
|
}
|
|
claims := Claims{
|
|
StaffID: staffID,
|
|
Name: name,
|
|
Role: role,
|
|
Permissions: permissions,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(exp)),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(secret))
|
|
}
|
|
|
|
func ParseToken(tokenStr string) (*Claims, error) {
|
|
secret := os.Getenv("JWT_SECRET")
|
|
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
|
}
|
|
return []byte(secret), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
claims, ok := token.Claims.(*Claims)
|
|
if !ok || !token.Valid {
|
|
return nil, fmt.Errorf("invalid token")
|
|
}
|
|
return claims, nil
|
|
}
|