some cleaning up
This commit is contained in:
parent
e3049dddd9
commit
a6a02d3521
4 changed files with 25 additions and 27 deletions
|
@ -1,17 +1,18 @@
|
|||
package auth
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"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 User, expiryTimestamp uint64) (string, error) {
|
||||
claims := Claims{
|
||||
func GenerateJWT(key string, user auth.User, expiryTimestamp uint64) (string, error) {
|
||||
claims := auth.Claims{
|
||||
User: user,
|
||||
Exp: expiryTimestamp,
|
||||
}
|
||||
|
@ -20,10 +21,6 @@ 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) {
|
||||
|
@ -33,7 +30,7 @@ func JwtMiddleware(secret string) gin.HandlerFunc {
|
|||
jwtSplit := strings.Split(c.GetHeader("Authorization"), " ")
|
||||
|
||||
if len(jwtSplit) < 2 || jwtSplit[0] != "Bearer" {
|
||||
invalidAuth(c)
|
||||
types.ErrorUnauthorized.Throw(c, nil)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -42,21 +39,21 @@ func JwtMiddleware(secret string) gin.HandlerFunc {
|
|||
|
||||
claims, err := ValidateJWT(jwt, secret)
|
||||
if err != nil {
|
||||
invalidAuth(c)
|
||||
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 {
|
||||
invalidAuth(c)
|
||||
types.ErrorUnauthorized.Throw(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
var user User
|
||||
var user auth.User
|
||||
err = json.Unmarshal(userJSON, &user)
|
||||
if err != nil {
|
||||
invalidAuth(c)
|
||||
types.ErrorUserNotFound.Throw(c, err)
|
||||
return
|
||||
}
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue