Merge branch 'filter-by-company' into 'main'
Protected routes See merge request ukacorp/mesari/backend!24
This commit was merged in pull request #24.
This commit is contained in:
@@ -5,10 +5,17 @@
|
||||
package middlewares
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jinzhu/gorm"
|
||||
"gitlab.com/pactual1/backend/config"
|
||||
"gitlab.com/pactual1/backend/models"
|
||||
"gitlab.com/pactual1/backend/shared"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -102,3 +109,50 @@ func ValidateToken(tokenString string, key string) (*jwt.Token, error) {
|
||||
|
||||
return token, err
|
||||
}
|
||||
|
||||
// AuthMiddleware checks the session token and validates it
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var jwtKey = []byte(config.AppConfig.Service.JwtSecretKey)
|
||||
tokenString := c.GetHeader("Authorization")
|
||||
|
||||
// Check if token is in the correct format (Bearer token)
|
||||
if len(tokenString) > 7 && strings.ToUpper(tokenString[0:7]) == "BEARER " {
|
||||
tokenString = tokenString[7:]
|
||||
} else {
|
||||
c.JSON(http.StatusForbidden, gin.H{"message": "Your request is not authorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Parse and validate the token
|
||||
claims := &jwt.StandardClaims{}
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwtKey, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
c.JSON(http.StatusForbidden, gin.H{"message": "Invalid authorization token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the token is present and active in the SessionToken table
|
||||
var sessionToken models.SessionToken
|
||||
result := shared.GetDb().Where("token = ? AND is_active = ?", tokenString, true).First(&sessionToken)
|
||||
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"message": "Invalid session token"})
|
||||
c.Abort()
|
||||
return
|
||||
} else if result.Error != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Set user ID in the Gin context
|
||||
c.Set("userID", sessionToken.UserID)
|
||||
c.Set("companyID", sessionToken.CompanyID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user