Base Project
This commit is contained in:
39
pkg/helper/jwt.go
Normal file
39
pkg/helper/jwt.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package helper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"wm-backend/global"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// GenerateToken tạo JWT token cho user
|
||||
func GenerateToken(userID string) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": userID,
|
||||
"iat": time.Now().Unix(), // issued at
|
||||
"exp": time.Now().Add(time.Duration(global.Cfg.JWT.ExpirationHours) * time.Hour * 7).Unix(), // expiry
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(global.Cfg.JWT.SecretKey)) // <-- lấy từ config
|
||||
}
|
||||
|
||||
func ParseToken(tokenString string) (jwt.MapClaims, error) {
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(global.Cfg.JWT.SecretKey), nil // <-- lấy từ config
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
Reference in New Issue
Block a user