Skip to content

feat(auth): Add bulk get/delete methods #400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
May 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions firebase_admin/_auth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from firebase_admin import _auth_utils
from firebase_admin import _http_client
from firebase_admin import _token_gen
from firebase_admin import _user_identifier
from firebase_admin import _user_import
from firebase_admin import _user_mgt

Expand Down Expand Up @@ -182,6 +183,56 @@ def get_user_by_phone_number(self, phone_number):
response = self._user_manager.get_user(phone_number=phone_number)
return _user_mgt.UserRecord(response)

def get_users(self, identifiers):
"""Gets the user data corresponding to the specified identifiers.

There are no ordering guarantees; in particular, the nth entry in the
result list is not guaranteed to correspond to the nth entry in the input
parameters list.

A maximum of 100 identifiers may be supplied. If more than 100
identifiers are supplied, this method raises a `ValueError`.

Args:
identifiers (list[Identifier]): A list of ``Identifier`` instances used
to indicate which user records should be returned. Must have <= 100
entries.

Returns:
GetUsersResult: A ``GetUsersResult`` instance corresponding to the
specified identifiers.

Raises:
ValueError: If any of the identifiers are invalid or if more than 100
identifiers are specified.
"""
response = self._user_manager.get_users(identifiers=identifiers)

def _matches(identifier, user_record):
if isinstance(identifier, _user_identifier.UidIdentifier):
return identifier.uid == user_record.uid
if isinstance(identifier, _user_identifier.EmailIdentifier):
return identifier.email == user_record.email
if isinstance(identifier, _user_identifier.PhoneIdentifier):
return identifier.phone_number == user_record.phone_number
if isinstance(identifier, _user_identifier.ProviderIdentifier):
return next((
True
for user_info in user_record.provider_data
if identifier.provider_id == user_info.provider_id
and identifier.provider_uid == user_info.uid
), False)
raise TypeError("Unexpected type: {}".format(type(identifier)))

def _is_user_found(identifier, user_records):
return any(_matches(identifier, user_record) for user_record in user_records)

users = [_user_mgt.UserRecord(user) for user in response]
not_found = [
identifier for identifier in identifiers if not _is_user_found(identifier, users)]

return _user_mgt.GetUsersResult(users=users, not_found=not_found)

def list_users(self, page_token=None, max_results=_user_mgt.MAX_LIST_USERS_RESULTS):
"""Retrieves a page of user accounts from a Firebase project.

Expand Down Expand Up @@ -306,6 +357,33 @@ def delete_user(self, uid):
"""
self._user_manager.delete_user(uid)

def delete_users(self, uids):
"""Deletes the users specified by the given identifiers.

Deleting a non-existing user does not generate an error (the method is
idempotent.) Non-existing users are considered to be successfully
deleted and are therefore included in the
`DeleteUserResult.success_count` value.

A maximum of 1000 identifiers may be supplied. If more than 1000
identifiers are supplied, this method raises a `ValueError`.

Args:
uids: A list of strings indicating the uids of the users to be deleted.
Must have <= 1000 entries.

Returns:
DeleteUsersResult: The total number of successful/failed deletions, as
well as the array of errors that correspond to the failed
deletions.

Raises:
ValueError: If any of the identifiers are invalid or if more than 1000
identifiers are specified.
"""
result = self._user_manager.delete_users(uids, force_delete=True)
return _user_mgt.DeleteUsersResult(result, len(uids))

def import_users(self, users, hash_alg=None):
"""Imports the specified list of users into Firebase Auth.

Expand Down
9 changes: 9 additions & 0 deletions firebase_admin/_auth_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@ def validate_provider_id(provider_id, required=True):
'string.'.format(provider_id))
return provider_id

def validate_provider_uid(provider_uid, required=True):
if provider_uid is None and not required:
return None
if not isinstance(provider_uid, str) or not provider_uid:
raise ValueError(
'Invalid provider UID: "{0}". Provider UID must be a non-empty '
'string.'.format(provider_uid))
return provider_uid

def validate_photo_url(photo_url, required=False):
"""Parses and validates the given URL string."""
if photo_url is None and not required:
Expand Down
87 changes: 87 additions & 0 deletions firebase_admin/_rfc3339.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Copyright 2020 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.

"""Parse RFC3339 date strings"""

from datetime import datetime, timezone
import re

def parse_to_epoch(datestr):
"""Parse an RFC3339 date string and return the number of seconds since the
epoch (as a float).
In particular, this method is meant to parse the strings returned by the
JSON mapping of protobuf google.protobuf.timestamp.Timestamp instances:
https://github.com/protocolbuffers/protobuf/blob/4cf5bfee9546101d98754d23ff378ff718ba8438/src/google/protobuf/timestamp.proto#L99
This method has microsecond precision; nanoseconds will be truncated.
Args:
datestr: A string in RFC3339 format.
Returns:
Float: The number of seconds since the Unix epoch.
Raises:
ValueError: Raised if the `datestr` is not a valid RFC3339 date string.
"""
return _parse_to_datetime(datestr).timestamp()


def _parse_to_datetime(datestr):
"""Parse an RFC3339 date string and return a python datetime instance.
Args:
datestr: A string in RFC3339 format.
Returns:
datetime: The corresponding `datetime` (with timezone information).
Raises:
ValueError: Raised if the `datestr` is not a valid RFC3339 date string.
"""
# If more than 6 digits appear in the fractional seconds position, truncate
# to just the most significant 6. (i.e. we only have microsecond precision;
# nanos are truncated.)
datestr_modified = re.sub(r'(\.\d{6})\d*', r'\1', datestr)

# This format is the one we actually expect to occur from our backend. The
# others are only present because the spec says we *should* accept them.
try:
return datetime.strptime(
datestr_modified, '%Y-%m-%dT%H:%M:%S.%fZ'
).replace(tzinfo=timezone.utc)
except ValueError:
pass

try:
return datetime.strptime(
datestr_modified, '%Y-%m-%dT%H:%M:%SZ'
).replace(tzinfo=timezone.utc)
except ValueError:
pass

# Note: %z parses timezone offsets, but requires the timezone offset *not*
# include a separating ':'. As of python 3.7, this was relaxed.
# TODO(rsgowman): Once python3.7 becomes our floor, we can drop the regex
# replacement.
datestr_modified = re.sub(r'(\d\d):(\d\d)$', r'\1\2', datestr_modified)

try:
return datetime.strptime(datestr_modified, '%Y-%m-%dT%H:%M:%S.%f%z')
except ValueError:
pass

try:
return datetime.strptime(datestr_modified, '%Y-%m-%dT%H:%M:%S%z')
except ValueError:
pass

raise ValueError('time data {0} does not match RFC3339 format'.format(datestr))
103 changes: 103 additions & 0 deletions firebase_admin/_user_identifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright 2020 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.

"""Classes to uniquely identify a user."""

from firebase_admin import _auth_utils

class UserIdentifier:
"""Identifies a user to be looked up."""


class UidIdentifier(UserIdentifier):
"""Used for looking up an account by uid.

See ``auth.get_user()``.
"""

def __init__(self, uid):
"""Constructs a new `UidIdentifier` object.

Args:
uid: A user ID string.
"""
self._uid = _auth_utils.validate_uid(uid, required=True)

@property
def uid(self):
return self._uid


class EmailIdentifier(UserIdentifier):
"""Used for looking up an account by email.

See ``auth.get_user()``.
"""

def __init__(self, email):
"""Constructs a new `EmailIdentifier` object.

Args:
email: A user email address string.
"""
self._email = _auth_utils.validate_email(email, required=True)

@property
def email(self):
return self._email


class PhoneIdentifier(UserIdentifier):
"""Used for looking up an account by phone number.

See ``auth.get_user()``.
"""

def __init__(self, phone_number):
"""Constructs a new `PhoneIdentifier` object.

Args:
phone_number: A phone number string.
"""
self._phone_number = _auth_utils.validate_phone(phone_number, required=True)

@property
def phone_number(self):
return self._phone_number


class ProviderIdentifier(UserIdentifier):
"""Used for looking up an account by provider.

See ``auth.get_user()``.
"""

def __init__(self, provider_id, provider_uid):
"""Constructs a new `ProviderIdentifier` object.

  Args:
    provider_id: A provider ID string.
    provider_uid: A provider UID string.
"""
self._provider_id = _auth_utils.validate_provider_id(provider_id, required=True)
self._provider_uid = _auth_utils.validate_provider_uid(
provider_uid, required=True)

@property
def provider_id(self):
return self._provider_id

@property
def provider_uid(self):
return self._provider_uid
7 changes: 6 additions & 1 deletion firebase_admin/_user_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,12 @@ def standard_scrypt(cls, memory_cost, parallelization, block_size, derived_key_l


class ErrorInfo:
"""Represents an error encountered while importing an ``ImportUserRecord``."""
"""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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_auth_utils could be a good place. But feel free to defer that to future PR.

# 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']
Expand Down
Loading