This repository has been archived by the owner on Feb 16, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
user.go
541 lines (461 loc) · 18 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package management
import (
"encoding/json"
"net/http"
"reflect"
"strconv"
"time"
)
// User represents an Auth0 user resource
//
// See: https://auth0.com/docs/users
type User struct {
// The users identifier.
ID *string `json:"user_id,omitempty"`
// The connection the user belongs to.
Connection *string `json:"connection,omitempty"`
// The user's email
Email *string `json:"email,omitempty"`
// The users name
Name *string `json:"name,omitempty"`
// The users given name
GivenName *string `json:"given_name,omitempty"`
// The users family name
FamilyName *string `json:"family_name,omitempty"`
// The user's username. Only valid if the connection requires a username
Username *string `json:"username,omitempty"`
// The user's nickname
Nickname *string `json:"nickname,omitempty"`
// The screen name, handle, or alias that this user identifies themselves with
ScreenName *string `json:"screen_name,omitempty"`
// The user-defined UTF-8 string describing their account
Description *string `json:"description,omitempty"`
// The user-defined location for this account’s profile
Location *string `json:"location,omitempty"`
// The user's password (mandatory for non SMS connections)
Password *string `json:"password,omitempty"`
// The user's phone number (following the E.164 recommendation), only valid
// for users to be added to SMS connections.
PhoneNumber *string `json:"phone_number,omitempty"`
// The time the user is created.
CreatedAt *time.Time `json:"created_at,omitempty"`
// The last time the user is updated.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
// The last time the user has logged in.
LastLogin *time.Time `json:"last_login,omitempty"`
// UserMetadata holds data that the user has read/write access to (e.g.
// color_preference, blog_url, etc).
UserMetadata map[string]interface{} `json:"user_metadata,omitempty"`
// Identities is a list of user identities for when accounts are linked.
Identities []*UserIdentity `json:"identities,omitempty"`
// True if the user's email is verified, false otherwise. If it is true then
// the user will not receive a verification email, unless verify_email: true
// was specified.
EmailVerified *bool `json:"-"`
// If true, the user will receive a verification email after creation, even
// if created with email_verified set to true. If false, the user will not
// receive a verification email, even if created with email_verified set to
// false. If unspecified, defaults to the behavior determined by the value
// of email_verified.
VerifyEmail *bool `json:"verify_email,omitempty"`
// True if the user's phone number is verified, false otherwise. When the
// user is added to a SMS connection, they will not receive an verification
// SMS if this is true.
PhoneVerified *bool `json:"phone_verified,omitempty"`
// AppMetadata holds data that the user has read-only access to (e.g. roles,
// permissions, vip, etc).
AppMetadata map[string]interface{} `json:"app_metadata,omitempty"`
// The user's picture url
Picture *string `json:"picture,omitempty"`
// A URL provided by the user in association with their profile
URL *string `json:"url,omitempty"`
// True if the user is blocked from the application, false if the user is enabled
Blocked *bool `json:"blocked,omitempty"`
// Last IP address from which this user logged in. Read only, cannot be modified.
LastIP *string `json:"last_ip,omitempty"`
// Total number of logins this user has performed. Read only, cannot be modified.
LoginsCount *int64 `json:"logins_count,omitempty"`
}
// UnmarshalJSON is a custom deserializer for the User type.
//
// We have to use a custom one due to possible inconsistencies in value types.
func (u *User) UnmarshalJSON(b []byte) error {
type user User
type userAlias struct {
*user
RawEmailVerified interface{} `json:"email_verified,omitempty"`
}
alias := &userAlias{(*user)(u), nil}
err := json.Unmarshal(b, alias)
if err != nil {
return err
}
if alias.RawEmailVerified != nil {
var emailVerified bool
switch rawEmailVerified := alias.RawEmailVerified.(type) {
case bool:
emailVerified = rawEmailVerified
case string:
emailVerified, err = strconv.ParseBool(rawEmailVerified)
if err != nil {
return err
}
default:
panic(reflect.TypeOf(rawEmailVerified))
}
alias.EmailVerified = &emailVerified
}
return nil
}
func (u *User) MarshalJSON() ([]byte, error) {
type user User
type userAlias struct {
*user
RawEmailVerified interface{} `json:"email_verified,omitempty"`
}
alias := &userAlias{user: (*user)(u)}
if u.EmailVerified != nil {
alias.RawEmailVerified = u.EmailVerified
}
return json.Marshal(alias)
}
// UserIdentityLink contains the data needed for linking an identity to a given user.
type UserIdentityLink struct {
// Connection id of the secondary user account being linked when more than one auth0 database provider exists.
ConnectionID *string `json:"connection_id,omitempty"`
// Secondary account user id.
UserID *string `json:"user_id,omitempty"`
// Identity provider of the secondary user account being linked.
Provider *string `json:"provider,omitempty"`
// LinkWith requires the authenticated primary account's JWT in the Authorization header.
// Must be a JWT for the secondary account being linked. If sending this parameter,
// provider, user_id, and connection_id must not be sent.
LinkWith *string `json:"link_with,omitempty"`
}
type UserIdentity struct {
Connection *string `json:"connection,omitempty"`
UserID *string `json:"-"`
Provider *string `json:"provider,omitempty"`
IsSocial *bool `json:"isSocial,omitempty"`
AccessToken *string `json:"access_token,omitempty"`
AccessTokenSecret *string `json:"access_token_secret,omitempty"`
RefreshToken *string `json:"refresh_token,omitempty"`
}
// UnmarshalJSON is a custom deserializer for the UserIdentity type.
//
// We have to use a custom one due to a bug in the Auth0 Management API which
// might return a number for `user_id` instead of a string.
//
// See https://community.auth0.com/t/users-user-id-returns-inconsistent-type-for-identities-user-id/39236
func (i *UserIdentity) UnmarshalJSON(b []byte) error {
type userIdentity UserIdentity
type userIdentityAlias struct {
*userIdentity
RawUserID interface{} `json:"user_id,omitempty"`
}
alias := &userIdentityAlias{(*userIdentity)(i), nil}
err := json.Unmarshal(b, alias)
if err != nil {
return err
}
if alias.RawUserID != nil {
var id string
switch rawID := alias.RawUserID.(type) {
case string:
id = rawID
case float64:
id = strconv.Itoa(int(rawID))
default:
panic(reflect.TypeOf(rawID))
}
alias.UserID = &id
}
return nil
}
func (i *UserIdentity) MarshalJSON() ([]byte, error) {
type userIdentity UserIdentity
type userIdentityAlias struct {
*userIdentity
RawUserID interface{} `json:"user_id,omitempty"`
}
alias := &userIdentityAlias{userIdentity: (*userIdentity)(i)}
if i.UserID != nil {
alias.RawUserID = i.UserID
}
return json.Marshal(alias)
}
type userBlock struct {
BlockedFor []*UserBlock `json:"blocked_for,omitempty"`
}
type UserBlock struct {
Identifier *string `json:"identifier,omitempty"`
IP *string `json:"ip,omitempty"`
}
type UserRecoveryCode struct {
RecoveryCode *string `json:"recovery_code,omitempty"`
}
// UserEnrollment contains information about the Guardian enrollments for the user
type UserEnrollment struct {
// Authentication method for this enrollment. Can be `authentication`, `guardian`, or `sms`.
AuthMethod *string `json:"auth_method,omitempty"`
// Start date and time of this enrollment.
EnrolledAt *time.Time `json:"enrolled_at,omitempty"`
// ID of this enrollment.
ID *string `json:"id,omitempty"`
// Device identifier (usually phone identifier) of this enrollment.
Identifier *string `json:"identifier,omitempty"`
// Last authentication date and time of this enrollment.
LastAuth *time.Time `json:"last_auth,omitempty"`
// Name of enrollment (usually phone number).
Name *string `json:"name,omitempty"`
// Phone number for this enrollment.
PhoneNumber *string `json:"phone_number,omitempty"`
// Status of this enrollment. Can be `pending` or `confirmed`.
Status *string `json:"status,omitempty"`
// Type of enrollment.
Type *string `json:"type,omitempty"`
}
// UserList is an envelope struct which is used when calling List() or Search()
// methods.
//
// It holds metadata such as the total result count, starting offset and limit.
type UserList struct {
List
Users []*User `json:"users"`
}
// UserManager manages Auth0 User resources.
type UserManager struct {
*Management
}
// newUserManager returns a new instance of a user manager.
func newUserManager(m *Management) *UserManager {
return &UserManager{m}
}
// Create a new user. It works only for database and passwordless connections.
//
// The samples on the right show you every attribute that could be used. The
// attribute connection is always mandatory but depending on the type of
// connection you are using there could be others too. For instance, database
// connections require `email` and `password`.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_users
func (m *UserManager) Create(u *User, opts ...RequestOption) error {
return m.Request("POST", m.URI("users"), u, opts...)
}
// Read user details for a given user_id.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id
func (m *UserManager) Read(id string, opts ...RequestOption) (u *User, err error) {
err = m.Request("GET", m.URI("users", id), &u, opts...)
return
}
// Update user.
//
// The following attributes can be updated at the root level:
//
// - `app_metadata`
// - `blocked`
// - `email`
// - `email_verified`
// - `family_name`
// - `given_name`
// - `name`
// - `nickname`
// - `password`
// - `phone_number`
// - `phone_verified`
// - `picture`
// - `username`
// - `user_metadata`
// - `verify_email`
//
// See: https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
func (m *UserManager) Update(id string, u *User, opts ...RequestOption) (err error) {
return m.Request("PATCH", m.URI("users", id), u, opts...)
}
// Delete a single user based on its id.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/delete_users_by_id
func (m *UserManager) Delete(id string, opts ...RequestOption) (err error) {
return m.Request("DELETE", m.URI("users", id), nil, opts...)
}
// List all users. This method forces the `include_totals` option.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_users
func (m *UserManager) List(opts ...RequestOption) (ul *UserList, err error) {
err = m.Request("GET", m.URI("users"), &ul, applyListDefaults(opts))
return
}
// Search is an alias for List.
func (m *UserManager) Search(opts ...RequestOption) (ul *UserList, err error) {
return m.List(opts...)
}
// ListByEmail retrieves all users matching a given email.
//
// If Auth0 is the identify provider (idP), the email address associated with a
// user is saved in lower case, regardless of how you initially provided it.
// For example, if you register a user as JohnSmith@example.com, Auth0 saves the
// user's email as johnsmith@example.com.
//
// In cases where Auth0 is not the idP, the `email` is stored based on the rules
// of idP, so make sure the search is made using the correct capitalization.
//
// When using this endpoint, make sure that you are searching for users via
// email addresses using the correct case.
//
// See: https://auth0.com/docs/api/management/v2#!/Users_By_Email/get_users_by_email
func (m *UserManager) ListByEmail(email string, opts ...RequestOption) (us []*User, err error) {
opts = append(opts, Parameter("email", email))
err = m.Request("GET", m.URI("users-by-email"), &us, opts...)
return
}
// Roles lists all roles associated with a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_user_roles
func (m *UserManager) Roles(id string, opts ...RequestOption) (r *RoleList, err error) {
err = m.Request("GET", m.URI("users", id, "roles"), &r, applyListDefaults(opts))
return
}
// AssignRoles assignes roles to a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_user_roles
func (m *UserManager) AssignRoles(id string, roles []*Role, opts ...RequestOption) error {
r := make(map[string][]*string)
r["roles"] = make([]*string, len(roles))
for i, role := range roles {
r["roles"][i] = role.ID
}
return m.Request("POST", m.URI("users", id, "roles"), &r, opts...)
}
// RemoveRoles removes any roles associated to a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/delete_user_roles
func (m *UserManager) RemoveRoles(id string, roles []*Role, opts ...RequestOption) error {
r := make(map[string][]*string)
r["roles"] = make([]*string, len(roles))
for i, role := range roles {
r["roles"][i] = role.ID
}
return m.Request("DELETE", m.URI("users", id, "roles"), &r, opts...)
}
// Permissions lists the permissions associated to the user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_permissions
func (m *UserManager) Permissions(id string, opts ...RequestOption) (p *PermissionList, err error) {
err = m.Request("GET", m.URI("users", id, "permissions"), &p, applyListDefaults(opts))
return
}
// AssignPermissions assigns permissions to the user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_permissions
func (m *UserManager) AssignPermissions(id string, permissions []*Permission, opts ...RequestOption) error {
p := make(map[string][]*Permission)
p["permissions"] = permissions
return m.Request("POST", m.URI("users", id, "permissions"), &p, opts...)
}
// RemovePermissions removes any permissions associated to a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/delete_permissions
func (m *UserManager) RemovePermissions(id string, permissions []*Permission, opts ...RequestOption) error {
p := make(map[string][]*Permission)
p["permissions"] = permissions
return m.Request("DELETE", m.URI("users", id, "permissions"), &p, opts...)
}
// Blocks retrieves a list of blocked IP addresses of a particular user using the
// user ID.
//
// See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks_by_id
func (m *UserManager) Blocks(id string, opts ...RequestOption) ([]*UserBlock, error) {
b := new(userBlock)
err := m.Request("GET", m.URI("user-blocks", id), &b, opts...)
return b.BlockedFor, err
}
// Blocks retrieves a list of blocked IP addresses of a particular user using
// any of the user identifiers: username, phone number or email.
//
// See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks
func (m *UserManager) BlocksByIdentifier(identifier string, opts ...RequestOption) ([]*UserBlock, error) {
b := new(userBlock)
opts = append(opts, Parameter("identifier", identifier))
err := m.Request("GET", m.URI("user-blocks"), &b, opts...)
return b.BlockedFor, err
}
// Unblock a user that was blocked due to an excessive amount of incorrectly
// provided credentials using the user ID.
//
// Note: This endpoint does not unblock users that were blocked by admins.
//
// See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks_by_id
func (m *UserManager) Unblock(id string, opts ...RequestOption) error {
return m.Request("DELETE", m.URI("user-blocks", id), nil, opts...)
}
// Unblock a user that was blocked due to an excessive amount of incorrectly
// provided credentials using any of the user identifiers: username, phone number or email.
//
// Note: This endpoint does not unblock users that were blocked by admins.
//
// See: https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks
func (m *UserManager) UnblockByIdentifier(identifier string, opts ...RequestOption) error {
opts = append(opts, Parameter("identifier", identifier))
return m.Request("DELETE", m.URI("user-blocks"), nil, opts...)
}
// Enrollments retrieves all Guardian enrollments for a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_enrollments
func (m *UserManager) Enrollments(id string, opts ...RequestOption) (enrolls []*UserEnrollment, err error) {
err = m.Request("GET", m.URI("users", id, "enrollments"), &enrolls, opts...)
return
}
// RegenerateRecoveryCode removes the current multi-factor authentication recovery code and generate a new one.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_recovery_code_regeneration
func (m *UserManager) RegenerateRecoveryCode(id string, opts ...RequestOption) (*UserRecoveryCode, error) {
r := new(UserRecoveryCode)
err := m.Request("POST", m.URI("users", id, "recovery-code-regeneration"), &r, opts...)
return r, err
}
// InvalidateRememberBrowser invalidates all remembered browsers across all authentication factors for a user.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_invalidate_remember_browser
func (m *UserManager) InvalidateRememberBrowser(id string, opts ...RequestOption) error {
uri := m.URI(
"users",
id,
"multifactor",
"actions",
"invalidate-remember-browser",
)
err := m.Request("POST", uri, nil, opts...)
return err
}
// Link links two user accounts together forming a primary and secondary relationship.
//
// See: https://auth0.com/docs/api/management/v2#!/Users/post_identities
func (m *UserManager) Link(id string, il *UserIdentityLink, opts ...RequestOption) (uIDs []UserIdentity, err error) {
req, err := m.NewRequest("POST", m.URI("users", id, "identities"), il, opts...)
if err != nil {
return uIDs, err
}
res, err := m.Do(req)
if err != nil {
return uIDs, err
}
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
return uIDs, newError(res.Body)
}
if res.StatusCode != http.StatusNoContent && res.StatusCode != http.StatusAccepted {
err := json.NewDecoder(res.Body).Decode(&uIDs)
if err != nil {
return uIDs, err
}
return uIDs, res.Body.Close()
}
return uIDs, nil
}
// List user's organizations
//
// See: https://auth0.com/docs/api/management/v2#!/Users/get_organizations
func (m *UserManager) Organizations(id string, opts ...RequestOption) (p *OrganizationList, err error) {
err = m.Request("GET", m.URI("users", id, "organizations"), &p, applyListDefaults(opts))
return
}