-
Notifications
You must be signed in to change notification settings - Fork 5
/
auth.go
60 lines (50 loc) · 1.32 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
package auth
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"errors"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"golang.org/x/crypto/pbkdf2"
)
var (
ITERATIONS int
HASH_LENGTH int
TIME_PERIOD int64
ISSUER string
JWTSECRET string
)
type AuthModel struct {
Username string `gorm:"not null;unique"`
Password []byte `gorm:"non null"`
Role string `gorm:"non null"`
Salt []byte
}
func CreateModel(username, password, role string) AuthModel {
salt := make([]byte, 16)
rand.Read(salt)
auth1 := AuthModel{
Username: username,
Password: pbkdf2.Key([]byte(password), salt, ITERATIONS, HASH_LENGTH, sha256.New),
Salt: salt,
Role: role,
}
return auth1
}
func Authenticate(username, password string, authEntry AuthModel) (string, error) {
hashedPassword := pbkdf2.Key([]byte(password), authEntry.Salt, ITERATIONS, HASH_LENGTH, sha256.New)
if !bytes.Equal(hashedPassword, authEntry.Password) {
return "", errors.New("The username or password is invalid")
}
return GenerateJWT(authEntry)
}
func Init(iter, hashLength int, timePeriod int64, issuer, jwtSecret string, managerRoles, adminRoles, userRoles []string) {
ITERATIONS = iter
HASH_LENGTH = hashLength
TIME_PERIOD = timePeriod
ISSUER = issuer
JWTSECRET = jwtSecret
ManagerRoles = managerRoles
AdminRoles = adminRoles
UserRoles = userRoles
}