You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/libs/auth/jwt.go

94 lines
2.1 KiB
Go

7 months ago
//
// jwt.go
// Copyright (C) 2024 veypi <i@veypi.com>
// 2024-09-23 18:28
// Distributed under terms of the MIT license.
//
package auth
import (
"errors"
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
6 months ago
"github.com/veypi/OneAuth/cfg"
"github.com/veypi/OneAuth/errs"
7 months ago
"github.com/veypi/OneBD/rest"
)
func GenJwt(claim *Claims) (string, error) {
return GenJwtWithKey(claim, cfg.Config.Key)
}
func GenJwtWithKey(claim *Claims, key string) (string, error) {
if claim.ExpiresAt == nil {
claim.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour))
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
return token.SignedString([]byte(key))
}
func ParseJwt(tokenString string) (*Claims, error) {
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(cfg.Config.Key), nil
})
if errors.Is(err, jwt.ErrTokenExpired) {
return nil, errs.AuthExpired
}
if err != nil || !token.Valid {
return nil, errs.AuthInvalid
}
return claims, nil
}
func checkJWT(x *rest.X) (*Claims, error) {
7 months ago
authHeader := x.Request.Header.Get("Authorization")
if authHeader == "" {
authHeader = x.Request.URL.Query().Get("Authorization")
if authHeader == "" {
return nil, errs.AuthNotFound
}
7 months ago
}
// Token is typically in the format "Bearer <token>"
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
// Parse the token
claims, err := ParseJwt(tokenString)
if err != nil {
return nil, err
}
x.Set("token", claims)
7 months ago
return claims, nil
}
func CheckJWT(x *rest.X) (any, error) {
return checkJWT(x)
}
func Check(target string, pid string, l AuthLevel) func(x *rest.X) (any, error) {
return func(x *rest.X) (any, error) {
claims, err := checkJWT(x)
7 months ago
if err != nil {
return nil, err
// return nil, err
7 months ago
}
tid := ""
if pid != "" {
7 months ago
tid = x.Params.Get(pid)
7 months ago
}
if !claims.Access.Check(target, tid, l) {
// return nil, errs.AuthNoPerm
7 months ago
}
return claims, nil
7 months ago
}
}