-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler_login.go
71 lines (57 loc) · 1.58 KB
/
handler_login.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 auth
import (
"time"
"github.com/boreq/errors"
)
type Login struct {
Username string
Password string
}
type LoginHandler struct {
passwordHasher PasswordHasher
transactionProvider TransactionProvider
accessTokenGenerator AccessTokenGenerator
}
func NewLoginHandler(
passwordHasher PasswordHasher,
transactionProvider TransactionProvider,
accessTokenGenerator AccessTokenGenerator,
) *LoginHandler {
return &LoginHandler{
passwordHasher: passwordHasher,
transactionProvider: transactionProvider,
accessTokenGenerator: accessTokenGenerator,
}
}
func (h *LoginHandler) Execute(cmd Login) (AccessToken, error) {
if err := validate(cmd.Username, cmd.Password); err != nil {
return "", errors.Wrap(ErrUnauthorized, "invalid parameters")
}
var token AccessToken
if err := h.transactionProvider.Write(func(r *TransactableRepositories) error {
u, err := r.Users.Get(cmd.Username)
if err != nil {
if errors.Is(err, ErrNotFound) {
return errors.Wrap(ErrUnauthorized, "user not found")
}
return errors.Wrap(err, "could not get the user")
}
if err := h.passwordHasher.Compare(u.Password, cmd.Password); err != nil {
return errors.Wrap(ErrUnauthorized, "invalid password")
}
t, err := h.accessTokenGenerator.Generate(cmd.Username)
if err != nil {
return errors.Wrap(err, "could not create an access token")
}
token = t
s := Session{
Token: t,
LastSeen: time.Now(),
}
u.Sessions = append(u.Sessions, s)
return r.Users.Put(*u)
}); err != nil {
return "", errors.Wrap(err, "transaction failed")
}
return token, nil
}