From 0272dc269e203a44fa1cbdbc7399f694bb6d7275 Mon Sep 17 00:00:00 2001 From: Benedikt Kulmann Date: Tue, 15 Sep 2020 19:41:38 +0200 Subject: [PATCH] Reject new account if id, mail or username already exists --- pkg/service/v0/accounts.go | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/pkg/service/v0/accounts.go b/pkg/service/v0/accounts.go index 97f0a523d5..ba3883d022 100644 --- a/pkg/service/v0/accounts.go +++ b/pkg/service/v0/accounts.go @@ -157,6 +157,41 @@ func (s Service) passwordIsValid(hash string, pwd string) (ok bool) { return c.Verify(hash, []byte(pwd)) == nil } +func (s Service) accountExists(ctx context.Context, username, mail, id string) (exists bool, err error) { + // only search for accounts + tq := bleve.NewTermQuery("account") + tq.SetField("bleve_type") + query := bleve.NewConjunctionQuery(tq) + + // parse the query like an odata filter + var q *godata.GoDataFilterQuery + queryUsername := fmt.Sprintf("on_premises_sam_account_name eq '%s'", username) + queryMail := fmt.Sprintf("mail eq '%s'", mail) + queryID := fmt.Sprintf("id eq '%s'", id) + if q, err = godata.ParseFilterString(queryUsername + " or " + queryMail + " or " + queryID); err != nil { + s.log.Error().Err(err).Msg("could not parse query") + return false, merrors.InternalServerError(s.id, "could not parse query: %v", err.Error()) + } + + // convert to bleve query + bq, err := provider.BuildBleveQuery(q) + if err != nil { + s.log.Error().Err(err).Msg("could not build bleve query") + return false, merrors.InternalServerError(s.id, "could not build bleve query: %v", err.Error()) + } + query.AddQuery(bq) + + searchRequest := bleve.NewSearchRequest(query) + var searchResult *bleve.SearchResult + searchResult, err = s.index.Search(searchRequest) + if err != nil { + s.log.Error().Err(err).Msg("could not execute bleve search") + return false, merrors.InternalServerError(s.id, "could not execute bleve search: %v", err.Error()) + } + + return searchResult.Total > 0, nil +} + func (s Service) hasAccountManagementPermissions(ctx context.Context) bool { // get roles from context roleIDs, ok := roles.ReadRoleIDsFromContext(ctx) @@ -327,6 +362,14 @@ func (s Service) CreateAccount(ctx context.Context, in *proto.CreateAccountReque return merrors.InternalServerError(s.id, "could not clean up account id: %v", err.Error()) } + exists, err := s.accountExists(ctx, acc.PreferredName, acc.Mail, acc.Id) + if err != nil { + return merrors.InternalServerError(s.id, "could not check if account exists: %v", err.Error()) + } + if exists { + return merrors.BadRequest(s.id, "account already exists") + } + if acc.PasswordProfile != nil { if acc.PasswordProfile.Password != "" { // encrypt password