setup.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package setup
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "golang.org/x/crypto/bcrypt"
  7. "github.com/usememos/memos/api"
  8. "github.com/usememos/memos/common"
  9. )
  10. func Execute(
  11. ctx context.Context,
  12. store store,
  13. hostUsername, hostPassword string,
  14. ) error {
  15. s := setupService{store: store}
  16. return s.Setup(ctx, hostUsername, hostPassword)
  17. }
  18. type store interface {
  19. FindUserList(ctx context.Context, find *api.UserFind) ([]*api.User, error)
  20. CreateUser(ctx context.Context, create *api.UserCreate) (*api.User, error)
  21. }
  22. type setupService struct {
  23. store store
  24. }
  25. func (s setupService) Setup(
  26. ctx context.Context,
  27. hostUsername, hostPassword string,
  28. ) error {
  29. if err := s.makeSureHostUserNotExists(ctx); err != nil {
  30. return err
  31. }
  32. if err := s.createUser(ctx, hostUsername, hostPassword); err != nil {
  33. return fmt.Errorf("create user: %w", err)
  34. }
  35. return nil
  36. }
  37. func (s setupService) makeSureHostUserNotExists(ctx context.Context) error {
  38. hostUserType := api.Host
  39. existedHostUsers, err := s.store.FindUserList(ctx, &api.UserFind{
  40. Role: &hostUserType,
  41. })
  42. if err != nil {
  43. return fmt.Errorf("find user list: %w", err)
  44. }
  45. if len(existedHostUsers) != 0 {
  46. return errors.New("host user already exists")
  47. }
  48. return nil
  49. }
  50. func (s setupService) createUser(
  51. ctx context.Context,
  52. hostUsername, hostPassword string,
  53. ) error {
  54. userCreate := &api.UserCreate{
  55. Username: hostUsername,
  56. // The new signup user should be normal user by default.
  57. Role: api.Host,
  58. Nickname: hostUsername,
  59. Password: hostPassword,
  60. OpenID: common.GenUUID(),
  61. }
  62. if err := userCreate.Validate(); err != nil {
  63. return fmt.Errorf("validate: %w", err)
  64. }
  65. passwordHash, err := bcrypt.GenerateFromPassword([]byte(hostPassword), bcrypt.DefaultCost)
  66. if err != nil {
  67. return fmt.Errorf("hash password: %w", err)
  68. }
  69. userCreate.PasswordHash = string(passwordHash)
  70. if _, err := s.store.CreateUser(ctx, userCreate); err != nil {
  71. return fmt.Errorf("create user: %w", err)
  72. }
  73. return nil
  74. }