69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var jwtSecret []byte
|
|
|
|
func SetJWTSecret(secret string) {
|
|
jwtSecret = []byte(secret)
|
|
}
|
|
|
|
func GetJWTSecret() []byte {
|
|
return jwtSecret
|
|
}
|
|
|
|
type Claims struct {
|
|
UserID int64 `json:"user_id"`
|
|
Email string `json:"email"`
|
|
Username string `json:"username"`
|
|
IsAdmin bool `json:"is_admin"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GenerateToken(userID int64, email, username string, isAdmin bool) (string, error) {
|
|
expirationTime := time.Now().Add(24 * time.Hour)
|
|
claims := &Claims{
|
|
UserID: userID,
|
|
Email: email,
|
|
Username: username,
|
|
IsAdmin: isAdmin,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString(jwtSecret)
|
|
}
|
|
|
|
func ValidateToken(tokenString string) (*Claims, error) {
|
|
claims := &Claims{}
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
return jwtSecret, nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
return nil, err
|
|
}
|
|
|
|
return claims, nil
|
|
}
|
|
|
|
type contextKey string
|
|
|
|
const userContextKey contextKey = "user"
|
|
|
|
func SetTestUser(ctx context.Context, claims *Claims) context.Context {
|
|
return context.WithValue(ctx, userContextKey, claims)
|
|
}
|
|
|
|
func GetUserFromContext(ctx context.Context) (*Claims, bool) {
|
|
claims, ok := ctx.Value(userContextKey).(*Claims)
|
|
return claims, ok
|
|
}
|