forked from elgris/microservice-app-example
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuser.go
96 lines (71 loc) · 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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
)
var allowedUserHashes = map[string]interface{}{
"admin_admin": nil,
"johnd_foo": nil,
"janed_ddd": nil,
}
type User struct {
Username string `json:"username"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Role string `json:"role"`
}
type HTTPDoer interface {
Do(req *http.Request) (*http.Response, error)
}
type UserService struct {
Client HTTPDoer
UserAPIAddress string
AllowedUserHashes map[string]interface{}
}
func (h *UserService) Login(ctx context.Context, username, password string) (User, error) {
user, err := h.getUser(ctx, username)
if err != nil {
return user, err
}
userKey := fmt.Sprintf("%s_%s", username, password)
if _, ok := h.AllowedUserHashes[userKey]; !ok {
return user, ErrWrongCredentials // this is BAD, business logic layer must not return HTTP-specific errors
}
return user, nil
}
func (h *UserService) getUser(ctx context.Context, username string) (User, error) {
var user User
token, err := h.getUserAPIToken(username)
if err != nil {
return user, err
}
url := fmt.Sprintf("%s/users/%s", h.UserAPIAddress, username)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer "+token)
req = req.WithContext(ctx)
resp, err := h.Client.Do(req)
if err != nil {
return user, err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return user, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return user, fmt.Errorf("could not get user data: %s", string(bodyBytes))
}
err = json.Unmarshal(bodyBytes, &user)
return user, err
}
func (h *UserService) getUserAPIToken(username string) (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["username"] = username
claims["scope"] = "read"
return token.SignedString([]byte(jwtSecret))
}