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)
|
|
|
|
}
|
2024-02-23 11:22:28 +01:00
|
|
|
adminPWHash, err := utils.HashPassword(adminPW)
|
2024-02-22 10:18:59 +01:00
|
|
|
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)
|
|
|
|
}
|
2024-02-23 11:22:28 +01:00
|
|
|
result = nil
|
|
|
|
result = conn.Create(&Location{
|
|
|
|
Name: "Example",
|
|
|
|
Comment: "This is an example Location",
|
|
|
|
Subnets: []Subnet{
|
|
|
|
{
|
|
|
|
Name: "VLAN1337",
|
|
|
|
DisplayName: "Example Subnet",
|
|
|
|
IPv4Net: "1.3.3.7/32",
|
|
|
|
IPv6Net: "dead:beef:ca1f/64",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if result.Error != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
|
2024-02-22 10:18:59 +01:00
|
|
|
}
|