Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: check for phone identity on Phone Change #1819

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (a *API) UserUpdate(w http.ResponseWriter, r *http.Request) error {
}

if params.Phone != "" && user.GetPhone() != params.Phone {
if exists, err := models.IsDuplicatedPhone(db, params.Phone, aud); err != nil {
if exists, err := models.HasPhoneIdentity(db, params.Phone, aud); err != nil {
return internalServerError("Database error checking phone").WithInternalError(err)
} else if exists {
return unprocessableEntityError(ErrorCodePhoneExists, DuplicatePhoneMsg)
Expand Down
6 changes: 6 additions & 0 deletions internal/api/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ func (ts *UserTestSuite) TestUserUpdatePhoneAutoconfirmEnabled() {
require.NoError(ts.T(), err)
require.NoError(ts.T(), ts.API.db.Create(existingUser))

idPhone, err := models.NewIdentity(existingUser, "phone", map[string]interface{}{
"sub": "+29382983298",
})
require.NoError(ts.T(), err)
require.NoError(ts.T(), ts.API.db.Create(idPhone))

cases := []struct {
desc string
userData map[string]string
Expand Down
18 changes: 18 additions & 0 deletions internal/models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,24 @@ func IsDuplicatedPhone(tx *storage.Connection, phone, aud string) (bool, error)
return true, nil
}

// TODO: Simplify this, check if it is safe to do this in admin create user too
// HasPhoneIdentity checks if the phone number already exists in the identities table
func HasPhoneIdentity(tx *storage.Connection, phone, aud string) (bool, error) {
query := `SELECT 1 FROM users
JOIN identities ON users.id = identities.user_id
WHERE users.phone = ? AND users.aud = ? AND identities.provider = ?
LIMIT 1`

var exists bool
q := tx.RawQuery(query, phone, aud, "phone")
exists, err := q.Exists(&exists)
if err != nil {
return false, err
}

return exists, nil
}

// Ban a user for a given duration.
func (u *User) Ban(tx *storage.Connection, duration time.Duration) error {
if duration == time.Duration(0) {
Expand Down
Loading