Auth middleware with JWT
This commit is contained in:
@@ -3,6 +3,7 @@ package jwt
|
||||
import (
|
||||
"backend/config"
|
||||
"backend/models/user"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt"
|
||||
@@ -28,3 +29,27 @@ func GenerateJWT(u *user.User) (string, error) {
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
func ParseJWT(tokenString string) (jwt.MapClaims, error) {
|
||||
mySigningKey := []byte(config.Env["JWT_SECRET"])
|
||||
|
||||
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
|
||||
return mySigningKey, nil
|
||||
})
|
||||
// Check token parsing errors
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If good values then return
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// Return on invalid token
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package responses
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -19,3 +21,11 @@ func Error(c *gin.Context, err string, code int) {
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
func NeedsToLogin(c *gin.Context) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"error": "Authentication required",
|
||||
"needsAuthentication": true, // only appears in this error
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user