Move into api routers instead of main
This commit is contained in:
38
services/entry/pkg/api/middleware/auth.go
Normal file
38
services/entry/pkg/api/middleware/auth.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"net/http"
|
||||
"serverctl/pkg/application/users"
|
||||
)
|
||||
|
||||
func BasicAuthMiddleware(l *zap.Logger, us *users.Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
username, password, hasAuth := c.Request.BasicAuth()
|
||||
if !hasAuth {
|
||||
l.Info("user could not be authenticated",
|
||||
zap.String("username", username))
|
||||
c.Header("WWW-Authenticate", "Basic realm=serverctl")
|
||||
c.Abort()
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"message": "credentials were invalid (authorization header missing)"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := us.Authenticate(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
l.Info("user could not be authenticated",
|
||||
zap.String("username", username))
|
||||
c.Abort()
|
||||
c.Header("WWW-Authenticate", "Basic realm=serverctl")
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"message": "credentials were invalid (credentials didn't match)"})
|
||||
return
|
||||
}
|
||||
|
||||
l.Debug("user has been authenticated",
|
||||
zap.Int("userId", user.Id),
|
||||
zap.String("email", user.Email))
|
||||
c.Set("userId", user.Id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user