feat: auth middleware + /me endpoint
This commit is contained in:
parent
b28b719b51
commit
0b20a0d027
3 changed files with 40 additions and 5 deletions
|
@ -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)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -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 {
|
||||||
|
|
|
@ -11,11 +11,11 @@ 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 {
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue