|
| 1 | +// Copyright 2019 The Gitea Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package password |
| 6 | + |
| 7 | +import ( |
| 8 | + "crypto/rand" |
| 9 | + "math/big" |
| 10 | + "regexp" |
| 11 | + "sync" |
| 12 | + |
| 13 | + "code.gitea.io/gitea/modules/setting" |
| 14 | +) |
| 15 | + |
| 16 | +var matchComplexities = map[string]regexp.Regexp{} |
| 17 | +var matchComplexityOnce sync.Once |
| 18 | +var validChars string |
| 19 | +var validComplexities = map[string]string{ |
| 20 | + "lower": "abcdefghijklmnopqrstuvwxyz", |
| 21 | + "upper": "ABCDEFGHIJKLMNOPQRSTUVWXYZ", |
| 22 | + "digit": "0123456789", |
| 23 | + "spec": `][ !"#$%&'()*+,./:;<=>?@\^_{|}~` + "`-", |
| 24 | +} |
| 25 | + |
| 26 | +// NewComplexity for preparation |
| 27 | +func NewComplexity() { |
| 28 | + matchComplexityOnce.Do(func() { |
| 29 | + if len(setting.PasswordComplexity) > 0 { |
| 30 | + for key, val := range setting.PasswordComplexity { |
| 31 | + matchComplexity := regexp.MustCompile(val) |
| 32 | + matchComplexities[key] = *matchComplexity |
| 33 | + validChars += validComplexities[key] |
| 34 | + } |
| 35 | + } else { |
| 36 | + for _, val := range validComplexities { |
| 37 | + validChars += val |
| 38 | + } |
| 39 | + } |
| 40 | + }) |
| 41 | +} |
| 42 | + |
| 43 | +// IsComplexEnough return True if password is Complexity |
| 44 | +func IsComplexEnough(pwd string) bool { |
| 45 | + if len(setting.PasswordComplexity) > 0 { |
| 46 | + NewComplexity() |
| 47 | + for _, val := range matchComplexities { |
| 48 | + if !val.MatchString(pwd) { |
| 49 | + return false |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return true |
| 54 | +} |
| 55 | + |
| 56 | +// Generate a random password |
| 57 | +func Generate(n int) (string, error) { |
| 58 | + NewComplexity() |
| 59 | + buffer := make([]byte, n) |
| 60 | + max := big.NewInt(int64(len(validChars))) |
| 61 | + for { |
| 62 | + for j := 0; j < n; j++ { |
| 63 | + rnd, err := rand.Int(rand.Reader, max) |
| 64 | + if err != nil { |
| 65 | + return "", err |
| 66 | + } |
| 67 | + buffer[j] = validChars[rnd.Int64()] |
| 68 | + } |
| 69 | + if IsComplexEnough(string(buffer)) && string(buffer[0]) != " " && string(buffer[n-1]) != " " { |
| 70 | + return string(buffer), nil |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments