MCPcopy Index your code
hub / github.com/dnote/dnote / CreateUser

Method CreateUser

pkg/server/app/users.go:49–104  ·  view source on GitHub ↗

CreateUser creates a user

(email, password string, passwordConfirmation string)

Source from the content-addressed store, hash-verified

47
48// CreateUser creates a user
49func (a *App) CreateUser(email, password string, passwordConfirmation string) (database.User, error) {
50 if email == "" {
51 return database.User{}, ErrEmailRequired
52 }
53
54 if err := validatePassword(password); err != nil {
55 return database.User{}, err
56 }
57
58 if password != passwordConfirmation {
59 return database.User{}, ErrPasswordConfirmationMismatch
60 }
61
62 tx := a.DB.Begin()
63
64 var count int64
65 if err := tx.Model(&database.User{}).Where("email = ?", email).Count(&count).Error; err != nil {
66 tx.Rollback()
67 return database.User{}, pkgErrors.Wrap(err, "counting user")
68 }
69 if count > 0 {
70 tx.Rollback()
71 return database.User{}, ErrDuplicateEmail
72 }
73
74 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
75 if err != nil {
76 tx.Rollback()
77 return database.User{}, pkgErrors.Wrap(err, "hashing password")
78 }
79
80 uuid, err := helpers.GenUUID()
81 if err != nil {
82 tx.Rollback()
83 return database.User{}, pkgErrors.Wrap(err, "generating UUID")
84 }
85
86 user := database.User{
87 UUID: uuid,
88 Email: database.ToNullString(email),
89 Password: database.ToNullString(string(hashedPassword)),
90 }
91 if err = tx.Save(&user).Error; err != nil {
92 tx.Rollback()
93 return database.User{}, pkgErrors.Wrap(err, "saving user")
94 }
95
96 if err := a.TouchLastLoginAt(user, tx); err != nil {
97 tx.Rollback()
98 return database.User{}, pkgErrors.Wrap(err, "updating last login")
99 }
100
101 tx.Commit()
102
103 return user, nil
104}
105
106// GetUserByEmail finds a user by email

Callers 4

CreateMethod · 0.80
userCreateCmdFunction · 0.80
TestCreateUser_ProValueFunction · 0.80
TestCreateUserFunction · 0.80

Calls 7

TouchLastLoginAtMethod · 0.95
GenUUIDFunction · 0.92
ToNullStringFunction · 0.92
validatePasswordFunction · 0.85
BeginMethod · 0.65
RollbackMethod · 0.65
CommitMethod · 0.65

Tested by 2

TestCreateUser_ProValueFunction · 0.64
TestCreateUserFunction · 0.64