-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAuthenticatorService.go
112 lines (101 loc) · 2.52 KB
/
AuthenticatorService.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package services
import (
"bytes"
"encoding/base64"
"image/png"
"backend/internal"
"backend/kernel"
"backend/models"
"github.com/pquerna/otp/totp"
)
type (
AuthenticatorService struct {
us *UserService
}
)
func NewAuthenticatorService(us *UserService) *AuthenticatorService {
return &AuthenticatorService{us: us}
}
func (s *AuthenticatorService) Process(m *models.User, r *models.Authenticator) error {
if m.AuthenticatorEnabled {
return s.DisableAuthenticator(m, r)
}
return s.EnableAuthenticator(m, r)
}
func (s *AuthenticatorService) Generate(m *models.User) (*models.Authenticator, error) {
if !m.RecoveryQuestionsSet {
return nil, internal.ErrRecoveryQuestionNotSet
}
if m.AuthenticatorEnabled {
return nil, internal.ErrAuthenticatorAlreadyEnabled
}
key, err := totp.Generate(totp.GenerateOpts{
Issuer: kernel.App.Host,
AccountName: m.Email,
})
if err != nil {
return nil, err
}
var buf bytes.Buffer
img, err := key.Image(200, 200)
if err != nil {
return nil, err
}
err = png.Encode(&buf, img)
if err != nil {
return nil, err
}
a := new(models.Authenticator)
a.Seed = key.Secret()
a.URL = key.URL()
a.Image = base64.StdEncoding.EncodeToString(buf.Bytes())
m.AuthenticatorSecret = key.Secret()
err = s.us.Save(m)
if err != nil {
return nil, err
}
return a, nil
}
func (s *AuthenticatorService) DisableMFA(r *models.DisableMFA) error {
u, err := s.us.Authenticate(r.Username, r.Password)
if err != nil {
return err
}
// b, err := s.us.ValidateRecoveryQuestions(u, r.RecoveryQuestions)
// if err != nil {
// return err
// }
// if !b {
// return internal.ErrBadRecoveryAnswers
// }
u.DisableAuthenticator()
u.UnVerifyMobile()
return s.us.Save(u)
}
func (s *AuthenticatorService) DisableAuthenticator(m *models.User, r *models.Authenticator) error {
if !totp.Validate(r.Code, m.AuthenticatorSecret) {
return internal.ErrInvalidAuthenticatorCode
}
m.DisableAuthenticator()
return s.us.Save(m)
}
func (s *AuthenticatorService) EnableAuthenticator(m *models.User, r *models.Authenticator) error {
if !m.RecoveryQuestionsSet {
return internal.ErrRecoveryQuestionNotSet
}
if !totp.Validate(r.Code, m.AuthenticatorSecret) {
return internal.ErrInvalidAuthenticatorCode
}
m.AuthenticatorEnabled = true
err := s.us.Save(m)
if err != nil {
return err
}
return nil
}
func (s *AuthenticatorService) ValidateAuthenticator(m *models.User, code string) error {
if !totp.Validate(code, m.AuthenticatorSecret) {
return internal.ErrInvalidAuthenticatorCode
}
return nil
}