-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.go
169 lines (143 loc) · 4.59 KB
/
users.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
package users
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/emicklei/go-restful"
"github.com/gtarcea/1DevDayTalk2014/app"
"github.com/gtarcea/1DevDayTalk2014/schema"
"github.com/gtarcea/1DevDayTalk2014/ws/events"
"github.com/gtarcea/1DevDayTalk2014/ws/rest"
)
// usersResource implements a users REST end point.
type usersResource struct {
users app.UsersService // Service to use to get/create users
privateKey []byte // The private key used to generate JWT tokens.
hub events.Hub // Hub to broadcast new users on.
}
// userReq is sent when a client creates a new user.
type userReq struct {
Email string `json:"email"`
Fullname string `json:"fullname"`
}
// loginReq is sent when a user attempts to login to the system.
type loginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
// NewResource creates a new REST resource for users.
func NewResource(users app.UsersService, privateKey []byte, hub events.Hub) *usersResource {
return &usersResource{
users: users,
privateKey: privateKey,
hub: hub,
}
}
// WebService creates a new restful service for users.
func (r *usersResource) WebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path("/users").
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON)
ws.Route(ws.GET("").To(rest.RouteHandler(r.getAllUsers)).
Doc("Retrieves all users").
Writes([]schema.User{}))
ws.Route(ws.GET("{email}").To(rest.RouteHandler(r.getUser)).
Doc("Retrieves a user by email address").
Param(ws.PathParameter("email", "email address of existing user").DataType("string")).
Writes(schema.User{}))
ws.Route(ws.POST("").To(rest.RouteHandler(r.createUser)).
Doc("Creates a new user account").
Reads(userReq{}).
Writes(schema.User{}))
ws.Route(ws.PUT("{email}").To(rest.RouteHandler(r.updateUser)).
Doc("Updates a user by email address").
Param(ws.PathParameter("email", "email address of existing user").DataType("string")).
Reads(userReq{}).
Writes(schema.User{}))
ws.Route(ws.POST("/login").To(rest.RouteHandler(r.login)).
Doc("User login").
Reads(loginReq{}).
Writes(schema.Auth{}))
return ws
}
// getAllUsers returns a list of all users.
func (r *usersResource) getAllUsers(request *restful.Request, response *restful.Response, user schema.User) (error, interface{}) {
users, err := r.users.GetAll()
return err, users
}
// getUser looks up a user by their email.
func (r *usersResource) getUser(request *restful.Request, response *restful.Response, user schema.User) (error, interface{}) {
email := request.PathParameter("email")
if email == "" {
return app.ErrInvalid, nil
}
user, err := r.users.GetUserByEmail(email)
if err != nil {
return err, nil
}
return nil, &user
}
// createUser adds a new user to the system.
func (r *usersResource) createUser(request *restful.Request, response *restful.Response, user schema.User) (error, interface{}) {
var req userReq
if err := request.ReadEntity(&req); err != nil {
return err, nil
}
u, err := r.users.CreateUser(req.Email, req.Fullname)
if err == nil {
msg := events.Message{
Event: "addeduser",
Data: u,
}
r.hub.Broadcast(msg)
}
return err, u
}
// updateUser updates an existing user
func (r *usersResource) updateUser(request *restful.Request, response *restful.Response, user schema.User) (error, interface{}) {
var req userReq
if err := request.ReadEntity(&req); err != nil {
return err, nil
}
u, err := r.users.UpdateUserByEmail(req.Email, req.Fullname)
if err == nil {
msg := events.Message{
// piggy back on addeduser since the client will figure out
// duplicates and updates.
Event: "addeduser",
Data: u,
}
r.hub.Broadcast(msg)
}
return err, u
}
// login processes a user login request. If successful it returns a JWT token that must
// be used on all requests.
func (r *usersResource) login(request *restful.Request, response *restful.Response, user schema.User) (error, interface{}) {
var req loginReq
if err := request.ReadEntity(&req); err != nil {
return err, nil
}
if err := r.authenticate(req); err != nil {
return err, nil
}
// Create the JWT Token
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims["ID"] = req.Username
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
tokenStr, err := token.SignedString(r.privateKey)
if err != nil {
return err, nil
}
auth := schema.Auth{
Username: req.Username,
Token: tokenStr,
}
return nil, &auth
}
func (r *usersResource) authenticate(req loginReq) error {
if req.Username != "admin" || req.Password != "admin" {
return app.ErrNoAccess
}
return nil
}