-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
71 lines (64 loc) · 1.6 KB
/
auth.go
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
package guide
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"golang.org/x/crypto/argon2"
"regexp"
)
type user struct {
Id int64
Username, Password, Email string
}
func newUser(username, password, confirmPassword, email string) (user, error) {
if username == "" {
return user{}, errors.New("username cannot be empty")
}
if password == "" {
return user{}, errors.New("password cannot be empty")
}
if len(password) < 8 {
return user{}, errors.New("password has to be at least 8 characters long")
}
if password != confirmPassword {
return user{}, errors.New("passwords do not match")
}
if email == "" {
return user{}, errors.New("email cannot be empty")
}
match := rxEmail.Match([]byte(email))
if !match {
return user{}, errors.New("email has to be a valid address")
}
salt, err := generateSalt(saltSize)
hashedPassword := argon2.IDKey([]byte(password), salt, argon2Time, argon2Memory, argon2Threads, argon2KeyLen)
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
encodedPassword := base64.RawStdEncoding.EncodeToString(hashedPassword)
encodedHash := fmt.Sprintf("%s%s", encodedSalt, encodedPassword)
if err != nil {
return user{}, err
}
u := user{
Username: username,
Password: encodedHash,
Email: email,
}
return u, nil
}
func generateSalt(size int) ([]byte, error) {
b := make([]byte, size)
_, err := rand.Read(b)
if err != nil {
return []byte{}, err
}
return b, nil
}
var rxEmail = regexp.MustCompile(".+@.+\\..+")
const (
argon2Time = 1
argon2Memory = 64 * 1024
argon2Threads = 24
argon2KeyLen = 32
saltSize = 16
)