setup.go 2.4 KB

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