github.com/mattermost/mattermost-server/v5@v5.39.3/services/users/password.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package users
     5  
     6  import (
     7  	"errors"
     8  	"strings"
     9  
    10  	"github.com/mattermost/mattermost-server/v5/model"
    11  	"golang.org/x/crypto/bcrypt"
    12  )
    13  
    14  func CheckUserPassword(user *model.User, password string) error {
    15  	if err := ComparePassword(user.Password, password); err != nil {
    16  		return NewErrInvalidPassword("")
    17  	}
    18  
    19  	return nil
    20  }
    21  
    22  // HashPassword generates a hash using the bcrypt.GenerateFromPassword
    23  func HashPassword(password string) string {
    24  	hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
    25  	if err != nil {
    26  		panic(err)
    27  	}
    28  
    29  	return string(hash)
    30  }
    31  
    32  func ComparePassword(hash string, password string) error {
    33  	if password == "" || hash == "" {
    34  		return errors.New("empty password or hash")
    35  	}
    36  
    37  	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
    38  }
    39  
    40  func (us *UserService) isPasswordValid(password string) error {
    41  
    42  	if *us.config().ServiceSettings.EnableDeveloper {
    43  		return nil
    44  	}
    45  
    46  	return IsPasswordValidWithSettings(password, &us.config().PasswordSettings)
    47  }
    48  
    49  // IsPasswordValidWithSettings is a utility functions that checks if the given password
    50  // comforms to the password settings. It returns the error id as error value.
    51  func IsPasswordValidWithSettings(password string, settings *model.PasswordSettings) error {
    52  	id := "model.user.is_valid.pwd"
    53  	isError := false
    54  
    55  	if len(password) < *settings.MinimumLength || len(password) > model.PASSWORD_MAXIMUM_LENGTH {
    56  		isError = true
    57  	}
    58  
    59  	if *settings.Lowercase {
    60  		if !strings.ContainsAny(password, model.LOWERCASE_LETTERS) {
    61  			isError = true
    62  		}
    63  
    64  		id = id + "_lowercase"
    65  	}
    66  
    67  	if *settings.Uppercase {
    68  		if !strings.ContainsAny(password, model.UPPERCASE_LETTERS) {
    69  			isError = true
    70  		}
    71  
    72  		id = id + "_uppercase"
    73  	}
    74  
    75  	if *settings.Number {
    76  		if !strings.ContainsAny(password, model.NUMBERS) {
    77  			isError = true
    78  		}
    79  
    80  		id = id + "_number"
    81  	}
    82  
    83  	if *settings.Symbol {
    84  		if !strings.ContainsAny(password, model.SYMBOLS) {
    85  			isError = true
    86  		}
    87  
    88  		id = id + "_symbol"
    89  	}
    90  
    91  	if isError {
    92  		return NewErrInvalidPassword(id + ".app_error")
    93  	}
    94  
    95  	return nil
    96  }