authentication #2

Merged
hex merged 4 commits from authentication into dev 2025-05-06 07:11:27 +00:00
3 changed files with 40 additions and 5 deletions
Showing only changes of commit 0b20a0d027 - Show all commits

View file

@ -33,4 +33,9 @@ func RegisterAuthRoutes(cfg *types.StereoConfig, api *gin.RouterGroup) {
c.String(http.StatusOK, jwt) 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 ( import (
"fmt" "fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5" "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)) 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) { func ValidateJWT(jwtString, key string) (jwt.MapClaims, error) {
token, err := jwt.Parse(jwtString, func(token *jwt.Token) (any, error) { token, err := jwt.Parse(jwtString, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {

View file

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