-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
79 lines (64 loc) · 1.75 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
75
76
package service
import (
"crypto/sha1"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/p-12s/todo-list-rest-api"
"github.com/p-12s/todo-list-rest-api/pkg/repository"
"time"
)
const (
salt = "kjalsdfasfjasdf"
tokenTTL = 12 * time.Hour
signingKey = "jkadf*^(&le23#a0d9"
)
type tokenClaims struct {
jwt.StandardClaims
UserId int `json:"user_id"`
}
type AuthService struct {
repo repository.Authorization
}
func NewAuthService(repo repository.Authorization) *AuthService {
return &AuthService{repo: repo}
}
func (s *AuthService) CreateUser(user todo.User) (int, error) {
user.Password = generatePasswordHash(user.Password)
return s.repo.CreateUser(user)
}
func (s *AuthService) GenerateToken(username, password string) (string, error) {
user, err := s.repo.GetUser(username, generatePasswordHash(password))
if err != nil {
return "", err
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &tokenClaims{
jwt.StandardClaims{
ExpiresAt: time.Now().Add(tokenTTL).Unix(),
IssuedAt: time.Now().Unix(),
},
user.Id,
})
return token.SignedString([]byte(signingKey))
}
func (s *AuthService) ParseToken(accessToken string) (int, error) {
token, err := jwt.ParseWithClaims(accessToken, &tokenClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("invalid signing method")
}
return []byte(signingKey), nil
})
if err != nil {
return 0, err
}
claims, ok := token.Claims.(*tokenClaims)
if !ok {
return 0, errors.New("token claims are not of type *tokenClaims")
}
return claims.UserId, nil
}
func generatePasswordHash(password string) string {
hash := sha1.New()
hash.Write([]byte(password))
return fmt.Sprintf("%x", hash.Sum([]byte(salt)))
}