1c74d12df6
modified: main_dc/yalarba/api_es/go.sum new file: main_dc/yalarba/api_es/internal/dto/user.go new file: main_dc/yalarba/api_es/internal/handler/all_handlers.go new file: main_dc/yalarba/api_es/internal/handler/auth_handler.go new file: main_dc/yalarba/api_es/internal/handler/user_handler.go deleted: main_dc/yalarba/api_es/internal/handlers/all_handlers.go deleted: main_dc/yalarba/api_es/internal/handlers/auth_handler.go deleted: main_dc/yalarba/api_es/internal/handlers/user_handler.go new file: main_dc/yalarba/api_es/internal/middleware/auth.go deleted: main_dc/yalarba/api_es/internal/repositories/user_repository.go new file: main_dc/yalarba/api_es/internal/repository/user_repository.go new file: main_dc/yalarba/api_es/internal/service/user_service.go new file: main_dc/yalarba/api_es/internal/utils/jwt.go add service, handler, repository for user model
54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
type JWTUtil struct {
|
|
secretKey string
|
|
}
|
|
|
|
type Claims struct {
|
|
UserID uint `json:"user_id"`
|
|
Email string `json:"email"`
|
|
Role string `json:"role"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func NewJWTUtil(secretKey string) *JWTUtil {
|
|
return &JWTUtil{secretKey: secretKey}
|
|
}
|
|
|
|
func (j *JWTUtil) GenerateToken(userID uint, email, role string) (string, error) {
|
|
claims := Claims{
|
|
UserID: userID,
|
|
Email: email,
|
|
Role: role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(j.secretKey))
|
|
}
|
|
|
|
func (j *JWTUtil) ValidateToken(tokenString string) (*Claims, error) {
|
|
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(j.secretKey), nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, jwt.ErrInvalidKey
|
|
}
|