summaryrefslogtreecommitdiffstats
path: root/modules/password/password.go
blob: 54131b96415569ffdbbfb34079dc869edef982dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package password

import (
	"crypto/rand"
	"math/big"
	"regexp"
	"sync"

	"code.gitea.io/gitea/modules/setting"
)

var matchComplexities = map[string]regexp.Regexp{}
var matchComplexityOnce sync.Once
var validChars string
var validComplexities = map[string]string{
	"lower": "abcdefghijklmnopqrstuvwxyz",
	"upper": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
	"digit": "0123456789",
	"spec":  `][ !"#$%&'()*+,./:;<=>?@\^_{|}~` + "`-",
}

// NewComplexity for preparation
func NewComplexity() {
	matchComplexityOnce.Do(func() {
		if len(setting.PasswordComplexity) > 0 {
			for key, val := range setting.PasswordComplexity {
				matchComplexity := regexp.MustCompile(val)
				matchComplexities[key] = *matchComplexity
				validChars += validComplexities[key]
			}
		} else {
			for _, val := range validComplexities {
				validChars += val
			}
		}
	})
}

// IsComplexEnough return True if password is Complexity
func IsComplexEnough(pwd string) bool {
	if len(setting.PasswordComplexity) > 0 {
		NewComplexity()
		for _, val := range matchComplexities {
			if !val.MatchString(pwd) {
				return false
			}
		}
	}
	return true
}

// Generate  a random password
func Generate(n int) (string, error) {
	NewComplexity()
	buffer := make([]byte, n)
	max := big.NewInt(int64(len(validChars)))
	for {
		for j := 0; j < n; j++ {
			rnd, err := rand.Int(rand.Reader, max)
			if err != nil {
				return "", err
			}
			buffer[j] = validChars[rnd.Int64()]
		}
		if IsComplexEnough(string(buffer)) && string(buffer[0]) != " " && string(buffer[n-1]) != " " {
			return string(buffer), nil
		}
	}
}