feat: add basic workings
This commit is contained in:
@@ -5,7 +5,6 @@ import (
|
||||
"net/http"
|
||||
"orbits-server/internal/server/api/assets"
|
||||
"orbits-server/internal/server/service"
|
||||
"orbits-server/internal/shared/security"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -13,6 +12,8 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const authPrefix = "Bearer"
|
||||
|
||||
func SlogMiddleware(logger *slog.Logger) gin.HandlerFunc {
|
||||
// Make a slog-looking logger, inspired by the gin docs themself
|
||||
// JSON logger: https://gin-gonic.com/en/docs/logging/structured-logging/
|
||||
@@ -45,40 +46,30 @@ func AuthMiddleware(db *gorm.DB) gin.HandlerFunc {
|
||||
keyService := service.NewKeyService(db)
|
||||
|
||||
return func(c *gin.Context) {
|
||||
authorizationHeader := c.GetHeader("Authorization")
|
||||
if len(authorizationHeader) == 0 {
|
||||
header := c.GetHeader("Authorization")
|
||||
if len(header) == 0 {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.ResponseObject{
|
||||
Msg: "Authorization header is required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
headerParts := strings.Split(authorizationHeader, " ")
|
||||
// The header must be a specific format, 0 being the bearer text and 1 being the token itself, making it 2 pieces total
|
||||
// In the following if statement we verify both parts if the part after Bearer is empty its only 1 part for example
|
||||
if len(headerParts) != 2 || headerParts[0] != "Bearer" {
|
||||
if !strings.HasPrefix(header, authPrefix) {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.ResponseObject{
|
||||
Msg: "Authorization header is invalid",
|
||||
Msg: "Invalid authorization header",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
candidateKey := headerParts[1]
|
||||
storedKeys, err := keyService.ListValidKeyHashes()
|
||||
if err != nil {
|
||||
slog.Error("failed to retrieve key hashes", "error", err)
|
||||
assets.InternalErrorResponse(c)
|
||||
token := strings.TrimSpace(header[len(authPrefix):])
|
||||
ok := keyService.Validate(token)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.ResponseObject{
|
||||
Msg: "Invalid key",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
for _, key := range storedKeys {
|
||||
if match := security.CompareKey(key, candidateKey); match {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, assets.ResponseObject{
|
||||
Msg: "invalid key",
|
||||
})
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user