Switch from cookie to Bearer token auth and add CORS support - Semi finished
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -38,26 +39,31 @@ func (j *JwtTokenGenerator) GenerateToken(claims map[string]interface{}) (string
|
||||
// Gin middleware
|
||||
func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, err := c.Request.Cookie("token")
|
||||
if err != nil {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
|
||||
return
|
||||
}
|
||||
t, err := jwt.Parse(token.Value, func(t *jwt.Token) (interface{}, error) {
|
||||
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
t, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(j.Key), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := t.Claims.(jwt.MapClaims)
|
||||
if !ok || claims["role"] != "admin" { // Check role, only if its admin let it go
|
||||
if !ok || claims["role"] != "admin" {
|
||||
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user