feat: auth middleware + /me endpoint

This commit is contained in:
hexlocation 2025-05-06 08:39:19 +02:00
parent b28b719b51
commit 0b20a0d027
3 changed files with 40 additions and 5 deletions

View file

@ -33,4 +33,9 @@ func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
c.String(http.StatusOK, jwt)
})
api.GET("/auth/me", auth.JwtMiddleware(cfg.JWTSecret), func(c *gin.Context) {
claims, _ := c.Get("claims")
c.JSON(http.StatusOK, claims)
})
}

View file

@ -2,7 +2,10 @@ package auth
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
@ -16,6 +19,33 @@ func GenerateJWT(key string, user User, expiryTimestamp uint64) (string, error)
return token.SignedString([]byte(key))
}
func invalidAuth(c *gin.Context) {
c.String(http.StatusUnauthorized, "Unauthorized.")
c.Abort()
}
func JwtMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
jwtSplit := strings.Split(c.GetHeader("Authorization"), " ")
if jwtSplit[0] != "Bearer" {
invalidAuth(c)
return
}
claims, err := ValidateJWT(jwtSplit[1], secret)
if err != nil {
invalidAuth(c)
return
}
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 {

View file

@ -11,11 +11,11 @@ type TokenResponse struct {
}
type User struct {
ID string `json:"id" gorm:"primaryKey"`
Username string `json:"username"`
Blacklisted bool
Email string `json:"email"`
CreatedAt time.Time
ID string `json:"id" gorm:"primaryKey"`
Username string `json:"username"`
Blacklisted bool `json:"blacklisted"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}
type AvatarDecorationData struct {