-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
190 lines (148 loc) · 5.73 KB
/
service.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package login
import (
"encoding/json"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/monologid/m9/config"
"golang.org/x/crypto/bcrypt"
)
// IService is an interface for login service
type IService interface {
SignInUsingServiceProvider(serviceProvider string, profile map[string]interface{}) error
RegisterNewAccountUsingServiceProvider(serviceProvider string, profile map[string]interface{}) error
RegisterNewAccount(newAccount ReqRegisterModel) error
SignIn(loginReq ReqLoginModel) error
GenerateAccessToken() (string, error)
}
// Service is the implementation of login.IService
type Service struct {
LoginRepository IRepository
Account AccountModel
}
// SignInUsingServiceProvider returns nil once the login or registration using service provider is succeeded
func (s *Service) SignInUsingServiceProvider(serviceProvider string, profile map[string]interface{}) error {
email, ok := profile["email"]
if !ok {
return errors.New("unable to retrieve profile from" + serviceProvider)
}
account, err := s.LoginRepository.FindOneByEmail(fmt.Sprintf("%v", email))
if err != nil {
return err
}
if account.ID.String() == "00000000-0000-0000-0000-000000000000" {
return s.RegisterNewAccountUsingServiceProvider(serviceProvider, profile)
}
s.Account = *account
return nil
}
// RegisterNewAccountUsingServiceProvider returns nil when registration new account using service provider is succeded.
// This method will parse data from service provider and construct it using the AccountModel and AccountServiceModel.
// All data other than basic fields will be stored in AccountServiceModel.Metadata.
func (s *Service) RegisterNewAccountUsingServiceProvider(serviceProvider string, profile map[string]interface{}) error {
MetricInitiateAccountRegistration(serviceProvider)
var account AccountModel
metadata, err := json.Marshal(profile)
if err != nil {
MetricInitiateAccountRegistrationFailed(serviceProvider)
return errors.New("failed to convert profile metadata")
}
account.AccountServiceProvider.ServiceProvider = serviceProvider
account.AccountServiceProvider.Metadata = metadata
if serviceProvider == "facebook" {
account.Email = fmt.Sprintf("%v", profile["email"])
account.FirstName = fmt.Sprintf("%v", profile["first_name"])
account.LastName = fmt.Sprintf("%v", profile["last_name"])
account.AccountServiceProvider.ServiceProviderID = fmt.Sprintf("%v", profile["id"])
if picURL, ok := profile["picture"].(map[string]interface{})["data"].(map[string]interface{})["url"]; ok {
account.PicURL = fmt.Sprintf("%v", picURL)
account.AccountServiceProvider.PicURL = account.PicURL
}
} else if serviceProvider == "google" {
account.Email = fmt.Sprintf("%v", profile["email"])
account.FirstName = fmt.Sprintf("%v", profile["given_name"])
account.LastName = fmt.Sprintf("%v", profile["family_name"])
account.PicURL = fmt.Sprintf("%v", profile["picture"])
account.AccountServiceProvider.ServiceProviderID = fmt.Sprintf("%v", profile["sub"])
account.AccountServiceProvider.PicURL = account.PicURL
} else {
return errors.New("invalid service provider")
}
s.Account = account
return s.LoginRepository.Insert(account)
}
// RegisterNewAccount returns nil if registration using default method is success.
func (s *Service) RegisterNewAccount(newAccount ReqRegisterModel) error {
errValidate := newAccount.Validate()
if errValidate != nil {
return errValidate
}
tempAccount, err := s.LoginRepository.FindOneByEmail(newAccount.Email)
if err != nil {
return err
}
if tempAccount.Email == newAccount.Email && tempAccount.ID.String() != "00000000-0000-0000-0000-000000000000" {
return errors.New("email has been registered")
}
account := AccountModel{
FirstName: newAccount.FirstName,
LastName: newAccount.LastName,
Email: newAccount.Email,
}
accountServiceProvider := AccountServiceProviderModel{
ServiceProvider: "default",
}
account.AccountServiceProvider = accountServiceProvider
passwd, err := bcrypt.GenerateFromPassword([]byte(newAccount.Password), bcrypt.MinCost)
if err != nil {
fmt.Println(err)
return errors.New("failed to encrypt password")
}
account.Password = string(passwd)
s.Account = account
return s.LoginRepository.Insert(account)
}
// SignIn returns nil if email and password are verified
func (s *Service) SignIn(loginReq ReqLoginModel) error {
errValidate := loginReq.Validate()
if errValidate != nil {
return errValidate
}
tempAccount, err := s.LoginRepository.FindOneByEmail(loginReq.Email)
if err != nil {
return err
}
if tempAccount.Email != loginReq.Email && tempAccount.ID.String() == "00000000-0000-0000-0000-000000000000" {
return errors.New("invalid email address")
}
if errCheckPassword := bcrypt.CompareHashAndPassword([]byte(tempAccount.Password), []byte(loginReq.Password)); errCheckPassword != nil {
return errCheckPassword
}
s.Account = *tempAccount
return nil
}
// GenerateAccessToken returns access token in JWT format.
// The claim is based on data when being set in registration or login methods using the AccountModel.
func (s *Service) GenerateAccessToken() (string, error) {
if s.Account.ID.String() == "00000000-0000-0000-0000-000000000000" {
tempAccount, err := s.LoginRepository.FindOneByEmail(s.Account.Email)
if err != nil {
return "", err
}
s.Account.ID = tempAccount.ID
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"_id": s.Account.ID,
"firstName": s.Account.FirstName,
"lastName": s.Account.LastName,
"email": s.Account.Email,
"profilePic": s.Account.PicURL,
})
return token.SignedString([]byte(config.C.Security.JWT.Secret))
}
// NewService initiates new login service
func NewService(loginRepository IRepository) IService {
return &Service{
LoginRepository: loginRepository,
}
}