-
Notifications
You must be signed in to change notification settings - Fork 329
/
Copy path_user_import.py
520 lines (414 loc) · 17 KB
/
_user_import.py
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
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Firebase user import sub module."""
import base64
import json
from firebase_admin import _auth_utils
def b64_encode(bytes_value):
return base64.urlsafe_b64encode(bytes_value).decode()
class UserProvider:
"""Represents a user identity provider that can be associated with a Firebase user.
One or more providers can be specified in an ``ImportUserRecord`` when importing users via
``auth.import_users()``.
Args:
uid: User's unique ID assigned by the identity provider.
provider_id: ID of the identity provider. This can be a short domain name or the identifier
of an OpenID identity provider.
email: User's email address (optional).
display_name: User's display name (optional).
photo_url: User's photo URL (optional).
"""
def __init__(self, uid, provider_id, email=None, display_name=None, photo_url=None):
self.uid = uid
self.provider_id = provider_id
self.email = email
self.display_name = display_name
self.photo_url = photo_url
@property
def uid(self):
return self._uid
@uid.setter
def uid(self, uid):
self._uid = _auth_utils.validate_uid(uid, required=True)
@property
def provider_id(self):
return self._provider_id
@provider_id.setter
def provider_id(self, provider_id):
self._provider_id = _auth_utils.validate_provider_id(provider_id, required=True)
@property
def email(self):
return self._email
@email.setter
def email(self, email):
self._email = _auth_utils.validate_email(email)
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, display_name):
self._display_name = _auth_utils.validate_display_name(display_name)
@property
def photo_url(self):
return self._photo_url
@photo_url.setter
def photo_url(self, photo_url):
self._photo_url = _auth_utils.validate_photo_url(photo_url)
def to_dict(self):
payload = {
'rawId': self.uid,
'providerId': self.provider_id,
'displayName': self.display_name,
'email': self.email,
'photoUrl': self.photo_url,
}
return {k: v for k, v in payload.items() if v is not None}
class ImportUserRecord:
"""Represents a user account to be imported to Firebase Auth.
Must specify the ``uid`` field at a minimum. A sequence of ``ImportUserRecord`` objects can be
passed to the ``auth.import_users()`` function, in order to import those users into Firebase
Auth in bulk. If the ``password_hash`` is set on a user, a hash configuration must be
specified when calling ``import_users()``.
Args:
uid: User's unique ID. Must be a non-empty string not longer than 128 characters.
email: User's email address (optional).
email_verified: A boolean indicating whether the user's email has been verified (optional).
display_name: User's display name (optional).
phone_number: User's phone number (optional).
photo_url: User's photo URL (optional).
disabled: A boolean indicating whether this user account has been disabled (optional).
user_metadata: An ``auth.UserMetadata`` instance with additional user metadata (optional).
provider_data: A list of ``auth.UserProvider`` instances (optional).
custom_claims: A ``dict`` of custom claims to be set on the user account (optional).
password_hash: User's password hash as a ``bytes`` sequence (optional).
password_salt: User's password salt as a ``bytes`` sequence (optional).
Raises:
ValueError: If provided arguments are invalid.
"""
def __init__(self, uid, email=None, email_verified=None, display_name=None, phone_number=None,
photo_url=None, disabled=None, user_metadata=None, provider_data=None,
custom_claims=None, password_hash=None, password_salt=None):
self.uid = uid
self.email = email
self.display_name = display_name
self.phone_number = phone_number
self.photo_url = photo_url
self.password_hash = password_hash
self.password_salt = password_salt
self.email_verified = email_verified
self.disabled = disabled
self.user_metadata = user_metadata
self.provider_data = provider_data
self.custom_claims = custom_claims
@property
def uid(self):
return self._uid
@uid.setter
def uid(self, uid):
self._uid = _auth_utils.validate_uid(uid, required=True)
@property
def email(self):
return self._email
@email.setter
def email(self, email):
self._email = _auth_utils.validate_email(email)
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, display_name):
self._display_name = _auth_utils.validate_display_name(display_name)
@property
def phone_number(self):
return self._phone_number
@phone_number.setter
def phone_number(self, phone_number):
self._phone_number = _auth_utils.validate_phone(phone_number)
@property
def photo_url(self):
return self._photo_url
@photo_url.setter
def photo_url(self, photo_url):
self._photo_url = _auth_utils.validate_photo_url(photo_url)
@property
def password_hash(self):
return self._password_hash
@password_hash.setter
def password_hash(self, password_hash):
self._password_hash = _auth_utils.validate_bytes(password_hash, 'password_hash')
@property
def password_salt(self):
return self._password_salt
@password_salt.setter
def password_salt(self, password_salt):
self._password_salt = _auth_utils.validate_bytes(password_salt, 'password_salt')
@property
def user_metadata(self):
return self._user_metadata
@user_metadata.setter
def user_metadata(self, user_metadata):
created_at = user_metadata.creation_timestamp if user_metadata is not None else None
last_login_at = user_metadata.last_sign_in_timestamp if user_metadata is not None else None
self._created_at = _auth_utils.validate_timestamp(created_at, 'creation_timestamp')
self._last_login_at = _auth_utils.validate_timestamp(
last_login_at, 'last_sign_in_timestamp')
self._user_metadata = user_metadata
@property
def provider_data(self):
return self._provider_data
@provider_data.setter
def provider_data(self, provider_data):
if provider_data is not None:
try:
if any([not isinstance(p, UserProvider) for p in provider_data]):
raise ValueError('One or more provider data instances are invalid.')
except TypeError:
raise ValueError('provider_data must be iterable.')
self._provider_data = provider_data
@property
def custom_claims(self):
return self._custom_claims
@custom_claims.setter
def custom_claims(self, custom_claims):
json_claims = json.dumps(custom_claims) if isinstance(
custom_claims, dict) else custom_claims
self._custom_claims_str = _auth_utils.validate_custom_claims(json_claims)
self._custom_claims = custom_claims
def to_dict(self):
"""Returns a dict representation of the user. For internal use only."""
payload = {
'localId': self.uid,
'email': self.email,
'displayName': self.display_name,
'phoneNumber': self.phone_number,
'photoUrl': self.photo_url,
'emailVerified': (bool(self.email_verified)
if self.email_verified is not None else None),
'disabled': bool(self.disabled) if self.disabled is not None else None,
'customAttributes': self._custom_claims_str,
'createdAt': self._created_at,
'lastLoginAt': self._last_login_at,
'passwordHash': b64_encode(self.password_hash) if self.password_hash else None,
'salt': b64_encode(self.password_salt) if self.password_salt else None,
}
if self.provider_data:
payload['providerUserInfo'] = [p.to_dict() for p in self.provider_data]
return {k: v for k, v in payload.items() if v is not None}
class UserImportHash:
"""Represents a hash algorithm used to hash user passwords.
An instance of this class must be specified when importing users with passwords via the
``auth.import_users()`` API. Use one of the provided class methods to obtain new
instances when required. Refer to `documentation`_ for more details.
.. _documentation: https://firebase.google.com/docs/auth/admin/import-users
"""
def __init__(self, name, data=None):
self._name = name
self._data = data
def to_dict(self):
payload = {'hashAlgorithm': self._name}
if self._data:
payload.update(self._data)
return payload
@classmethod
def _hmac(cls, name, key):
data = {
'signerKey': b64_encode(_auth_utils.validate_bytes(key, 'key', required=True))
}
return UserImportHash(name, data)
@classmethod
def hmac_sha512(cls, key):
"""Creates a new HMAC SHA512 algorithm instance.
Args:
key: Signer key as a byte sequence.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return cls._hmac('HMAC_SHA512', key)
@classmethod
def hmac_sha256(cls, key):
"""Creates a new HMAC SHA256 algorithm instance.
Args:
key: Signer key as a byte sequence.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return cls._hmac('HMAC_SHA256', key)
@classmethod
def hmac_sha1(cls, key):
"""Creates a new HMAC SHA1 algorithm instance.
Args:
key: Signer key as a byte sequence.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return cls._hmac('HMAC_SHA1', key)
@classmethod
def hmac_md5(cls, key):
"""Creates a new HMAC MD5 algorithm instance.
Args:
key: Signer key as a byte sequence.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return cls._hmac('HMAC_MD5', key)
@classmethod
def md5(cls, rounds):
"""Creates a new MD5 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 0 and 8192.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'MD5',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 0, 8192)})
@classmethod
def sha1(cls, rounds):
"""Creates a new SHA1 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 1 and 8192.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'SHA1',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 1, 8192)})
@classmethod
def sha256(cls, rounds):
"""Creates a new SHA256 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 1 and 8192.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'SHA256',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 1, 8192)})
@classmethod
def sha512(cls, rounds):
"""Creates a new SHA512 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 1 and 8192.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'SHA512',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 1, 8192)})
@classmethod
def pbkdf_sha1(cls, rounds):
"""Creates a new PBKDF SHA1 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 0 and 120000.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'PBKDF_SHA1',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 0, 120000)})
@classmethod
def pbkdf2_sha256(cls, rounds):
"""Creates a new PBKDF2 SHA256 algorithm instance.
Args:
rounds: Number of rounds. Must be an integer between 0 and 120000.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash(
'PBKDF2_SHA256',
{'rounds': _auth_utils.validate_int(rounds, 'rounds', 0, 120000)})
@classmethod
def scrypt(cls, key, rounds, memory_cost, salt_separator=None):
"""Creates a new Scrypt algorithm instance.
This is the modified Scrypt algorithm used by Firebase Auth. See ``standard_scrypt()``
function for the standard Scrypt algorith,
Args:
key: Signer key as a byte sequence.
rounds: Number of rounds. Must be an integer between 1 and 8.
memory_cost: Memory cost as an integer between 1 and 14.
salt_separator: Salt separator as a byte sequence (optional).
Returns:
UserImportHash: A new ``UserImportHash``.
"""
data = {
'signerKey': b64_encode(_auth_utils.validate_bytes(key, 'key', required=True)),
'rounds': _auth_utils.validate_int(rounds, 'rounds', 1, 8),
'memoryCost': _auth_utils.validate_int(memory_cost, 'memory_cost', 1, 14),
}
if salt_separator:
data['saltSeparator'] = b64_encode(_auth_utils.validate_bytes(
salt_separator, 'salt_separator'))
return UserImportHash('SCRYPT', data)
@classmethod
def bcrypt(cls):
"""Creates a new Bcrypt algorithm instance.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
return UserImportHash('BCRYPT')
@classmethod
def standard_scrypt(cls, memory_cost, parallelization, block_size, derived_key_length):
"""Creates a new standard Scrypt algorithm instance.
Args:
memory_cost: CPU Memory cost as a non-negative integer.
parallelization: Parallelization as a non-negative integer.
block_size: Block size as a non-negative integer.
derived_key_length: Derived key length as a non-negative integer.
Returns:
UserImportHash: A new ``UserImportHash``.
"""
data = {
'cpuMemCost': _auth_utils.validate_int(memory_cost, 'memory_cost', low=0),
'parallelization': _auth_utils.validate_int(parallelization, 'parallelization', low=0),
'blockSize': _auth_utils.validate_int(block_size, 'block_size', low=0),
'dkLen': _auth_utils.validate_int(derived_key_length, 'derived_key_length', low=0),
}
return UserImportHash('STANDARD_SCRYPT', data)
class ErrorInfo:
"""Represents an error encountered while performing a batch operation such
as importing users or deleting multiple user accounts.
"""
# TODO(rsgowman): This class used to be specific to importing users (hence
# it's home in _user_import.py). It's now also used by bulk deletion of
# users. Move this to a more common location.
def __init__(self, error):
self._index = error['index']
self._reason = error['message']
@property
def index(self):
return self._index
@property
def reason(self):
return self._reason
class UserImportResult:
"""Represents the result of a bulk user import operation.
See ``auth.import_users()`` API for more details.
"""
def __init__(self, result, total):
errors = result.get('error', [])
self._success_count = total - len(errors)
self._failure_count = len(errors)
self._errors = [ErrorInfo(err) for err in errors]
@property
def success_count(self):
"""Returns the number of users successfully imported."""
return self._success_count
@property
def failure_count(self):
"""Returns the number of users that failed to be imported."""
return self._failure_count
@property
def errors(self):
"""Returns a list of ``auth.ErrorInfo`` instances describing the errors encountered."""
return self._errors