45 lines
930 B
Go
45 lines
930 B
Go
package db
|
|
|
|
import (
|
|
"log"
|
|
|
|
"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
|
|
conn.Find(&users).Count(&count)
|
|
if count >= 1 {
|
|
return
|
|
}
|
|
adminPW, err := utils.RandomString(32)
|
|
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)
|
|
}
|
|
}
|