NAM-APJATEL-BACKEND/middleware/auth_middleware.go

121 lines
3.5 KiB
Go

package middleware
import (
"crypto/tls"
"encoding/json"
"log"
"net/http"
"strings"
"time"
"users_management/m/config"
"users_management/m/model/dto/res"
"users_management/m/model/entity"
"users_management/m/usecase"
"users_management/m/utils/common"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// ConditionalAuthMiddleware checks config to decide whether to apply auth
func ConditionalAuthMiddleware(userUC usecase.UsersUsecase, cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
// If auth is disabled, skip authentication but set default values
if !cfg.AuthConfig.UserAuthEnabled {
log.Println("Authentication disabled - skipping auth middleware")
// Set default values for when auth is disabled
c.Set("userID", uuid.New()) // Generate a dummy UUID
c.Set("userName", "system")
c.Set("userRole", "Admin") // Default role when auth is disabled
c.Set("token", "no-auth-mode")
c.Next()
return
}
// If auth is enabled, run the normal auth middleware
AuthMiddleware(userUC)(c)
}
}
func AuthMiddleware(userUC usecase.UsersUsecase) gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
common.ErrorResponses(c, http.StatusUnauthorized, "authorization token required")
c.Abort()
return
}
token = strings.TrimPrefix(token, "Bearer ")
c.Set("token", token)
req, err := http.NewRequest("POST", "https://demo.api-hrm.winteraccess.id/api/v2/auth/me", nil)
if err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
var client *http.Client
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: tr,
Timeout: 30 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
common.ErrorResponses(c, http.StatusUnauthorized, "Unauthorized")
c.Abort()
return
}
var authResponse res.AuthMeResponse
if err := json.NewDecoder(resp.Body).Decode(&authResponse); err != nil {
common.ErrorResponses(c, http.StatusInternalServerError, err.Error())
c.Abort()
return
}
// Set basic user info from external API
var user entity.User
// Check if user exists in local database
user, err = userUC.GetUserByUsername(strings.ToLower(authResponse.Data.Username))
c.Set("userID", user.ID)
c.Set("userName", user.Username)
log.Println("User data from local DB:", user.ID)
if err != nil {
defaultRole := "Teknisi"
c.Set("userRole", defaultRole)
} else {
// User exists in local DB, use their assigned role
c.Set("userRole", user.Role.Name)
}
c.Next()
}
}