Example #1
0
def test_list_users(new_user_list):
    err_msg_template = (
        'Missing {field} field. A common cause would be forgetting to add the "Firebase '
        +
        'Authentication Admin" permission. See instructions in CONTRIBUTING.md'
    )

    fetched = []
    # Test exporting all user accounts.
    page = auth.list_users()
    while page:
        for user in page.users:
            assert isinstance(user, auth.ExportedUserRecord)
            if user.uid in new_user_list:
                fetched.append(user.uid)
                assert user.password_hash is not None, (
                    err_msg_template.format(field='password_hash'))
                assert user.password_salt is not None, (
                    err_msg_template.format(field='password_salt'))
        page = page.get_next_page()
    assert len(fetched) == len(new_user_list)

    fetched = []
    page = auth.list_users()
    for user in page.iterate_all():
        assert isinstance(user, auth.ExportedUserRecord)
        if user.uid in new_user_list:
            fetched.append(user.uid)
            assert user.password_hash is not None, (err_msg_template.format(
                field='password_hash'))
            assert user.password_salt is not None, (err_msg_template.format(
                field='password_salt'))
    assert len(fetched) == len(new_user_list)
def list_all_users():
    # [START list_all_users]
    # Start listing users from the beginning, 1000 at a time.
    page = auth.list_users()
    while page:
        for user in page.users:
            print('User: '******'User: ' + user.uid)
Example #3
0
    def test_list_multiple_pages(self, user_mgt_app):
        # Page 1
        response = {
            'users': [{
                'localId': 'user1'
            }, {
                'localId': 'user2'
            }, {
                'localId': 'user3'
            }],
            'nextPageToken':
            'token'
        }
        _, recorder = _instrument_user_manager(user_mgt_app, 200,
                                               json.dumps(response))
        page = auth.list_users(app=user_mgt_app)
        assert len(page.users) == 3
        assert page.next_page_token == 'token'
        assert page.has_next_page is True
        self._check_rpc_calls(recorder)

        # Page 2 (also the last page)
        response = {'users': [{'localId': 'user4'}]}
        _, recorder = _instrument_user_manager(user_mgt_app, 200,
                                               json.dumps(response))
        page = page.get_next_page()
        assert len(page.users) == 1
        assert page.next_page_token == ''
        assert page.has_next_page is False
        assert page.get_next_page() is None
        self._check_rpc_calls(recorder, {
            'maxResults': '1000',
            'nextPageToken': 'token'
        })
    def test_list_users_paged_iteration(self, user_mgt_app):
        # Page 1
        response = {
            'users': [{'localId': 'user1'}, {'localId': 'user2'}, {'localId': 'user3'}],
            'nextPageToken': 'token'
        }
        _, recorder = _instrument_user_manager(user_mgt_app, 200, json.dumps(response))
        page = auth.list_users(app=user_mgt_app)
        assert page.next_page_token == 'token'
        assert page.has_next_page is True
        iterator = page.iterate_all()
        for index in range(3):
            user = next(iterator)
            assert user.uid == 'user{0}'.format(index+1)
        assert len(recorder) == 1
        self._check_rpc_calls(recorder)

        # Page 2 (also the last page)
        response = {'users': [{'localId': 'user4'}]}
        _, recorder = _instrument_user_manager(user_mgt_app, 200, json.dumps(response))
        user = next(iterator)
        assert user.uid == 'user4'
        with pytest.raises(StopIteration):
            next(iterator)
        self._check_rpc_calls(recorder, {'maxResults': 1000, 'nextPageToken': 'token'})
Example #5
0
 def test_list_users_no_users_response(self, user_mgt_app):
     response = {'users': []}
     _instrument_user_manager(user_mgt_app, 200, json.dumps(response))
     page = auth.list_users(app=user_mgt_app)
     assert len(page.users) is 0
     users = [user for user in page.iterate_all()]
     assert len(users) is 0
Example #6
0
def prune_anonymous_users_in_firebase_and_django():
    """
    This job deletes all anonymous users that haven't used their account in a week from both Firebase and Django
    """
    page = auth.list_users()
    anonymous_users = []
    for user in page.users:
        user_last_refresh = date.fromtimestamp(
            user.user_metadata.last_refresh_timestamp / 1e3)
        logged_within_one_week = date.today() - timedelta(
            days=7) > user_last_refresh
        if user.email is None and logged_within_one_week:
            anonymous_users.append(user.uid)
    result = auth.delete_users(anonymous_users)

    if len(result.errors) == 0:
        profiles = Profile.objects.filter(is_anonymous=True)
        for profile in profiles:
            profile.user.delete()

    print('Successfully deleted {0} users'.format(result.success_count))
    print('Failed to delete {0} users'.format(result.failure_count))
    for err in result.errors:
        print('error #{0}, reason: {1}'.format(result.index, result.reason))

    db.connections.close_all()
def newAdmin(userID):
    for user in auth.list_users().iterate_all():
        if user.uid == userID:
            newAd = {
                "Customer ID": userID,
            }
            db.child("Admin").push(newAd)
Example #8
0
    def map(item):
        # The map() function must be static, so we manually create a "cls"
        # variable instead of changing the function into a classmethod.
        cls = SyncFirebaseAccountsOneOffJob

        if isinstance(item, auth_models.UserIdByFirebaseAuthIdModel):
            auth_id, assoc_info = (item.id, (cls.ASSOC_BY_AUTH_ID_KEY,
                                             (item.user_id, item.deleted)))
            yield (auth_id, assoc_info)

        elif isinstance(item, auth_models.UserAuthDetailsModel):
            if item.gae_id == feconf.SYSTEM_COMMITTER_ID:
                yield (cls.SYSTEM_COMMITTER_ACK, item.id)
                return
            auth_id, assoc_info = (item.firebase_auth_id
                                   or cls.EMPTY_AUTH_ID_KEY,
                                   (cls.ASSOC_BY_USER_ID_KEY, (item.id,
                                                               item.deleted)))
            yield (auth_id, assoc_info)

        # The item must be an instance of auth_models.FirebaseSeedModel.
        elif item.id == auth_models.ONLY_FIREBASE_SEED_MODEL_ID:
            page = firebase_auth.list_users(max_results=1000)
            user_batch = []
            while page is not None:
                user_batch[:] = page.users  # NOTE: Avoids allocating a new list.
                if not user_batch:
                    break
                for user in user_batch:
                    auth_id, assoc_info = (user.uid, (cls.FIREBASE_ACCOUNT_KEY,
                                                      (None, user.disabled)))
                    yield (auth_id, assoc_info)
                page = page.get_next_page()
Example #9
0
def user_typeahead(request, search_path):
    if len(search_path) < 3:
        return Response(
            {
                "success": "false",
                "error": "InsufficientQueryLength"
            },
            status=status.HTTP_400_BAD_REQUEST)
    try:
        filtered_user = []
        for user in auth.list_users().iterate_all():
            if len(filtered_user) == 5:
                break
            if user.display_name is None:
                continue
            if search_path.lower() in user.display_name.lower():
                filtered_user.append(user)

        users = [{
            "display_name": x.display_name,
            "email_id": x.email
        } for x in filtered_user]
        return Response({
            "success": "true",
            "payload": users
        },
                        status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        return Response({
            "error": 'InternalException',
            "success": "false"
        },
                        status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def revoke_all_user_tokens():
    page = auth.list_users()
    while page:
        for user in page.users:
            auth.revoke_refresh_tokens(user.uid)
            user = auth.get_user(user.uid)
        page = page.get_next_page()
Example #11
0
def create_template():
    if "user" not in session or "uid" not in session["user"]:
        return redirect(
            url_for("auth.login", redirect=url_for("sms.create_template")))
    user_obj = fireClient.collection("users").document(session["uid"]).get()
    if not user_obj.exists or user_obj.to_dict().get("tier", "") != "director":
        abort(401)
    if request.method == "GET":
        return render_template("create_template.html",
                               available_data=access_property)
    template = {
        "template": request.form["template"],
        "author": {
            "uid": session["user"]["uid"],
            "name": session["user"]["display_name"]
        },
        "generated": False,
        "recipients": {
            user.uid: False
            for user in firebase_auth.list_users().iterate_all()
            if user.uid not in director_uids
        },
        "UTC_timestamp": str(datetime.utcnow())
    }
    template_obj = fireClient.collection("message_templates").document()
    fireClient.collection("message_templates").document(
        template_obj.id).set(template)
    return redirect(url_for("sms.view_template", template_id=template_obj.id))
Example #12
0
def sendMails(distance_value):
    #send email to users
    page = auth.list_users()
    mail_list = []
    while page:
        for user in page.users:
            mail_list.append(user.email)
        # Get next batch of users.
        page = page.get_next_page()

    msg = MIMEMultipart()
    msg['From'] = email
    msg['To'] = ", ".join(mail_list)
    msg['Subject'] = 'Rivertracker alert: Device ' + str(
        device_id) + ' is reporting abnormal readings! ' + str(
            distance_value) + " cm."

    body = "We detected that device # " + str(
        device_id) + ' is reporting abnormal readings: ' + str(
            distance_value) + " cm.\nhttps://river-tracker-295612.web.app/"
    msg.attach(MIMEText(body, 'plain'))
    text = msg.as_string()

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email, password)
    print("The login was done succesfully !")
    server.sendmail(email, mail_list, text)
    print("The email was sent to ", mail_list)
Example #13
0
def all_test_user_emails_in_production_db():
    page = auth.list_users()
    for uid in all_uids():
        user = auth.get_user(uid)
        email = user.email
        if string_strongly_resembles_test_generated_email(email):
            yield email
Example #14
0
    def test_list_users_iterator_state(self, user_mgt_app):
        response = {
            'users': [{
                'localId': 'user1'
            }, {
                'localId': 'user2'
            }, {
                'localId': 'user3'
            }]
        }
        _, recorder = _instrument_user_manager(user_mgt_app, 200,
                                               json.dumps(response))
        page = auth.list_users(app=user_mgt_app)

        # Iterate through 2 results and break.
        index = 0
        iterator = page.iterate_all()
        for user in iterator:
            index += 1
            assert user.uid == 'user{0}'.format(index)
            if index == 2:
                break

        # Iterator should resume from where left off.
        user = next(iterator)
        assert user.uid == 'user3'
        with pytest.raises(StopIteration):
            next(iterator)
        self._check_rpc_calls(recorder)
Example #15
0
 def get_users(self):
     """
     the auth users
     """
     return [{
         'email': u.email,
         'id': u.localId
     } for u in auth.list_users(app=self.app).iterate_all()]
Example #16
0
def get_users() -> list:
    """Get all Firebase users.
    Returns:
        (list): A list of Firebase users.
    """
    users = []
    for user in auth.list_users().iterate_all():
        users.append(user)
    return users
def list_users():
    page = auth.list_users()
    while page:
        for user in page.users:
            print(
                'UID: {0}, Name: {1}, Email: {2}, Email verified: {3}'.format(
                    user.uid, user.display_name, user.email,
                    user.email_verified))
        page = page.get_next_page()
Example #18
0
def users():
    """ to get all users"""
    page = auth.list_users()
    for user in page.users:
        user_email = user.email if hasattr(user, 'email') else None
        user_displayName = user.displayName if hasattr(user,
                                                       'displayName') else None
        text = f'{user.uid}, - , {user_email} - {user_displayName}'
        print_style(text, fg=Fore.MAGENTA)
Example #19
0
 def get_results(self):
     result = list()
     for user in auth.list_users().users:
         data = user._data.get('providerUserInfo')[-1]
         data['id'] = user._data.get('localId')
         if self.query in str(data.get('displayName')) or\
             self.query in str(data.get('email')):
             result.append(data)
     return result
Example #20
0
 def get(self, request):
     list_ = []
     for user in auth.list_users().iterate_all():
         list_.append({
             'uid': user.uid,
             'email': user.email,
             'status': user.disabled
         })
     return JsonResponse(list_, safe=False)
 def test_list_single_page(self, user_mgt_app):
     _, recorder = _instrument_user_manager(user_mgt_app, 200, MOCK_LIST_USERS_RESPONSE)
     page = auth.list_users(app=user_mgt_app)
     self._check_page(page)
     assert page.next_page_token == ''
     assert page.has_next_page is False
     assert page.get_next_page() is None
     users = [user for user in page.iterate_all()]
     assert len(users) == 2
     self._check_rpc_calls(recorder)
Example #22
0
def get_all_user():
    res = []
    for user in auth.list_users().iterate_all():
        roles = None
        if not user.custom_claims is None:
            roles = list(user.custom_claims.keys())
        res.append({'uid': user.uid, 'email': user.email, 'roles': roles})
        #print('User: ' + user.uid)
    print(res)
    return res
Example #23
0
def signIn():
    body = request.json
    snapshot = body['snapshot']

    try:
        binary = base64.b64decode(snapshot)
        image = np.asarray(bytearray(binary), dtype="uint8")
        image = cv.imdecode(image, cv.IMREAD_COLOR)
        face = return_face(image)
        if face is None:
            raise Exception("No face detected")
        thumbnail = return_square_face(image)
        eigenface_original = get_eigenface(face)

        scores = []
        uids = []

        base64face = f"data:image/jpg;base64,{base64.b64encode(cv.imencode('.jpg', thumbnail)[1]).decode()}"

        max_score = 0

        for user in auth.list_users().iterate_all():
            blob = bucket.blob(f"{user.uid}.jpg")
            binary = blob.download_as_string()
            image = np.asarray(bytearray(binary), dtype="uint8")
            image = cv.imdecode(image, cv.IMREAD_COLOR)
            eigenface_iteration = get_eigenface(return_face(image))
            score = cosine_similarity(eigenface_iteration, eigenface_original)

            uids.append(user.uid)
            scores.append(score)

            print(f'User {user.uid} | score: {score} | distance {1/score}')

        max_score = max(scores)
        max_score_index = scores.index(max_score)
        max_score_uid = uids[max_score_index]
        print(f'Max Score = {max_score} | Max Score User {max_score_uid}')
    except Exception as e:
        return {'message': str(e), 'code': 500}, 500

    if (max_score >= SCORE_THRESHOLD):
        return {
            'uid': max_score_uid,
            'token': generate_token(max_score_uid),
            'score': max_score,
            'face': base64face
        }
    else:
        return {
            'message': 'Did not find match.',
            'score': max_score,
            'face': base64face,
            'code': 401
        }, 401
Example #24
0
 def yield_firebase_user_batches(cls):
     """Yields every single Firebase account in batches."""
     # 1000 is the maximum amount of users that can be deleted at once.
     page = firebase_auth.list_users(
         max_results=cls.MAX_USERS_FIREBASE_CAN_DELETE_PER_CALL)
     while page is not None:
         user_batch = page.users
         if not user_batch:
             break
         yield user_batch
         page = page.get_next_page()
def getUsers():
    lst = []
    for user in auth.list_users().iterate_all():
        try:
            username = user.display_name
        except AttributeError:
            username = "******"

        userInfo = {"User ID": user.uid, "User Name": username}
        lst.append(userInfo)
    return lst
 def do_list(self, args):
     for user in auth.list_users().iterate_all():
         try:
             doc = db.collection(USER_COLLECTION).document(user.uid).get()
             display_name = doc.to_dict()['name']
         except:
             display_name = ""
         line =  display_name + (" " * max(0,20-len(display_name)))
         line += user.email   + (" " * max(0,40-len(user.email)))
         line += user.uid
         print(line)
Example #27
0
 def test_list_users_with_all_args(self, user_mgt_app):
     _, recorder = _instrument_user_manager(user_mgt_app, 200,
                                            MOCK_LIST_USERS_RESPONSE)
     page = auth.list_users(page_token='foo',
                            max_results=500,
                            app=user_mgt_app)
     self._check_page(page)
     self._check_rpc_calls(recorder, {
         'nextPageToken': 'foo',
         'maxResults': '500'
     })
Example #28
0
def get_user_dict():
    # Set dictionary.
    uid2email = {}
    # Start listing users from the beginning, 1000 at a time.
    page = auth.list_users()
    while page:
        for user in page.users:
            #         print(user.uid, user.email)
            uid2email[user.uid] = user.email
        # Get next batch of users.
        page = page.get_next_page()
    return uid2email
Example #29
0
 def get(self, request):
     list_ = []
     for user in auth.list_users().iterate_all():
         list_.append({
             'uid': user.uid,
             'email': user.email,
             'status': user.disabled
         })
     print(list_)
     return render(request, self.template, {
         'title': 'List User',
         'data': list_
     })
Example #30
0
def insert_resource_certificate_request(uid, resource_id):
    user = next(x for x in auth.list_users().users if x.uid == uid)
    image = firebase_images.child(resource_id).get()
    requestsRef = firebase_images.child(resource_id).child('requests')
    requests = requestsRef.get()
    requests = requests if requests else list()
    requests.append({
        'userId': uid,
        'userName': user.display_name,
        'resourceId': resource_id,
        'resourceName': image['fileName']
    })
    requestsRef.set(requests)