-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
user_controller.go
352 lines (317 loc) · 12.2 KB
/
user_controller.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
package web
import (
"net/http"
"strings"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/jackc/pgconn"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink/v2/core/auth"
"github.com/smartcontractkit/chainlink/v2/core/logger/audit"
"github.com/smartcontractkit/chainlink/v2/core/services/chainlink"
clsession "github.com/smartcontractkit/chainlink/v2/core/sessions"
"github.com/smartcontractkit/chainlink/v2/core/utils"
webauth "github.com/smartcontractkit/chainlink/v2/core/web/auth"
"github.com/smartcontractkit/chainlink/v2/core/web/presenters"
)
// UserController manages the current Session's User.
type UserController struct {
App chainlink.Application
}
// UpdatePasswordRequest defines the request to set a new password for the
// current session's User.
type UpdatePasswordRequest struct {
OldPassword string `json:"oldPassword"`
NewPassword string `json:"newPassword"`
}
var errUnsupportedForAuth = errors.New("action is unsupported with configured authentication provider")
// Index lists all API users
func (c *UserController) Index(ctx *gin.Context) {
users, err := c.App.AuthenticationProvider().ListUsers()
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("Unable to list users", "err", err)
jsonAPIError(ctx, http.StatusInternalServerError, err)
return
}
jsonAPIResponse(ctx, presenters.NewUserResources(users), "users")
}
// Create creates a new API user with provided context arguments.
func (c *UserController) Create(ctx *gin.Context) {
type newUserRequest struct {
Email string `json:"email"`
Password string `json:"password"`
Role string `json:"role"`
}
var request newUserRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
userRole, err := clsession.GetUserRole(request.Role)
if err != nil {
jsonAPIError(ctx, http.StatusBadRequest, err)
return
}
if verr := clsession.ValidateEmail(request.Email); verr != nil {
jsonAPIError(ctx, http.StatusBadRequest, verr)
return
}
if verr := utils.VerifyPasswordComplexity(request.Password, request.Email); verr != nil {
jsonAPIError(ctx, http.StatusBadRequest, verr)
return
}
user, err := clsession.NewUser(request.Email, request.Password, userRole)
if err != nil {
jsonAPIError(ctx, http.StatusBadRequest, errors.Errorf("error creating API user: %s", err))
return
}
if err = c.App.AuthenticationProvider().CreateUser(&user); err != nil {
// If this is a duplicate key error (code 23505), return a nicer error message
var pgErr *pgconn.PgError
if ok := errors.As(err, &pgErr); ok {
if pgErr.Code == "23505" {
jsonAPIError(ctx, http.StatusBadRequest, errors.Errorf("user with email %s already exists", request.Email))
return
}
}
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("Error creating new API user", "err", err)
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("error creating API user"))
return
}
jsonAPIResponse(ctx, presenters.NewUserResource(user), "user")
}
// UpdateRole changes role field of a specified API user.
func (c *UserController) UpdateRole(ctx *gin.Context) {
type updateUserRequest struct {
Email string `json:"email"`
NewRole string `json:"newRole"`
}
var request updateUserRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
// Don't allow current admin user to edit self
sessionUser, ok := webauth.GetAuthenticatedUser(ctx)
if !ok {
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("failed to obtain current user from context"))
return
}
if strings.EqualFold(sessionUser.Email, request.Email) {
jsonAPIError(ctx, http.StatusBadRequest, errors.New("can not change state or permissions of current admin user"))
return
}
// In case email/role is not specified try to give friendlier/actionable error messages
if request.Email == "" {
jsonAPIError(ctx, http.StatusBadRequest, errors.New("email flag is empty, must specify an email"))
return
}
if request.NewRole == "" {
jsonAPIError(ctx, http.StatusBadRequest, errors.New("new-role flag is empty, must specify a new role, possible options are 'admin', 'edit', 'run', 'view'"))
return
}
_, err := clsession.GetUserRole(request.NewRole)
if err != nil {
jsonAPIError(ctx, http.StatusBadRequest, errors.New("new role does not exist, possible options are 'admin', 'edit', 'run', 'view'"))
return
}
user, err := c.App.AuthenticationProvider().UpdateRole(request.Email, request.NewRole)
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
jsonAPIError(ctx, http.StatusInternalServerError, errors.Wrap(err, "error updating API user"))
return
}
jsonAPIResponse(ctx, presenters.NewUserResource(user), "user")
}
// Delete deletes an API user and any sessions by email
func (c *UserController) Delete(ctx *gin.Context) {
email := ctx.Param("email")
// Attempt find user by email
user, err := c.App.AuthenticationProvider().FindUser(email)
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
jsonAPIError(ctx, http.StatusBadRequest, errors.Errorf("specified user not found: %s", email))
return
}
// Don't allow current admin user to delete self
sessionUser, ok := webauth.GetAuthenticatedUser(ctx)
if !ok {
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("failed to obtain current user from context"))
return
}
if strings.EqualFold(sessionUser.Email, email) {
jsonAPIError(ctx, http.StatusBadRequest, errors.New("can not delete currently logged in admin user"))
return
}
if err = c.App.AuthenticationProvider().DeleteUser(email); err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("Error deleting API user", "err", err)
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("error deleting API user"))
return
}
jsonAPIResponse(ctx, presenters.NewUserResource(user), "user")
}
// UpdatePassword changes the password for the current User.
func (c *UserController) UpdatePassword(ctx *gin.Context) {
var request UpdatePasswordRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
sessionUser, ok := webauth.GetAuthenticatedUser(ctx)
if !ok {
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("failed to obtain current user from context"))
return
}
user, err := c.App.AuthenticationProvider().FindUser(sessionUser.Email)
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("failed to obtain current user record: %s", err)
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("unable to update password"))
return
}
if !utils.CheckPasswordHash(request.OldPassword, user.HashedPassword) {
c.App.GetAuditLogger().Audit(audit.PasswordResetAttemptFailedMismatch, map[string]interface{}{"user": user.Email})
jsonAPIError(ctx, http.StatusConflict, errors.New("old password does not match"))
return
}
if err := utils.VerifyPasswordComplexity(request.NewPassword, user.Email); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
if err := c.updateUserPassword(ctx, &user, request.NewPassword); err != nil {
jsonAPIError(ctx, http.StatusInternalServerError, err)
return
}
c.App.GetAuditLogger().Audit(audit.PasswordResetSuccess, map[string]interface{}{"user": user.Email})
jsonAPIResponse(ctx, presenters.NewUserResource(user), "user")
}
// NewAPIToken generates a new API token for a user overwriting any pre-existing one set.
func (c *UserController) NewAPIToken(ctx *gin.Context) {
var request clsession.ChangeAuthTokenRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
sessionUser, ok := webauth.GetAuthenticatedUser(ctx)
if !ok {
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("failed to obtain current user from context"))
return
}
user, err := c.App.AuthenticationProvider().FindUser(sessionUser.Email)
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("failed to obtain current user record: %s", err)
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("unable to create API token"))
return
}
// In order to create an API token, login validation with provided password must succeed
err = c.App.AuthenticationProvider().TestPassword(sessionUser.Email, request.Password)
if err != nil {
c.App.GetAuditLogger().Audit(audit.APITokenCreateAttemptPasswordMismatch, map[string]interface{}{"user": user.Email})
jsonAPIError(ctx, http.StatusUnauthorized, errors.New("incorrect password"))
return
}
newToken := auth.NewToken()
if err := c.App.AuthenticationProvider().SetAuthToken(&user, newToken); err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
jsonAPIError(ctx, http.StatusInternalServerError, err)
return
}
c.App.GetAuditLogger().Audit(audit.APITokenCreated, map[string]interface{}{"user": user.Email})
jsonAPIResponseWithStatus(ctx, newToken, "auth_token", http.StatusCreated)
}
// DeleteAPIToken deletes and disables a user's API token.
func (c *UserController) DeleteAPIToken(ctx *gin.Context) {
var request clsession.ChangeAuthTokenRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
jsonAPIError(ctx, http.StatusUnprocessableEntity, err)
return
}
sessionUser, ok := webauth.GetAuthenticatedUser(ctx)
if !ok {
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("failed to obtain current user from context"))
return
}
user, err := c.App.AuthenticationProvider().FindUser(sessionUser.Email)
if err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
c.App.GetLogger().Errorf("failed to obtain current user record: %s", err)
jsonAPIError(ctx, http.StatusInternalServerError, errors.New("unable to delete API token"))
return
}
err = c.App.AuthenticationProvider().TestPassword(sessionUser.Email, request.Password)
if err != nil {
c.App.GetAuditLogger().Audit(audit.APITokenDeleteAttemptPasswordMismatch, map[string]interface{}{"user": user.Email})
jsonAPIError(ctx, http.StatusUnauthorized, errors.New("incorrect password"))
return
}
if err := c.App.AuthenticationProvider().DeleteAuthToken(&user); err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
jsonAPIError(ctx, http.StatusBadRequest, errUnsupportedForAuth)
return
}
jsonAPIError(ctx, http.StatusInternalServerError, err)
return
}
{
c.App.GetAuditLogger().Audit(audit.APITokenDeleted, map[string]interface{}{"user": user.Email})
jsonAPIResponseWithStatus(ctx, nil, "auth_token", http.StatusNoContent)
}
}
func getCurrentSessionID(ctx *gin.Context) (string, error) {
session := sessions.Default(ctx)
sessionID, ok := session.Get(webauth.SessionIDKey).(string)
if !ok {
return "", errors.New("unable to get current session ID")
}
return sessionID, nil
}
func (c *UserController) updateUserPassword(ctx *gin.Context, user *clsession.User, newPassword string) error {
sessionID, err := getCurrentSessionID(ctx)
if err != nil {
return err
}
orm := c.App.AuthenticationProvider()
if err := orm.ClearNonCurrentSessions(sessionID); err != nil {
c.App.GetLogger().Errorf("failed to clear non current user sessions: %s", err)
return errors.New("unable to update password")
}
if err := orm.SetPassword(user, newPassword); err != nil {
if errors.Is(err, clsession.ErrNotSupported) {
return errUnsupportedForAuth
}
c.App.GetLogger().Errorf("failed to update current user password: %s", err)
return errors.New("unable to update password")
}
return nil
}