Users: Improve conflict error handling (#26958)
* API: Improve error handling (#26934) * New ErrUserAlreadyExists error has been introduced * Create user endpoint returns 412 Precondition Failed on ErrUserAlreadyExists errors * Make ErrUserAlreadyExists error message clearer Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> * Use errors.Is instead of equality comparator on AdminCreateUser handler * Improve sqlstore/user test definition Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com> * Improve sqlstore/user tests for ErrUserAlreadyExists cases * Remove no needed string fmt and err declaration on sqlstore/user tests * Code improvements for sqlstore/user tests Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com> * Use err.Error() instead of sentinel error value on AdminCreateUser Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com> * Add ErrUserAlreadyExists handling for signup & org invite use cases Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com> Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
This commit is contained in:
co-authored by
Emil Tullstedt
Arve Knudsen
parent
5398ef1103
commit
ef631582ba
@@ -68,6 +68,11 @@ func CreateUser(ctx context.Context, cmd *models.CreateUserCommand) error {
|
||||
cmd.Email = cmd.Login
|
||||
}
|
||||
|
||||
exists, _ := sess.Where("email=? OR login=?", cmd.Email, cmd.Login).Get(&models.User{})
|
||||
if exists {
|
||||
return models.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
// create user
|
||||
user := models.User{
|
||||
Email: cmd.Email,
|
||||
|
||||
@@ -568,6 +568,40 @@ func TestUserDataAccess(t *testing.T) {
|
||||
So(query.Result.IsAdmin, ShouldEqual, true)
|
||||
})
|
||||
})
|
||||
|
||||
Convey("Given one user", func() {
|
||||
const email = "user@test.com"
|
||||
const username = "user"
|
||||
createUserCmd := &models.CreateUserCommand{
|
||||
Email: email,
|
||||
Name: "user",
|
||||
Login: username,
|
||||
}
|
||||
err := CreateUser(context.Background(), createUserCmd)
|
||||
So(err, ShouldBeNil)
|
||||
|
||||
Convey("When trying to create a new user with the same email, an error is returned", func() {
|
||||
createUserCmd := &models.CreateUserCommand{
|
||||
Email: email,
|
||||
Name: "user2",
|
||||
Login: "user2",
|
||||
SkipOrgSetup: true,
|
||||
}
|
||||
err := CreateUser(context.Background(), createUserCmd)
|
||||
So(err, ShouldEqual, models.ErrUserAlreadyExists)
|
||||
})
|
||||
|
||||
Convey("When trying to create a new user with the same login, an error is returned", func() {
|
||||
createUserCmd := &models.CreateUserCommand{
|
||||
Email: "user2@test.com",
|
||||
Name: "user2",
|
||||
Login: username,
|
||||
SkipOrgSetup: true,
|
||||
}
|
||||
err := CreateUser(context.Background(), createUserCmd)
|
||||
So(err, ShouldEqual, models.ErrUserAlreadyExists)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user