homebox/backend/app/api/seed.go

93 lines
2.2 KiB
Go
Raw Normal View History

2022-08-30 02:30:36 +00:00
package main
import (
"context"
"github.com/google/uuid"
2022-08-30 02:40:54 +00:00
"github.com/hay-kot/content/backend/internal/repo"
"github.com/hay-kot/content/backend/internal/types"
"github.com/hay-kot/content/backend/pkgs/hasher"
2022-09-03 18:38:35 +00:00
"github.com/rs/zerolog/log"
2022-08-30 02:30:36 +00:00
)
const (
2022-08-30 18:05:11 +00:00
DefaultGroup = "Default"
2022-08-30 02:30:36 +00:00
DefaultName = "Admin"
DefaultEmail = "admin@admin.com"
DefaultPassword = "admin"
)
// EnsureAdministrator ensures that there is at least one superuser in the database
// if one isn't found a default is generate using the default credentials
func (a *app) EnsureAdministrator() {
superusers, err := a.repos.Users.GetSuperusers(context.Background())
if err != nil {
2022-09-03 18:38:35 +00:00
log.Fatal().Err(err).Msg("failed to get superusers")
2022-08-30 02:30:36 +00:00
}
if len(superusers) > 0 {
return
}
pw, _ := hasher.HashPassword(DefaultPassword)
newSuperUser := types.UserCreate{
Name: DefaultName,
Email: DefaultEmail,
IsSuperuser: true,
Password: pw,
}
2022-09-03 18:38:35 +00:00
log.Info().
Str("name", newSuperUser.Name).
Str("email", newSuperUser.Email).
Msg("no superusers found, creating default superuser")
2022-08-30 02:30:36 +00:00
_, err = a.repos.Users.Create(context.Background(), newSuperUser)
if err != nil {
2022-09-03 18:38:35 +00:00
log.Fatal().Err(err).Msg("failed to create default superuser")
2022-08-30 02:30:36 +00:00
}
}
func (a *app) SeedDatabase(repos *repo.AllRepos) {
if !a.conf.Seed.Enabled {
return
}
2022-08-30 18:05:11 +00:00
group, err := repos.Groups.Create(context.Background(), DefaultGroup)
if err != nil {
2022-09-03 18:38:35 +00:00
log.Fatal().Err(err).Msg("failed to create default group")
2022-08-30 18:05:11 +00:00
}
2022-08-30 02:30:36 +00:00
for _, user := range a.conf.Seed.Users {
// Check if User Exists
usr, _ := repos.Users.GetOneEmail(context.Background(), user.Email)
if usr.ID != uuid.Nil {
2022-09-03 18:38:35 +00:00
log.Info().Str("email", user.Email).Msg("user already exists, skipping")
2022-08-30 02:30:36 +00:00
continue
}
hashedPw, err := hasher.HashPassword(user.Password)
if err != nil {
2022-09-03 18:38:35 +00:00
log.Fatal().Err(err).Msg("failed to hash password")
2022-08-30 02:30:36 +00:00
}
_, err = repos.Users.Create(context.Background(), types.UserCreate{
Name: user.Name,
Email: user.Email,
IsSuperuser: user.IsSuperuser,
Password: hashedPw,
2022-08-30 18:05:11 +00:00
GroupID: group.ID,
2022-08-30 02:30:36 +00:00
})
if err != nil {
2022-09-03 18:38:35 +00:00
log.Fatal().Err(err).Msg("failed to create user")
2022-08-30 02:30:36 +00:00
}
2022-09-03 18:38:35 +00:00
log.Info().Str("email", user.Email).Msg("created user")
2022-08-30 02:30:36 +00:00
}
}