github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/app/import_utils.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"crypto/rand"
     8  	"math/big"
     9  )
    10  
    11  const (
    12  	passwordSpecialChars     = "!$%^&*(),."
    13  	passwordNumbers          = "0123456789"
    14  	passwordUpperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    15  	passwordLowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"
    16  	passwordAllChars         = passwordSpecialChars + passwordNumbers + passwordUpperCaseLetters + passwordLowerCaseLetters
    17  )
    18  
    19  func randInt(max int) (int, error) {
    20  	val, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
    21  	if err != nil {
    22  		return 0, err
    23  	}
    24  	return int(val.Int64()), nil
    25  }
    26  
    27  func generatePassword(minimumLength int) (string, error) {
    28  	upperIdx, err := randInt(len(passwordUpperCaseLetters))
    29  	if err != nil {
    30  		return "", err
    31  	}
    32  	numberIdx, err := randInt(len(passwordNumbers))
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  	lowerIdx, err := randInt(len(passwordLowerCaseLetters))
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  	specialIdx, err := randInt(len(passwordSpecialChars))
    41  	if err != nil {
    42  		return "", err
    43  	}
    44  
    45  	// Make sure we are guaranteed at least one of each type to meet any possible password complexity requirements.
    46  	password := string([]rune(passwordUpperCaseLetters)[upperIdx]) +
    47  		string([]rune(passwordNumbers)[numberIdx]) +
    48  		string([]rune(passwordLowerCaseLetters)[lowerIdx]) +
    49  		string([]rune(passwordSpecialChars)[specialIdx])
    50  
    51  	for len(password) < minimumLength {
    52  		i, err := randInt(len(passwordAllChars))
    53  		if err != nil {
    54  			return "", err
    55  		}
    56  		password = password + string([]rune(passwordAllChars)[i])
    57  	}
    58  
    59  	return password, nil
    60  }