From 0bd2632d295e2c808154594c0166fcec3111a92c Mon Sep 17 00:00:00 2001 From: konrad Date: Fri, 18 Dec 2020 13:54:49 +0000 Subject: [PATCH] Add login via email (#740) Add login via email Co-authored-by: kolaente Reviewed-on: https://kolaente.dev/vikunja/api/pulls/740 Co-Authored-By: konrad Co-Committed-By: konrad --- pkg/user/user.go | 26 +++++++++++++++++++++----- pkg/user/user_test.go | 5 +++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/pkg/user/user.go b/pkg/user/user.go index 1fba498488..b655da8707 100644 --- a/pkg/user/user.go +++ b/pkg/user/user.go @@ -176,22 +176,38 @@ func getUser(user *User, withEmail bool) (userOut *User, err error) { return userOut, err } +func getUserByUsernameOrEmail(usernameOrEmail string) (u *User, err error) { + u = &User{} + exists, err := x. + Where("username = ? OR email = ?", usernameOrEmail, usernameOrEmail). + Get(u) + if err != nil { + return nil, err + } + if !exists { + return nil, ErrUserDoesNotExist{} + } + + u.Email = "" + return +} + // CheckUserCredentials checks user credentials func CheckUserCredentials(u *Login) (*User, error) { // Check if we have any credentials if u.Password == "" || u.Username == "" { - return &User{}, ErrNoUsernamePassword{} + return nil, ErrNoUsernamePassword{} } // Check if the user exists - user, err := GetUserByUsername(u.Username) + user, err := getUserByUsernameOrEmail(u.Username) if err != nil { // hashing the password takes a long time, so we hash something to not make it clear if the username was wrong _, _ = bcrypt.GenerateFromPassword([]byte(u.Username), 14) - return &User{}, ErrWrongUsernameOrPassword{} + return nil, ErrWrongUsernameOrPassword{} } - // User is invalid if it needs to verify its email address + // The user is invalid if they need to verify their email address if !user.IsActive { return &User{}, ErrEmailNotConfirmed{UserID: user.ID} } @@ -199,7 +215,7 @@ func CheckUserCredentials(u *Login) (*User, error) { // Check the users password err = CheckUserPassword(user, u.Password) if err != nil { - return &User{}, err + return nil, err } return user, nil diff --git a/pkg/user/user_test.go b/pkg/user/user_test.go index 0ba3843e17..472bff409d 100644 --- a/pkg/user/user_test.go +++ b/pkg/user/user_test.go @@ -201,6 +201,11 @@ func TestCheckUserCredentials(t *testing.T) { assert.Error(t, err) assert.True(t, IsErrNoUsernamePassword(err)) }) + t.Run("email", func(t *testing.T) { + db.LoadAndAssertFixtures(t) + _, err := CheckUserCredentials(&Login{Username: "user1@example.com", Password: "1234"}) + assert.NoError(t, err) + }) } func TestUpdateUser(t *testing.T) {