-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.go
435 lines (385 loc) · 12.2 KB
/
user.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package main
import (
"bytes"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/Microkubes/microservice-registration/app"
"github.com/Microkubes/microservice-registration/config"
"github.com/Microkubes/microservice-tools/rabbitmq"
"github.com/afex/hystrix-go/hystrix"
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/goadesign/goa"
uuid "github.com/satori/go.uuid"
)
// UserController implements the user resource.
type UserController struct {
*goa.Controller
Config *config.Config
ChannelRabbitMQ rabbitmq.Channel
Client *http.Client
}
// Email holds info for the email template
type Email struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Token string `json:"token,omitempty"`
}
// UserProfile represents User Profle
type UserProfile struct {
Fullname string
Email string
}
// NewUserController creates a user controller.
func NewUserController(service *goa.Service, config *config.Config, channelRabbitMQ rabbitmq.Channel, client *http.Client) *UserController {
return &UserController{
Controller: service.NewController("UserController"),
Config: config,
ChannelRabbitMQ: channelRabbitMQ,
Client: client,
}
}
// Register runs the register action. It creates a user and user profile.
// Also, it sends a massage to the queue in ordet microservice-mail to send
// varification mail to the user.
func (c *UserController) Register(ctx *app.RegisterUserContext) error {
user := &app.Users{}
token := generateToken(42)
ctx.Payload.Token = &token
// Create new user from payload
jsonUser, err := json.Marshal(ctx.Payload)
if err != nil {
c.Service.LogError("Register: Failed to deserialize payload", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
output := make(chan *http.Response, 1)
errorsChan := hystrix.Go("user-microservice.create_user", func() error {
resp, e := makeRequest(c.Client, http.MethodPost, jsonUser, c.Config.Services["user-microservice"], c.Config)
if e != nil {
return e
}
output <- resp
return nil
}, nil)
var createUserResp *http.Response
select {
case out := <-output:
createUserResp = out
case respErr := <-errorsChan:
c.Service.LogError("Register: Failed to create user.", "err", respErr.Error())
return ctx.InternalServerError(goa.ErrInternal(respErr))
}
body, err := ioutil.ReadAll(createUserResp.Body)
if err != nil {
c.Service.LogError("Register: Create user returned error response.", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
if createUserResp.StatusCode != 200 && createUserResp.StatusCode != 201 {
goaErr := &goa.ErrorResponse{}
err = json.Unmarshal(body, goaErr)
if err != nil {
c.Service.LogError("Register: Failed to deserialize create_user respose", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
switch createUserResp.StatusCode {
case 400:
c.Service.LogError("Register: Received bad request (400) error from user microservice.", "err", goaErr.Error())
return ctx.BadRequest(goaErr)
case 500:
c.Service.LogError("Register: Received internal error (500) error from user microservice.", "err", goaErr.Error())
return ctx.InternalServerError(goaErr)
}
}
if err = json.Unmarshal(body, &user); err != nil {
c.Service.LogError("Register: Deserialization error (create user body)", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
// Update user profile. Create it if does not exist
user.Fullname = ctx.Payload.Fullname
userProfile := UserProfile{user.Fullname, user.Email}
jsonUseProfile, err := json.Marshal(userProfile)
if err != nil {
c.Service.LogError("Register: Serialization error (update user profile body)", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
upOutput := make(chan *http.Response, 1)
upErrorChan := hystrix.Go("user-microservice.update_user_profile", func() error {
resp, errUserProfile := makeRequest(c.Client, http.MethodPut, jsonUseProfile, fmt.Sprintf("%s/%s", c.Config.Services["microservice-user-profile"], user.ID), c.Config)
if errUserProfile != nil {
return errUserProfile
}
upOutput <- resp
return nil
}, nil)
var createUpResp *http.Response
select {
case out := <-upOutput:
createUpResp = out
case respErr := <-upErrorChan:
c.Service.LogError("Register: Call to update user profile failed.", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(respErr))
}
body, err = ioutil.ReadAll(createUpResp.Body)
if err != nil {
c.Service.LogError("Register: Failed to read update user profile body.", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
if createUpResp.StatusCode != 200 && createUpResp.StatusCode != 204 {
goaErr := &goa.ErrorResponse{}
err = json.Unmarshal(body, goaErr)
if err != nil {
c.Service.LogError("Register: Deserialization error (update user profile body)", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
switch createUpResp.StatusCode {
case 400:
c.Service.LogError("Register: Received bad request (400) error from update user profile.", "err", err.Error())
return ctx.BadRequest(goaErr)
case 500:
c.Service.LogError("Register: Received internal error (500) from update user profile.", "err", err.Error())
return ctx.InternalServerError(goaErr)
}
}
if ctx.Payload.ExternalID == nil {
emailInfo := Email{
ID: user.ID,
Name: user.Fullname,
Email: user.Email,
Token: token,
}
body, err := json.Marshal(emailInfo)
fmt.Println("EMAIL INFO -> ", string(body))
if err != nil {
c.Service.LogError("Register: failed to serialize email payload.", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
if err := c.ChannelRabbitMQ.Send("verification-email", body); err != nil {
c.Service.LogError("Register: failed to serialize email payload.", "err", err.Error())
return ctx.InternalServerError(goa.ErrInternal(err))
}
}
c.Service.LogInfo("New user registered.", "id", user.ID)
return ctx.Created(user)
}
// ResendVerification resets the activation token and resends activation emal to user.
func (c *UserController) ResendVerification(ctx *app.ResendVerificationUserContext) error {
// 1. Reset user token
userID, token, err := c.resetVerificationToken(ctx.Payload.Email)
if err != nil {
if restErr, ok := err.(*RestClientError); ok {
switch restErr.Code {
case 404:
return ctx.BadRequest(fmt.Errorf("unknown email"))
case 400:
return ctx.BadRequest(err)
default:
return ctx.InternalServerError(err)
}
}
return ctx.InternalServerError(err)
}
// 2. Fetch user profile
profile, err := c.fetchUserProfile(userID)
if err != nil {
if restErr, ok := err.(*RestClientError); ok {
switch restErr.Code {
case 404:
profile = &UserProfile{
Fullname: userID,
}
case 400:
return ctx.BadRequest(err)
default:
return ctx.InternalServerError(err)
}
}
return ctx.InternalServerError(err)
}
// 3. Schedule send mail
if err = c.scheduleSendVerificationMail(userID, profile, token); err != nil {
return ctx.InternalServerError(err)
}
return ctx.OK([]byte{})
}
func (c *UserController) resetVerificationToken(email string) (userID, token string, err error) {
resetTokenPayload, err := json.Marshal(map[string]string{
"email": email,
})
if err != nil {
return "", "", err
}
resetTokenURL := fmt.Sprintf("%s/verification/reset", c.Config.Services["user-microservice"])
var resetResponse *http.Response
hystErr := hystrix.Do("user-microservice.reset_verification", func() error {
resp, e := makeRequest(c.Client, "POST", resetTokenPayload, resetTokenURL, c.Config)
if e != nil {
return e
}
resetResponse = resp
if resp.StatusCode != 200 {
return extractErrorMessage(resp)
}
return nil
}, nil)
if hystErr != nil {
return "", "", hystErr
}
respData, err := ioutil.ReadAll(resetResponse.Body)
if err != nil {
return "", "", err
}
tokenResponse := map[string]string{}
if err = json.Unmarshal(respData, &tokenResponse); err != nil {
return "", "", err
}
return tokenResponse["id"], tokenResponse["token"], nil
}
func (c *UserController) fetchUserProfile(userID string) (profile *UserProfile, err error) {
fetchUserProfileURL := fmt.Sprintf("%s/%s", c.Config.Services["microservice-user-profile"], userID)
var fetchProfileResp *http.Response
hystErr := hystrix.Do("user-profile.get_user_profile", func() error {
resp, e := makeRequest(c.Client, "GET", nil, fetchUserProfileURL, c.Config)
if e != nil {
return e
}
fetchProfileResp = resp
if resp.StatusCode != 200 {
return extractErrorMessage(resp)
}
return nil
}, nil)
if hystErr != nil {
return nil, hystErr
}
bodyData, err := ioutil.ReadAll(fetchProfileResp.Body)
if err != nil {
return nil, err
}
profile = &UserProfile{}
if err := json.Unmarshal(bodyData, &profile); err != nil {
return nil, err
}
return profile, nil
}
func (c *UserController) scheduleSendVerificationMail(userID string, profile *UserProfile, token string) error {
emailInfo := Email{
Email: profile.Email,
ID: userID,
Name: profile.Fullname,
Token: token,
}
body, err := json.Marshal(&emailInfo)
if err != nil {
return err
}
if err = c.ChannelRabbitMQ.Send("verification-email", body); err != nil {
return err
}
return nil
}
func extractErrorMessage(resp *http.Response) error {
if resp == nil || resp.Body == nil {
return &RestClientError{
Message: "no error in response",
}
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return &RestClientError{
Code: -1,
Message: fmt.Sprintf("IO Error on response read: %s", err.Error()),
}
}
result := map[string]interface{}{}
if err = json.Unmarshal(data, &result); err != nil {
return &RestClientError{
Code: -1,
Message: fmt.Sprintf("JSON Unmarshal error: %s", err.Error()),
}
}
if _, ok := result["message"]; ok {
if message, ok := result["message"].(string); ok {
return &RestClientError{
Code: resp.StatusCode,
StatusLine: resp.Status,
Message: message,
}
}
}
return &RestClientError{
Code: -1,
Message: "Unable to get error from response. Maybe not JSON response?",
}
}
// makeRequest makes http request
func makeRequest(client *http.Client, method string, payload []byte, url string, cfg *config.Config) (*http.Response, error) {
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
token, err := selfSignJWT(cfg)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, err
}
// selfSignJWT generates a JWT token which is self-signed with the system private key.
// This token is used for accesing the user and user-profile microservices.
func selfSignJWT(cfg *config.Config) (string, error) {
key, err := ioutil.ReadFile(cfg.SystemKey)
if err != nil {
return "", err
}
block, _ := pem.Decode(key)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
randUUID, err := uuid.NewV4()
if err != nil {
return "", err
}
claims := jwtgo.MapClaims{
"iss": "microservice-registration",
"exp": time.Now().Add(time.Duration(30) * time.Second).Unix(),
"jti": randUUID.String(),
"nbf": 0,
"sub": "microservice-registration",
"scope": "api:read",
"userId": "system",
"username": "system",
"roles": "system",
}
tokenRS := jwtgo.NewWithClaims(jwtgo.SigningMethodRS256, claims)
tokenStr, err := tokenRS.SignedString(privateKey)
return tokenStr, err
}
func generateToken(n int) string {
rv := make([]byte, n)
if _, err := rand.Reader.Read(rv); err != nil {
panic(err)
}
return base64.URLEncoding.EncodeToString(rv)
}
// RestClientError represents an error that occured in a REST call to a remote API.
type RestClientError struct {
Code int
StatusLine string
Message string
}
func (e *RestClientError) Error() string {
return fmt.Sprintf("%d %s %s", e.Code, e.StatusLine, e.Message)
}