feat: jwt token generation (todo: create jwt validation middleware)

This commit is contained in:
hexlocation 2025-05-05 23:04:50 +02:00
parent d8caef7e5d
commit b28b719b51
9 changed files with 86 additions and 29 deletions

View file

@ -8,8 +8,6 @@ import (
"net/http"
"net/url"
"strings"
"time"
"stereo.cat/backend/internal/auth"
)

37
internal/auth/jwt.go Normal file
View file

@ -0,0 +1,37 @@
package auth
import (
"fmt"
"github.com/golang-jwt/jwt/v5"
)
func GenerateJWT(key string, user User, expiryTimestamp uint64) (string, error) {
claims := jwt.MapClaims{
"user": user,
"exp": expiryTimestamp,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(key))
}
func ValidateJWT(jwtString, key string) (jwt.MapClaims, error) {
token, err := jwt.Parse(jwtString, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Invalid signing method!")
}
return []byte(key), nil
})
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!")
}

View file

@ -1,23 +1,21 @@
package auth
import (
"gorm.io/gorm"
)
import "time"
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn uint64 `json:"expires_in"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
type User struct {
gorm.Model
ID string `json:"id" gorm:"primaryKey;autoIncrement:false"`
ID string `json:"id" gorm:"primaryKey"`
Username string `json:"username"`
Blacklisted bool
Email string `json:"email"`
CreatedAt time.Time
}
type AvatarDecorationData struct {