Ejemplo n.º 1
0
 def delete_user(self, uid):
     """Deletes the user identified by the specified user ID."""
     _auth_utils.validate_uid(uid, required=True)
     body, http_resp = self._make_request('post', '/accounts:delete', json={'localId' : uid})
     if not body or not body.get('kind'):
         raise _auth_utils.UnexpectedResponseError(
             'Failed to delete user: {0}.'.format(uid), http_response=http_resp)
Ejemplo n.º 2
0
    def delete_users(self, uids, force_delete=False):
        """Deletes the users identified by the specified user ids.

        Args:
            uids: A list of strings indicating the uids of the users to be deleted.
                Must have <= 1000 entries.
            force_delete: Optional parameter that indicates if users should be
                deleted, even if they're not disabled. Defaults to False.


        Returns:
            BatchDeleteAccountsResponse: Server's proto response, wrapped in a
            python object.

        Raises:
            ValueError: If any of the identifiers are invalid or if more than 1000
                identifiers are specified.
            UnexpectedResponseError: If the backend server responds with an
                unexpected message.
        """
        if not uids:
            return BatchDeleteAccountsResponse()

        if len(uids) > 1000:
            raise ValueError("`uids` paramter must have <= 1000 entries.")
        for uid in uids:
            _auth_utils.validate_uid(uid, required=True)

        body, http_resp = self._make_request('post', '/accounts:batchDelete',
                                             json={'localIds': uids, 'force': force_delete})
        if not isinstance(body, dict):
            raise _auth_utils.UnexpectedResponseError(
                'Unexpected response from server while attempting to delete users.',
                http_response=http_resp)
        return BatchDeleteAccountsResponse(body.get('errors', []))
Ejemplo n.º 3
0
 def delete_user(self, uid):
     """Deletes the user identified by the specified user ID."""
     _auth_utils.validate_uid(uid, required=True)
     try:
         response = self._client.request('post', 'deleteAccount', json={'localId' : uid})
     except requests.exceptions.RequestException as error:
         self._handle_http_error(
             USER_DELETE_ERROR, 'Failed to delete user: {0}.'.format(uid), error)
     else:
         if not response or not response.get('kind'):
             raise ApiCallError(USER_DELETE_ERROR, 'Failed to delete user: {0}.'.format(uid))
Ejemplo n.º 4
0
 def delete_user(self, uid):
     """Deletes the user identified by the specified user ID."""
     _auth_utils.validate_uid(uid, required=True)
     try:
         body, http_resp = self._client.body_and_response(
             'post', '/accounts:delete', json={'localId' : uid})
     except requests.exceptions.RequestException as error:
         raise _auth_utils.handle_auth_backend_error(error)
     else:
         if not body or not body.get('kind'):
             raise _auth_utils.UnexpectedResponseError(
                 'Failed to delete user: {0}.'.format(uid), http_response=http_resp)
Ejemplo n.º 5
0
    def get_user(self, **kwargs):
        """Gets the user data corresponding to the provided key."""
        if 'uid' in kwargs:
            key, key_type = kwargs.pop('uid'), 'user ID'
            payload = {
                'localId': [_auth_utils.validate_uid(key, required=True)]
            }
        elif 'email' in kwargs:
            key, key_type = kwargs.pop('email'), 'email'
            payload = {
                'email': [_auth_utils.validate_email(key, required=True)]
            }
        elif 'phone_number' in kwargs:
            key, key_type = kwargs.pop('phone_number'), 'phone number'
            payload = {
                'phoneNumber':
                [_auth_utils.validate_phone(key, required=True)]
            }
        else:
            raise TypeError(
                'Unsupported keyword arguments: {0}.'.format(kwargs))

        try:
            body, http_resp = self._client.body_and_response(
                'post', '/accounts:lookup', json=payload)
        except requests.exceptions.RequestException as error:
            raise _auth_utils.handle_auth_backend_error(error)
        else:
            if not body or not body.get('users'):
                raise _auth_utils.UserNotFoundError(
                    'No user record found for the provided {0}: {1}.'.format(
                        key_type, key),
                    http_response=http_resp)
            return body['users'][0]
Ejemplo n.º 6
0
    def get_user(self, **kwargs):
        """Gets the user data corresponding to the provided key."""
        if 'uid' in kwargs:
            key, key_type = kwargs.pop('uid'), 'user ID'
            payload = {'localId' : [_auth_utils.validate_uid(key, required=True)]}
        elif 'email' in kwargs:
            key, key_type = kwargs.pop('email'), 'email'
            payload = {'email' : [_auth_utils.validate_email(key, required=True)]}
        elif 'phone_number' in kwargs:
            key, key_type = kwargs.pop('phone_number'), 'phone number'
            payload = {'phoneNumber' : [_auth_utils.validate_phone(key, required=True)]}
        else:
            raise TypeError('Unsupported keyword arguments: {0}.'.format(kwargs))

        try:
            response = self._client.request('post', 'getAccountInfo', json=payload)
        except requests.exceptions.RequestException as error:
            msg = 'Failed to get user by {0}: {1}.'.format(key_type, key)
            self._handle_http_error(INTERNAL_ERROR, msg, error)
        else:
            if not response or not response.get('users'):
                raise ApiCallError(
                    USER_NOT_FOUND_ERROR,
                    'No user record found for the provided {0}: {1}.'.format(key_type, key))
            return response['users'][0]
    def __init__(self, uid):
        """Constructs a new `UidIdentifier` object.

        Args:
            uid: A user ID string.
        """
        self._uid = _auth_utils.validate_uid(uid, required=True)
Ejemplo n.º 8
0
 def create_user(self,
                 uid=None,
                 display_name=None,
                 email=None,
                 phone_number=None,
                 photo_url=None,
                 password=None,
                 disabled=None,
                 email_verified=None):
     """Creates a new user account with the specified properties."""
     payload = {
         'localId':
         _auth_utils.validate_uid(uid),
         'displayName':
         _auth_utils.validate_display_name(display_name),
         'email':
         _auth_utils.validate_email(email),
         'phoneNumber':
         _auth_utils.validate_phone(phone_number),
         'photoUrl':
         _auth_utils.validate_photo_url(photo_url),
         'password':
         _auth_utils.validate_password(password),
         'emailVerified':
         bool(email_verified) if email_verified is not None else None,
         'disabled':
         bool(disabled) if disabled is not None else None,
     }
     payload = {k: v for k, v in payload.items() if v is not None}
     body, http_resp = self._make_request('post', '/accounts', json=payload)
     if not body or not body.get('localId'):
         raise _auth_utils.UnexpectedResponseError(
             'Failed to create new user.', http_response=http_resp)
     return body.get('localId')
Ejemplo n.º 9
0
    def update_user(self, uid, display_name=None, email=None, phone_number=None,
                    photo_url=None, password=None, disabled=None, email_verified=None,
                    valid_since=None, custom_claims=None):
        """Updates an existing user account with the specified properties"""
        payload = {
            'localId': _auth_utils.validate_uid(uid, required=True),
            'email': _auth_utils.validate_email(email),
            'password': _auth_utils.validate_password(password),
            'validSince': _auth_utils.validate_timestamp(valid_since, 'valid_since'),
            'emailVerified': bool(email_verified) if email_verified is not None else None,
            'disableUser': bool(disabled) if disabled is not None else None,
        }

        remove = []
        if display_name is not None:
            if display_name is DELETE_ATTRIBUTE:
                remove.append('DISPLAY_NAME')
            else:
                payload['displayName'] = _auth_utils.validate_display_name(display_name)
        if photo_url is not None:
            if photo_url is DELETE_ATTRIBUTE:
                remove.append('PHOTO_URL')
            else:
                payload['photoUrl'] = _auth_utils.validate_photo_url(photo_url)
        if remove:
            payload['deleteAttribute'] = remove

        if phone_number is not None:
            if phone_number is DELETE_ATTRIBUTE:
                payload['deleteProvider'] = ['phone']
            else:
                payload['phoneNumber'] = _auth_utils.validate_phone(phone_number)

        if custom_claims is not None:
            if custom_claims is DELETE_ATTRIBUTE:
                custom_claims = {}
            json_claims = json.dumps(custom_claims) if isinstance(
                custom_claims, dict) else custom_claims
            payload['customAttributes'] = _auth_utils.validate_custom_claims(json_claims)

        payload = {k: v for k, v in payload.items() if v is not None}
        try:
            body, http_resp = self._client.body_and_response(
                'post', '/accounts:update', json=payload)
        except requests.exceptions.RequestException as error:
            raise _auth_utils.handle_auth_backend_error(error)
        else:
            if not body or not body.get('localId'):
                raise _auth_utils.UnexpectedResponseError(
                    'Failed to update user: {0}.'.format(uid), http_response=http_resp)
            return body.get('localId')
Ejemplo n.º 10
0
    def update_user(self, uid, display_name=_UNSPECIFIED, email=None, phone_number=_UNSPECIFIED,
                    photo_url=_UNSPECIFIED, password=None, disabled=None, email_verified=None,
                    valid_since=None, custom_claims=_UNSPECIFIED):
        """Updates an existing user account with the specified properties"""
        payload = {
            'localId': _auth_utils.validate_uid(uid, required=True),
            'email': _auth_utils.validate_email(email),
            'password': _auth_utils.validate_password(password),
            'validSince': _auth_utils.validate_timestamp(valid_since, 'valid_since'),
            'emailVerified': bool(email_verified) if email_verified is not None else None,
            'disableUser': bool(disabled) if disabled is not None else None,
        }

        remove = []
        if display_name is not _UNSPECIFIED:
            if display_name is None:
                remove.append('DISPLAY_NAME')
            else:
                payload['displayName'] = _auth_utils.validate_display_name(display_name)
        if photo_url is not _UNSPECIFIED:
            if photo_url is None:
                remove.append('PHOTO_URL')
            else:
                payload['photoUrl'] = _auth_utils.validate_photo_url(photo_url)
        if remove:
            payload['deleteAttribute'] = remove

        if phone_number is not _UNSPECIFIED:
            if phone_number is None:
                payload['deleteProvider'] = ['phone']
            else:
                payload['phoneNumber'] = _auth_utils.validate_phone(phone_number)

        if custom_claims is not _UNSPECIFIED:
            if custom_claims is None:
                custom_claims = {}
            json_claims = json.dumps(custom_claims) if isinstance(
                custom_claims, dict) else custom_claims
            payload['customAttributes'] = _auth_utils.validate_custom_claims(json_claims)

        payload = {k: v for k, v in payload.items() if v is not None}
        try:
            response = self._client.request('post', 'setAccountInfo', json=payload)
        except requests.exceptions.RequestException as error:
            self._handle_http_error(
                USER_UPDATE_ERROR, 'Failed to update user: {0}.'.format(uid), error)
        else:
            if not response or not response.get('localId'):
                raise ApiCallError(USER_UPDATE_ERROR, 'Failed to update user: {0}.'.format(uid))
            return response.get('localId')
Ejemplo n.º 11
0
 def create_user(self,
                 uid=None,
                 display_name=None,
                 email=None,
                 phone_number=None,
                 photo_url=None,
                 password=None,
                 disabled=None,
                 email_verified=None):
     """Creates a new user account with the specified properties."""
     payload = {
         'localId':
         _auth_utils.validate_uid(uid),
         'displayName':
         _auth_utils.validate_display_name(display_name),
         'email':
         _auth_utils.validate_email(email),
         'phoneNumber':
         _auth_utils.validate_phone(phone_number),
         'photoUrl':
         _auth_utils.validate_photo_url(photo_url),
         'password':
         _auth_utils.validate_password(password),
         'emailVerified':
         bool(email_verified) if email_verified is not None else None,
         'disabled':
         bool(disabled) if disabled is not None else None,
     }
     payload = {k: v for k, v in payload.items() if v is not None}
     try:
         response = self._client.request('post',
                                         'signupNewUser',
                                         json=payload)
     except requests.exceptions.RequestException as error:
         self._handle_http_error(USER_CREATE_ERROR,
                                 'Failed to create new user.', error)
     else:
         if not response or not response.get('localId'):
             raise ApiCallError(USER_CREATE_ERROR,
                                'Failed to create new user.')
         return response.get('localId')
Ejemplo n.º 12
0
 def uid(self, uid):
     self._uid = _auth_utils.validate_uid(uid, required=True)