[MM-33794] Improve password generation during bulk import (#17147)

Automatic Merge
Этот коммит содержится в:
Claudio Costa
2021-03-24 10:32:16 +01:00
коммит произвёл GitHub
родитель 2789be220b
Коммит 6a65b6ceca
6 изменённых файлов: 110 добавлений и 73 удалений

Просмотреть файл

@@ -9,13 +9,10 @@ import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"regexp"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"golang.org/x/crypto/bcrypt"
@@ -940,41 +937,3 @@ func UsersWithGroupsAndCountFromJson(data io.Reader) *UsersWithGroupsAndCount {
json.Unmarshal(bodyBytes, uwg)
return uwg
}
//msgp:ignore lockedRand
type lockedRand struct {
mu sync.Mutex
rn *rand.Rand
}
func (r *lockedRand) Intn(n int) int {
r.mu.Lock()
m := r.rn.Intn(n)
r.mu.Unlock()
return m
}
var passwordRandom = lockedRand{
rn: rand.New(rand.NewSource(time.Now().Unix())),
}
var passwordSpecialChars = "!$%^&*(),."
var passwordNumbers = "0123456789"
var passwordUpperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var passwordLowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"
var passwordAllChars = passwordSpecialChars + passwordNumbers + passwordUpperCaseLetters + passwordLowerCaseLetters
func GeneratePassword(minimumLength int) string {
// Make sure we are guaranteed at least one of each type to meet any possible password complexity requirements.
password := string([]rune(passwordUpperCaseLetters)[passwordRandom.Intn(len(passwordUpperCaseLetters))]) +
string([]rune(passwordNumbers)[passwordRandom.Intn(len(passwordNumbers))]) +
string([]rune(passwordLowerCaseLetters)[passwordRandom.Intn(len(passwordLowerCaseLetters))]) +
string([]rune(passwordSpecialChars)[passwordRandom.Intn(len(passwordSpecialChars))])
for len(password) < minimumLength {
i := passwordRandom.Intn(len(passwordAllChars))
password = password + string([]rune(passwordAllChars)[i])
}
return password
}

Просмотреть файл

@@ -5,7 +5,6 @@ package model
import (
"fmt"
"math/rand"
"net/http"
"strings"
"testing"
@@ -351,33 +350,3 @@ func TestUserSlice(t *testing.T) {
assert.Equal(t, 1, len(nonBotUsers))
})
}
func TestGeneratePassword(t *testing.T) {
passwordRandom = lockedRand{
rn: rand.New(rand.NewSource(12345)),
}
t.Run("Should be the minimum length or 4, whichever is less", func(t *testing.T) {
password1 := GeneratePassword(5)
assert.Len(t, password1, 5)
password2 := GeneratePassword(10)
assert.Len(t, password2, 10)
password3 := GeneratePassword(1)
assert.Len(t, password3, 4)
})
t.Run("Should contain at least one of symbols, upper case, lower case and numbers", func(t *testing.T) {
password := GeneratePassword(4)
require.Len(t, password, 4)
assert.Contains(t, []rune(passwordUpperCaseLetters), []rune(password)[0])
assert.Contains(t, []rune(passwordNumbers), []rune(password)[1])
assert.Contains(t, []rune(passwordLowerCaseLetters), []rune(password)[2])
assert.Contains(t, []rune(passwordSpecialChars), []rune(password)[3])
})
t.Run("Should not fail on concurrent calls", func(t *testing.T) {
for i := 0; i < 10; i++ {
go GeneratePassword(10)
}
})
}