add: Admin creation
This commit is contained in:
@@ -1,9 +1,14 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"GoMembership/internal/constants"
|
||||
"GoMembership/internal/models"
|
||||
"GoMembership/pkg/logger"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"github.com/alexedwards/argon2id"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -29,6 +34,9 @@ func Open(dbPath string) error {
|
||||
DB = db
|
||||
|
||||
logger.Info.Print("Opened DB")
|
||||
if err := seedDatabase(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -40,3 +48,42 @@ func Close() error {
|
||||
}
|
||||
return db.Close()
|
||||
}
|
||||
|
||||
func seedDatabase() error {
|
||||
var count int64
|
||||
DB.Model(&models.User{}).Count(&count)
|
||||
if count == 0 {
|
||||
bytes := make([]byte, 12)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
password := hex.EncodeToString(bytes)
|
||||
hash, err := argon2id.CreateHash(password, argon2id.DefaultParams)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
admin := models.User{
|
||||
FirstName: "ad",
|
||||
LastName: "min",
|
||||
DateOfBirth: time.Now(),
|
||||
Password: hash,
|
||||
Address: "Downhill 4",
|
||||
ZipCode: "9999",
|
||||
City: "TechTown",
|
||||
Status: constants.ActiveStatus,
|
||||
RoleID: constants.Roles.Editor,
|
||||
}
|
||||
|
||||
result := DB.Create(&admin)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
logger.Error.Print("==============================================================")
|
||||
logger.Error.Printf("Admin Password: %v", password)
|
||||
logger.Error.Print("==============================================================")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user