56 lines
1.2 KiB
Go
56 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/go-chi/jwtauth/v5"
|
|
)
|
|
|
|
var TokenAuth *jwtauth.JWTAuth
|
|
|
|
// AuthResponse is the response structure for login/refresh endpoints
|
|
type AuthResponse struct {
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
func InitJWT(secret string) {
|
|
TokenAuth = jwtauth.New("HS256", []byte(secret), nil)
|
|
}
|
|
|
|
// GenerateToken creates a JWT with user_id and role
|
|
func GenerateToken(userID string, role string) (string, error) {
|
|
_, tokenString, err := TokenAuth.Encode(map[string]interface{}{
|
|
"user_id": userID,
|
|
"role": role,
|
|
"exp": time.Now().Add(30 * 24 * time.Hour).Unix(), // 30 days
|
|
})
|
|
return tokenString, err
|
|
}
|
|
|
|
// VerifyToken validates JWT and returns user_id and role
|
|
func VerifyToken(tokenString string, ctx context.Context) (userID string, role string, err error) {
|
|
token, err := TokenAuth.Decode(tokenString)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
claims, err := token.AsMap(ctx)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
|
|
userID, ok := claims["user_id"].(string)
|
|
if !ok {
|
|
return "", "", fmt.Errorf("invalid user_id claim")
|
|
}
|
|
|
|
role, ok = claims["role"].(string)
|
|
if !ok {
|
|
return "", "", fmt.Errorf("invalid role claim")
|
|
}
|
|
|
|
return userID, role, nil
|
|
}
|