2025-03-11 14:16:42 -05:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
"github.com/pocket-id/pocket-id/backend/internal/common"
|
|
|
|
|
"github.com/pocket-id/pocket-id/backend/internal/service"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type ApiKeyAuthMiddleware struct {
|
|
|
|
|
apiKeyService *service.ApiKeyService
|
|
|
|
|
jwtService *service.JwtService
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewApiKeyAuthMiddleware(apiKeyService *service.ApiKeyService, jwtService *service.JwtService) *ApiKeyAuthMiddleware {
|
|
|
|
|
return &ApiKeyAuthMiddleware{
|
|
|
|
|
apiKeyService: apiKeyService,
|
|
|
|
|
jwtService: jwtService,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (m *ApiKeyAuthMiddleware) Add(adminRequired bool) gin.HandlerFunc {
|
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
|
userID, isAdmin, err := m.Verify(c, adminRequired)
|
|
|
|
|
if err != nil {
|
|
|
|
|
c.Abort()
|
2025-03-27 16:48:36 +01:00
|
|
|
_ = c.Error(err)
|
2025-03-11 14:16:42 -05:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.Set("userID", userID)
|
|
|
|
|
c.Set("userIsAdmin", isAdmin)
|
|
|
|
|
c.Next()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (m *ApiKeyAuthMiddleware) Verify(c *gin.Context, adminRequired bool) (userID string, isAdmin bool, err error) {
|
|
|
|
|
apiKey := c.GetHeader("X-API-KEY")
|
|
|
|
|
|
2025-04-06 06:04:08 -07:00
|
|
|
user, err := m.apiKeyService.ValidateApiKey(c.Request.Context(), apiKey)
|
2025-03-11 14:16:42 -05:00
|
|
|
if err != nil {
|
|
|
|
|
return "", false, &common.NotSignedInError{}
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-18 10:38:50 -05:00
|
|
|
if user.Disabled {
|
|
|
|
|
return "", false, &common.UserDisabledError{}
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-11 14:16:42 -05:00
|
|
|
if adminRequired && !user.IsAdmin {
|
|
|
|
|
return "", false, &common.MissingPermissionError{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return user.ID, user.IsAdmin, nil
|
|
|
|
|
}
|