Files
aresv2/database/seeder/seeder.go
Beyhan Oğur 4362c3b83f first commit
2026-04-26 21:33:39 +03:00

76 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package seeder
import (
dbConfig "ares/database/config"
"ares/database/models"
"errors"
"fmt"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Seed checks for essential data and creates it if missing
func Seed() {
seedAdmin()
}
func seedAdmin() {
// Include soft-deleted records in lookup
var existing models.User
err := dbConfig.DB.Unscoped().Where("email = ?", "admin@example.com").First(&existing).Error
if err == nil {
// Found a user (could be soft-deleted)
// If soft-deleted, restore it
if existing.DeletedAt.Valid {
// Restore (set deleted_at to NULL) and ensure admin/verified flags
updateErr := dbConfig.DB.Unscoped().Model(&existing).Updates(map[string]interface{}{
"deleted_at": nil,
"is_admin": true,
"email_verified": true,
}).Error
if updateErr != nil {
fmt.Println("Admin restore hatası:", updateErr)
return
}
}
// user exists or restored, nothing more to do
return
} else if !errors.Is(err, gorm.ErrRecordNotFound) {
fmt.Println("Admin seed lookup error:", err)
return
}
// If not found at all, create
password := "password123"
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
isTrue := true
admin := models.User{
UserName: "Admin",
Email: "admin@example.com",
Password: string(hashedPassword),
IsAdmin: &isTrue,
EmailVerified: &isTrue,
}
res := dbConfig.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&admin)
if res.Error != nil {
fmt.Println("Admin seed hatası:", res.Error)
return
}
if res.RowsAffected == 0 {
// Another process likely created it concurrently
fmt.Println("Admin kullanıcı zaten mevcut; seed atlandı.")
return
}
fmt.Println("------------------------------------------------")
fmt.Println("Admin kullanıcısı oluşturuldu:")
fmt.Println("Email: admin@example.com")
fmt.Println("Şifre: password123")
fmt.Println("------------------------------------------------")
}