// Copyright (c) 2025 Nikolai Papin // // This file is part of Easywish // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . package middleware import ( "easywish/internal/dto" "easywish/internal/services" "easywish/internal/utils/enums" "errors" "net/http" "github.com/gin-gonic/gin" "go.uber.org/zap" errs "easywish/internal/errors" ) func AuthMiddleware(log *zap.Logger, auth services.AuthService) gin.HandlerFunc { return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { c.Set("session_info", dto.SessionInfo{ Username: "", Session: "", Role: enums.GuestRole}, ) c.Next() return } tokenString := authHeader if sessionInfo, err := auth.ValidateToken(tokenString, enums.JwtAccessTokenType); err != nil { if errors.Is(err, errs.ErrTokenExpired) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is expired"}) } else if errors.Is(err, errs.ErrTokenInvalid) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token is invalid"}) } else if errors.Is(err, errs.ErrWrongTokenType) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token type"}) } else if errors.Is(err, errs.ErrSessionNotFound) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Could not find session in database"}) } else if errors.Is(err, errs.ErrSessionTerminated) { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Session is terminated"}) } else { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"}) } return } else { c.Set("session_info", sessionInfo) c.Next() } return } }