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() } }