forked from Abdulkhalek-1/GoRing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.go
More file actions
98 lines (83 loc) · 2.67 KB
/
jwt.go
File metadata and controls
98 lines (83 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package auth
import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
)
var (
ErrInvalidToken = errors.New("invalid token")
ErrExpiredToken = errors.New("token expired")
ErrMissingClaim = errors.New("missing required claim")
)
// Claims represents the JWT claims we expect
type Claims struct {
Hash string `json:"hash"`
Name string `json:"name,omitempty"`
Username string `json:"username,omitempty"`
ImageProfile string `json:"image_profile,omitempty"`
UserType string `json:"user_type,omitempty"`
IsAdmin string `json:"is_admin,omitempty"`
jwt.RegisteredClaims
}
// UserInfo contains user profile data extracted from JWT
type UserInfo struct {
UserID string `json:"user_id"`
Name string `json:"name,omitempty"`
Username string `json:"username,omitempty"`
ImageProfile string `json:"image_profile,omitempty"`
}
// ValidateToken validates a JWT token and extracts user info from claims.
// Returns UserInfo on success, or an error describing the failure.
func ValidateToken(tokenString, secret string) (*UserInfo, error) {
if tokenString == "" {
return nil, ErrInvalidToken
}
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) {
// Validate signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
return nil, ErrExpiredToken
}
return nil, fmt.Errorf("%w: %v", ErrInvalidToken, err)
}
if !token.Valid {
return nil, ErrInvalidToken
}
claims, ok := token.Claims.(*Claims)
if !ok {
return nil, ErrInvalidToken
}
// Extract user_id from 'hash' claim
userID := claims.Hash
if userID == "" {
return nil, ErrMissingClaim
}
return &UserInfo{
UserID: userID,
Name: claims.Name,
Username: claims.Username,
ImageProfile: claims.ImageProfile,
}, nil
}
// GenerateToken creates a JWT token for testing purposes.
// In production, tokens should be generated by your auth service.
func GenerateToken(userID, secret string) (string, error) {
return GenerateTokenWithInfo(&UserInfo{UserID: userID}, secret)
}
// GenerateTokenWithInfo creates a JWT token with full user profile info.
// In production, tokens should be generated by your auth service.
func GenerateTokenWithInfo(info *UserInfo, secret string) (string, error) {
claims := Claims{
Hash: info.UserID,
Name: info.Name,
Username: info.Username,
ImageProfile: info.ImageProfile,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(secret))
}