46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
|
|
package auth
|
||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/golang-jwt/jwt/v5"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Claims struct {
|
||
|
|
AdminID int `json:"admin_id"`
|
||
|
|
Email string `json:"email"`
|
||
|
|
jwt.RegisteredClaims
|
||
|
|
}
|
||
|
|
|
||
|
|
func SignAdmin(secret string, adminID int, email string, ttl time.Duration) (string, error) {
|
||
|
|
claims := Claims{
|
||
|
|
AdminID: adminID,
|
||
|
|
Email: email,
|
||
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
||
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
|
||
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||
|
|
Issuer: IssuerAdmin,
|
||
|
|
},
|
||
|
|
}
|
||
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
|
|
return t.SignedString([]byte(secret))
|
||
|
|
}
|
||
|
|
|
||
|
|
func ParseAdmin(secret, token string) (*Claims, error) {
|
||
|
|
claims := &Claims{}
|
||
|
|
parsed, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) {
|
||
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||
|
|
return nil, errors.New("unexpected signing method")
|
||
|
|
}
|
||
|
|
return []byte(secret), nil
|
||
|
|
})
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
if !parsed.Valid || claims.Issuer != IssuerAdmin || claims.AdminID <= 0 {
|
||
|
|
return nil, errors.New("invalid token")
|
||
|
|
}
|
||
|
|
return claims, nil
|
||
|
|
}
|