-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
74 lines (62 loc) · 1.58 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
72
73
74
package domain
import (
"time"
"github.com/dgrijalva/jwt-go"
)
var jwtKey = []byte("my_secret_key") // TODO Add secret key in config
// Credentials defines the necessary parameters for a user to
// sign in and sign up
type Credentials struct {
Username string
Password string
Email string
}
// Claims defines the values we will add to the JWT claims
type Claims struct {
Username string
jwt.StandardClaims
}
// GetToken returns a JWT token with the username as a claim
func GetToken(username string) (string, error) {
expirationTime := time.Now().Add(5 * time.Minute) // TODO Set the time in config
claims := &Claims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", err
}
return tokenString, nil
}
// ValidateToken validates if a JWT is correct
func ValidateToken(token string) (bool, error) {
claims := &Claims{}
tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})
if err != nil {
return false, err
}
if !tkn.Valid {
return false, nil
}
return true, nil
}
// Validate checks that the required values of the credentials are filled and that they
// meet specific requirements
func (credentials *Credentials) Validate() bool {
if credentials.Username == "" {
return false
}
if credentials.Password == "" || len(credentials.Password) < 8 {
return false
}
if credentials.Email == "" {
return false
}
return true
}