2024-02-22 10:18:59 +01:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
|
2024-02-22 20:52:37 +01:00
|
|
|
"github.com/spf13/viper"
|
2024-02-22 10:18:59 +01:00
|
|
|
"gorm.io/gorm"
|
|
|
|
|
|
|
|
"git.jmbit.de/jmb/goipam/utils"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SetupDB checks if database has already been initialized and users exist, otherwise creates default users
|
|
|
|
func SetupDB() {
|
|
|
|
ConnectDB()
|
|
|
|
var users []User
|
|
|
|
var count int64
|
2024-02-22 20:52:37 +01:00
|
|
|
var err error
|
|
|
|
var adminPW string
|
2024-02-22 10:18:59 +01:00
|
|
|
conn.Find(&users).Count(&count)
|
|
|
|
if count >= 1 {
|
|
|
|
return
|
|
|
|
}
|
2024-02-22 20:52:37 +01:00
|
|
|
if viper.GetString("web.adminpw") != "" {
|
|
|
|
adminPW = viper.GetString("web.adminpw")
|
|
|
|
|
|
|
|
} else {
|
|
|
|
adminPW, err = utils.RandomString(32)
|
|
|
|
}
|
2024-02-22 10:18:59 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Could not generate admin PW: %v", err)
|
|
|
|
} else {
|
|
|
|
log.Println("Admin PW is:", adminPW)
|
|
|
|
}
|
|
|
|
adminPWHash, err := utils.RandomString(32)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Could not generate admin PW: %v", err)
|
|
|
|
} else {
|
|
|
|
log.Println("Hashed Admin PW", adminPWHash)
|
|
|
|
}
|
|
|
|
adminUser := User{
|
|
|
|
Model: gorm.Model{},
|
|
|
|
Name: "admin",
|
|
|
|
PassHash: adminPWHash,
|
|
|
|
Email: "admin@example.com",
|
|
|
|
DisplayName: "Administrator",
|
|
|
|
Admin: true,
|
|
|
|
}
|
|
|
|
result := conn.Create(&adminUser)
|
|
|
|
if result.Error != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
}
|