Skip to content

Commit

Permalink
auth: optimize lock scope for CheckPassword
Browse files Browse the repository at this point in the history
to improve authentication performance in concurrent scenarios when enable auth and using authentication based password
  • Loading branch information
wswcfan committed Apr 25, 2020
1 parent f1eca4e commit f18976f
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions auth/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,17 +346,27 @@ func (as *authStore) CheckPassword(username, password string) (uint64, error) {
return 0, ErrAuthNotEnabled
}

tx := as.be.BatchTx()
tx.Lock()
defer tx.Unlock()
var user *authpb.User
// CompareHashAndPassword is very expensive, so we use closures
// to avoid putting it in the critical section of the tx lock.
revision, err := func() (uint64, error) {
tx := as.be.BatchTx()
tx.Lock()
defer tx.Unlock()

user = getUser(as.lg, tx, username)
if user == nil {
return 0, ErrAuthFailed
}

user := getUser(as.lg, tx, username)
if user == nil {
return 0, ErrAuthFailed
}
if user.Options != nil && user.Options.NoPassword {
return 0, ErrAuthFailed
}

if user.Options != nil && user.Options.NoPassword {
return 0, ErrAuthFailed
return getRevision(tx), nil
}()
if err != nil {
return 0, err
}

if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
Expand All @@ -367,7 +377,7 @@ func (as *authStore) CheckPassword(username, password string) (uint64, error) {
}
return 0, ErrAuthFailed
}
return getRevision(tx), nil
return revision, nil
}

func (as *authStore) Recover(be backend.Backend) {
Expand Down

0 comments on commit f18976f

Please sign in to comment.