shelfy-v2/internal/db/db.go
2025-08-18 20:44:27 +02:00

79 lines
1.9 KiB
Go
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 db
import (
"canguidev/shelfy/internal/client"
runner "canguidev/shelfy/internal/job"
"canguidev/shelfy/internal/models"
"fmt"
"log"
"os"
"path/filepath"
"golang.org/x/crypto/bcrypt"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func InitDB() *gorm.DB {
dbPath := "data/shelfly_db.db"
print(filepath.Dir(dbPath));
// Crée le dossier parent s'il n'existe pas
if err := os.MkdirAll(filepath.Dir(dbPath), os.ModePerm); err != nil {
panic(fmt.Sprintf("Erreur lors de la création du dossier : %v", err))
}
// Connexion à SQLite
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
if err != nil {
panic(fmt.Sprintf("Échec de connexion à SQLite : %v", err))
}
// Auto migration
if err := db.AutoMigrate(&models.User{},&models.PathDownload{},&client.DebridAccount{},&runner.DownloadJob{}); err != nil {
panic(fmt.Sprintf("Erreur d'auto-migration : %v", err))
}
InitDefaultAdmin(db)
fmt.Println("✅ SQLite initialisé correctement.")
return db
}
func InitDefaultAdmin(db *gorm.DB) {
const email = "canguijc@gmail.com"
const username = "admin"
const name = "Admin"
const password = "GHT30k7!"
var user models.User
result := db.Where("email = ?", email).First(&user)
if result.Error == gorm.ErrRecordNotFound {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
log.Fatalf("Erreur lors du hash du mot de passe: %v", err)
}
newUser := models.User{
Email: email,
Username: username,
Name: name,
Password: string(hashedPassword),
}
if err := db.Create(&newUser).Error; err != nil {
log.Fatalf("Erreur lors de la création de l'utilisateur admin: %v", err)
}
log.Println("✅ Utilisateur administrateur créé avec succès")
} else if result.Error != nil {
log.Fatalf("Erreur lors de la vérification de l'utilisateur admin: %v", result.Error)
} else {
log.Println(" L'utilisateur administrateur existe déjà")
}
}