backend/internal/auth/token/jwt.go
2025-06-15 12:53:27 +02:00

103 lines
2.6 KiB
Go

/*
Copyright (C) 2025 hexlocation (hex@iwakura.rip) & grngxd (grng@iwakura.rip)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package token
import (
"encoding/json"
"fmt"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"stereo.cat/backend/internal/auth"
"stereo.cat/backend/internal/types"
)
func GenerateJWT(key string, user auth.User, expiryTimestamp uint64) (string, error) {
claims := auth.Claims{
User: user,
Exp: expiryTimestamp,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(key))
}
func JwtMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
jwt, err := c.Cookie("jwt")
if err != nil {
// js as a fallback incase hex does a stupid again
jwtSplit := strings.Split(c.GetHeader("Authorization"), " ")
if len(jwtSplit) < 2 || jwtSplit[0] != "Bearer" {
types.ErrorUnauthorized.Throw(c, nil)
return
}
jwt = jwtSplit[1]
}
claims, err := ValidateJWT(jwt, secret)
if err != nil {
types.ErrorUnauthorized.Throw(c, err)
return
}
if userClaims, ok := claims["user"].(map[string]interface{}); ok {
userJSON, err := json.Marshal(userClaims) // Convert map to JSON
if err != nil {
types.ErrorUnauthorized.Throw(c, err)
return
}
var user auth.User
err = json.Unmarshal(userJSON, &user)
if err != nil {
types.ErrorUserNotFound.Throw(c, err)
return
}
claims["user"] = user
}
c.Set("claims", claims)
c.Next()
}
}
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!")
}