Authn: Prevent empty username and email during sync (#76330)

* Move errors to error file

* Move check for both empty username and email to user service

* Move check for empty email and username to user service Update

* Wrap inner error

* Set username in test
This commit is contained in:
Karl Persson
2023-10-11 14:27:43 +02:00
committed by GitHub
parent e46e66313d
commit 1528d6f5c4
8 changed files with 67 additions and 30 deletions
+19
View File
@@ -98,6 +98,15 @@ func (s *Service) Usage(ctx context.Context, _ *quota.ScopeParameters) (*quota.M
}
func (s *Service) Create(ctx context.Context, cmd *user.CreateUserCommand) (*user.User, error) {
if len(cmd.Login) == 0 {
cmd.Login = cmd.Email
}
// if login is still empty both email and login field is missing
if len(cmd.Login) == 0 {
return nil, user.ErrEmptyUsernameAndEmail.Errorf("user cannot be created with empty username and email")
}
cmdOrg := org.GetOrgIDForNewUserCommand{
Email: cmd.Email,
Login: cmd.Login,
@@ -215,10 +224,20 @@ func (s *Service) GetByEmail(ctx context.Context, query *user.GetUserByEmailQuer
}
func (s *Service) Update(ctx context.Context, cmd *user.UpdateUserCommand) error {
if len(cmd.Login) == 0 {
cmd.Login = cmd.Email
}
// if login is still empty both email and login field is missing
if len(cmd.Login) == 0 {
return user.ErrEmptyUsernameAndEmail.Errorf("user cannot be created with empty username and email")
}
if s.cfg.CaseInsensitiveLogin {
cmd.Login = strings.ToLower(cmd.Login)
cmd.Email = strings.ToLower(cmd.Email)
}
return s.store.Update(ctx, cmd)
}
+20
View File
@@ -38,6 +38,16 @@ func TestUserService(t *testing.T) {
require.NoError(t, err)
})
t.Run("create user should fail when username and email are empty", func(t *testing.T) {
_, err := userService.Create(context.Background(), &user.CreateUserCommand{
Email: "",
Login: "",
Name: "name",
})
require.ErrorIs(t, err, user.ErrEmptyUsernameAndEmail)
})
t.Run("get user by ID", func(t *testing.T) {
userService.cfg = setting.NewCfg()
userService.cfg.CaseInsensitiveLogin = false
@@ -88,6 +98,16 @@ func TestUserService(t *testing.T) {
require.NoError(t, err)
})
t.Run("update user should fail with empty username and password", func(t *testing.T) {
err := userService.Update(context.Background(), &user.UpdateUserCommand{
Email: "",
Login: "",
Name: "name",
})
require.ErrorIs(t, err, user.ErrEmptyUsernameAndEmail)
})
t.Run("GetByID - email conflict", func(t *testing.T) {
userService.cfg.CaseInsensitiveLogin = true
userStore.ExpectedError = errors.New("email conflict")