Added uuid middleware

This commit is contained in:
Nedim
2023-11-21 18:28:30 +01:00
parent a7ab058d01
commit d54b643378
11 changed files with 133 additions and 27 deletions

View File

@@ -6,6 +6,7 @@ package middlewares
import (
"errors"
"log"
"net/http"
"strings"
"time"
@@ -113,6 +114,15 @@ func ValidateToken(tokenString string, key string) (*jwt.Token, error) {
// AuthMiddleware checks the session token and validates it
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check if contractCheckPassed is set in the context
if passed, exists := c.Get("contractCheckPassed"); exists && passed.(bool) {
log.Printf("checjedpass auth %v", true)
// Skip further checks and proceed to the next middleware
c.Next()
return
}
log.Printf("checjedpass auth%v", false)
var jwtKey = []byte(config.AppConfig.Service.JwtSecretKey)
tokenString := c.GetHeader("Authorization")
@@ -156,3 +166,50 @@ func AuthMiddleware() gin.HandlerFunc {
c.Next()
}
}
func ContractCheckMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
db := shared.GetDb()
var contractID uint
var uuid string
// Handling for POST requests
if c.Request.Method == "POST" {
var payload struct {
UUID string `json:"uuid"`
}
if err := c.ShouldBindJSON(&payload); err == nil {
uuid = payload.UUID
}
}
// Handling for GET requests
if c.Request.Method == "GET" {
uuid = c.Query("uuid")
}
log.Printf("uuid %v", uuid)
log.Printf("contractID %v", contractID)
// Perform the check only if both contractID and uuid are provided
if uuid != "" {
var contract models.Contract
result := db.Where("uuid = ?", uuid).First(&contract)
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnauthorized, gin.H{"message": "Invalid contract ID or UUID"})
c.Abort()
return
} else if result.Error != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Internal server error"})
c.Abort()
return
}
// Set a flag in the context to indicate a successful contract check
c.Set("contractCheckPassed", true)
log.Printf("checjedpass %v", true)
}
c.Next()
}
}