ADD: added initial page with login
This commit is contained in:
47
backend/internal/auth/jwt.go
Normal file
47
backend/internal/auth/jwt.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
var jwtSecret = []byte("supersecret")
|
||||
|
||||
type Claims struct {
|
||||
UserID string
|
||||
Email string
|
||||
Role string
|
||||
}
|
||||
|
||||
func CreateJWT(userID, email, role string, duration time.Duration) (string, error) {
|
||||
claims := jwt.MapClaims{
|
||||
"userId": userID,
|
||||
"email": email,
|
||||
"role": role,
|
||||
"exp": time.Now().Add(duration).Unix(),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(jwtSecret)
|
||||
}
|
||||
|
||||
func ParseJWT(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
return nil, errors.New("invalid token")
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid claims")
|
||||
}
|
||||
|
||||
return &Claims{
|
||||
UserID: claims["userId"].(string),
|
||||
Email: claims["email"].(string),
|
||||
Role: claims["role"].(string),
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user