Mhamdans17 commited on
Commit
46976cd
·
1 Parent(s): e79019b

perf: optimize Login GORM query with select-specific-columns, specific preloads, and remove the redundant First(company) query

Browse files
Files changed (1) hide show
  1. controllers/auth_controller.go +19 -13
controllers/auth_controller.go CHANGED
@@ -14,6 +14,7 @@ import (
14
  "service-warungpos-go/services"
15
 
16
  "github.com/gin-gonic/gin"
 
17
  )
18
 
19
  // SeedDefaultAdmin inisialisasi default super admin jika belum ada
@@ -142,7 +143,15 @@ func Login(c *gin.Context) {
142
  }
143
 
144
  var user models.User
145
- if err := config.DB.Preload("Company").Preload("Branch").Where("email = ?", req.Email).First(&user).Error; err != nil {
 
 
 
 
 
 
 
 
146
  c.JSON(http.StatusUnauthorized, gin.H{"detail": "Email atau password salah"})
147
  return
148
  }
@@ -154,18 +163,15 @@ func Login(c *gin.Context) {
154
 
155
  // Cek status keaktifan user
156
  if !user.IsActive {
157
- if user.Role == "owner" && user.CompanyID != nil {
158
- var company models.Company
159
- if err := config.DB.First(&company, *user.CompanyID).Error; err == nil {
160
- if company.ApprovedAt != nil {
161
- // Pernah diapprove tapi sekarang dinonaktifkan
162
- c.JSON(http.StatusUnauthorized, gin.H{"detail": "ACCOUNT_DEACTIVATED"})
163
- return
164
- } else {
165
- // Belum diapprove super_admin
166
- c.JSON(http.StatusUnauthorized, gin.H{"detail": "PENDING_APPROVAL"})
167
- return
168
- }
169
  }
170
  }
171
  c.JSON(http.StatusForbidden, gin.H{"detail": "Akun tidak aktif, hubungi admin"})
 
14
  "service-warungpos-go/services"
15
 
16
  "github.com/gin-gonic/gin"
17
+ "gorm.io/gorm"
18
  )
19
 
20
  // SeedDefaultAdmin inisialisasi default super admin jika belum ada
 
143
  }
144
 
145
  var user models.User
146
+ if err := config.DB.Select("id, name, email, password, phone, role, company_id, branch_id, is_active, created_at").
147
+ Preload("Company", func(db *gorm.DB) *gorm.DB {
148
+ return db.Select("id, name, approved_at, is_active")
149
+ }).
150
+ Preload("Branch", func(db *gorm.DB) *gorm.DB {
151
+ return db.Select("id, name")
152
+ }).
153
+ Where("email = ?", req.Email).
154
+ First(&user).Error; err != nil {
155
  c.JSON(http.StatusUnauthorized, gin.H{"detail": "Email atau password salah"})
156
  return
157
  }
 
163
 
164
  // Cek status keaktifan user
165
  if !user.IsActive {
166
+ if user.Role == "owner" && user.Company != nil {
167
+ if user.Company.ApprovedAt != nil {
168
+ // Pernah diapprove tapi sekarang dinonaktifkan
169
+ c.JSON(http.StatusUnauthorized, gin.H{"detail": "ACCOUNT_DEACTIVATED"})
170
+ return
171
+ } else {
172
+ // Belum diapprove super_admin
173
+ c.JSON(http.StatusUnauthorized, gin.H{"detail": "PENDING_APPROVAL"})
174
+ return
 
 
 
175
  }
176
  }
177
  c.JSON(http.StatusForbidden, gin.H{"detail": "Akun tidak aktif, hubungi admin"})