Files
hspguard/internal/user/admin.go

41 lines
1.0 KiB
Go

package user
import (
"context"
"fmt"
"log"
"gitea.local/admin/hspguard/internal/config"
"gitea.local/admin/hspguard/internal/repository"
"gitea.local/admin/hspguard/internal/util"
"github.com/google/uuid"
)
func EnsureAdminUser(ctx context.Context, cfg *config.AppConfig, repo *repository.Queries) {
_, err := repo.FindUserEmail(ctx, cfg.Admin.Email)
if err != nil {
if cfg.Admin.Password == "" {
log.Fatalln("ERR: ADMIN_PASSWORD env variable is required")
}
if _, err := createAdmin(ctx, cfg.Admin.Name, cfg.Admin.Email, cfg.Admin.Password, repo); err != nil {
log.Fatalln("ERR: Failed to create admin account:", err)
}
}
}
func createAdmin(ctx context.Context, name, email, password string, repo *repository.Queries) (uuid.UUID, error) {
hash, err := util.HashPassword(password)
if err != nil {
var id uuid.UUID
return id, fmt.Errorf("failed to hash the admin password")
}
return repo.InsertUser(ctx, repository.InsertUserParams{
FullName: name,
Email: email,
PasswordHash: hash,
IsAdmin: true,
})
}