Files
pocket-id-pocket-id-2/backend/internal/middleware/jwt_auth.go

59 lines
1.5 KiB
Go
Raw Normal View History

2024-08-12 11:00:25 +02:00
package middleware
import (
"github.com/gin-gonic/gin"
2024-10-28 18:11:54 +01:00
"github.com/stonith404/pocket-id/backend/internal/common"
"github.com/stonith404/pocket-id/backend/internal/service"
2024-08-12 11:00:25 +02:00
"strings"
)
type JwtAuthMiddleware struct {
2024-08-23 17:04:19 +02:00
jwtService *service.JwtService
ignoreUnauthenticated bool
}
2024-08-23 17:04:19 +02:00
func NewJwtAuthMiddleware(jwtService *service.JwtService, ignoreUnauthenticated bool) *JwtAuthMiddleware {
return &JwtAuthMiddleware{jwtService: jwtService, ignoreUnauthenticated: ignoreUnauthenticated}
}
2024-08-12 11:00:25 +02:00
func (m *JwtAuthMiddleware) Add(adminOnly bool) gin.HandlerFunc {
return func(c *gin.Context) {
2024-08-12 11:00:25 +02:00
// Extract the token from the cookie or the Authorization header
token, err := c.Cookie("access_token")
if err != nil {
authorizationHeaderSplitted := strings.Split(c.GetHeader("Authorization"), " ")
if len(authorizationHeaderSplitted) == 2 {
token = authorizationHeaderSplitted[1]
2024-08-23 17:04:19 +02:00
} else if m.ignoreUnauthenticated {
c.Next()
return
2024-08-12 11:00:25 +02:00
} else {
2024-10-28 18:11:54 +01:00
c.Error(&common.NotSignedInError{})
c.Abort()
2024-08-12 11:00:25 +02:00
return
}
}
claims, err := m.jwtService.VerifyAccessToken(token)
2024-08-23 17:04:19 +02:00
if err != nil && m.ignoreUnauthenticated {
c.Next()
return
} else if err != nil {
2024-10-28 18:11:54 +01:00
c.Error(&common.NotSignedInError{})
2024-08-12 11:00:25 +02:00
c.Abort()
return
}
// Check if the user is an admin
if adminOnly && !claims.IsAdmin {
2024-10-28 18:11:54 +01:00
c.Error(&common.MissingPermissionError{})
2024-08-12 11:00:25 +02:00
c.Abort()
return
}
c.Set("userID", claims.Subject)
c.Set("userIsAdmin", claims.IsAdmin)
c.Next()
}
}