def verify_external_auth_associations_are_deleted(user_id): """Returns true if and only if we have successfully verified that all external associations have been deleted. Args: user_id: str. The unique ID of the user whose associations should be checked. Returns: bool. True if and only if we have successfully verified that all external associations have been deleted. """ auth_id = get_auth_id_from_user_id(user_id) if auth_id is None: return True try: with _firebase_admin_context(): firebase_auth.get_user(auth_id) except firebase_auth.UserNotFoundError: return True except (firebase_exceptions.FirebaseError, ValueError): # NOTE: logging.exception appends the stack trace automatically. The # errors are not re-raised because wipeout_services, the user of this # function, will keep retrying the other "delete" family of functions # until this returns True (in 12h intervals). logging.exception('[WIPEOUT] Firebase Admin SDK failed! Stack trace:') return False
def get_user_cards(db, user_private_id): try: auth.get_user(user_private_id) except: return user_not_found(user_private_id) user_public_id = get_user_public_id(user_private_id) user_private_ref = db.collection(u'users').document( user_public_id).collection(u'private').document(user_private_id).get() user_private_data = user_private_ref.to_dict() if user_private_data["stripe_id"] != '': stripe_user = stripe.Customer.retrieve(user_private_data["stripe_id"]) cards = [] for card in stripe_user.sources.data: formatted_card = { "id": card.id, "brand": card.brand, "last4": card.last4, "funding": card.funding, "default": stripe_user.default_source == card.id } cards.append(formatted_card) if len(cards) == 0: return cards_not_found(user_private_id) return JsonResponse({"list": cards}) else: return cards_not_found(user_private_id)
def verify_external_auth_associations_are_deleted(user_id): """Returns true if and only if we have successfully verified that all external associations have been deleted. Args: user_id: str. The unique ID of the user whose associations should be checked. Returns: bool. True if and only if we have successfully verified that all external associations have been deleted. """ auth_id = get_auth_id_from_user_id(user_id, include_deleted=True) if auth_id is None: return True try: # TODO(#11474): Replace with `get_users()` (plural) because `get_user()` # (singular) does not distinguish between disabled and deleted users. We # can't do it right now because firebase-admin==3.2.1 does not offer the # get_users() API. We will need to fix this when we've moved to a more # recent version (after the Python 3 migration). firebase_auth.get_user(auth_id) except firebase_auth.UserNotFoundError: return True except (firebase_exceptions.FirebaseError, ValueError): # NOTE: logging.exception appends the stack trace automatically. The # errors are not re-raised because wipeout_services, the user of this # function, will keep retrying the other "delete" family of functions # until this returns True (in 12h intervals). logging.exception('[WIPEOUT] Firebase Admin SDK failed! Stack trace:') return False
def authenticate(self, request, uid=None): try: auth.get_user(uid) return User.objects.get(uid=uid) except User.DoesNotExist: return User.objects.create(uid=uid) except (auth.AuthError, ValueError): return None
def test_revoke_refresh_tokens(new_user): user = auth.get_user(new_user.uid) old_valid_after = user.tokens_valid_after_timestamp time.sleep(1) auth.revoke_refresh_tokens(new_user.uid) user = auth.get_user(new_user.uid) new_valid_after = user.tokens_valid_after_timestamp assert new_valid_after > old_valid_after
def get(self): try: firebase_auth.get_user(g.user.firebase_uid) except (ValueError, firebase_auth.AuthError) as e: return {'message': f'{e}'}, 400 custom_token = firebase_auth.create_custom_token(g.user.firebase_uid) return {'custom_token': custom_token.decode()}
def create_custom_token(uid: str): try: auth.get_user(uid, app=app) except auth.UserNotFoundError: auth.create_user(uid=uid, app=app) custom_token = auth.create_custom_token(uid, app=app) return custom_token
def is_verified(uid): try: firebase_auth.get_user(uid) except: return False try: return fireClient.collection("users").document(uid).get().get("tier") == "director" except: return False
def root(): if request.method == 'GET': all_user_posts = db.collection('Posts').where( 'uid', '==', session['user_id']).get() user_record = auth.get_user(session['user_id']) params = { "first_name": user_record.display_name, "all_posts": all_user_posts, "user_image_url": user_record.photo_url, "user": user_record } for post in all_user_posts: collection = post.collection('Comments') print(collection) return render_template('home.html', **params) elif request.method == 'POST': user_record = auth.get_user(session['user_id']) if request.files['PostImage'] is not None: tags = [ request.form['tag1'], request.form['tag2'], request.form['tag3'] ] uploaded_file = request.files['PostImage'] photo_url = upload_file_helper(uploaded_file) post = Post(image_url=photo_url, uid=session['user_id'], username=user_record.display_name, tags=tags) db.collection('Posts').add(post.to_dict()) all_user_posts = db.collection('Posts').where( 'uid', '==', session['user_id']).stream() template_vars = { "all_posts": all_user_posts, "first_name": user_record.display_name, "user_image_url": user_record.photo_url, "user": user_record } return render_template("home.html", **template_vars) else: all_user_posts = db.collection('Posts').where( 'uid', '==', session['user_id']).stream() template_vars = { "all_posts": all_user_posts, "first_name": user_record.display_name, "user_image_url": user_record.photo_url, "user": user_record } for post in all_user_posts: print(post) return render_template("home.html", **template_vars)
def are_auth_associations_deleted(user_id): """Returns whether the Firebase account of the given user ID is deleted.""" assoc_model = ( auth_models.UserIdByFirebaseAuthIdModel.get_by_user_id(user_id)) if assoc_model is None: return True try: with _acquire_firebase_context(): firebase_auth.get_user(assoc_model.id) except firebase_auth.UserNotFoundError: return True except (ValueError, firebase_exceptions.FirebaseError) as e: logging.exception(e) return False
def get_user_info_by_uid(self, uid=None): if uid == None: user = self._db.collection('users').document(self._uid).get() else: try: auth.get_user(uid) user = self._db.collection('users').document(uid).get() except: return {'msg': '找不到使用者!'}, status_code.NOT_FOUND if user.exists: user_dict = User.from_dict(user.to_dict()).to_dict() user_dict.update({'uid': user.id}) print(user_dict, file=sys.stderr) return user_dict, status_code.OK
def add_chapter(): if "uid" not in session or not is_verified(session["uid"]): return redirect(url_for("auth.login", redirect=url_for("info.add_chapter"))) if request.method == "GET": return render_template("create_chapter.html") if not request.json or "name" not in request.json or "officers" not in request.json or any(role not in request.json["officers"] for role in officer_roles): abort(400, "Malformed chapter creation request") try: for role in officer_roles: firebase_auth.get_user(request.json["officers"][role]) except: abort(404, "Officer UIDs not found") chapters_info_obj = fireClient.collection("info").document("chapter_info").get() chapter_id = chapters_info_obj.get("id_counter") chapter_id = str(chapter_id) while len(chapter_id) < 3: chapter_id = "0" + chapter_id chapter_dict = chapters_info_obj.get("chapters") chapter_dict[request.json["name"]] = chapter_id fireClient.collection("info").document("chapter_info").set( { "id_counter": int(chapter_id) + 1, "chapters": chapter_dict } ) chapter_ref = fireClient.collection("info").document("chapter_info").collection("chapters").document(chapter_id) try: officers = request.json["officers"] chapter = { "name": request.json["name"], "officers": { role: officers[role] for role in officer_roles }, "ambassadors": [] } except KeyError: abort(400, "Malformed chapter creation request") batch_write = fireClient.batch() batch_write.set(chapter_ref, chapter) for uid in officers.values(): user_ref = fireClient.collection("users").document(uid) old_user = user_ref.get().to_dict() old_user["tier"] = "officer" batch_write.set(fireClient.collection("users").document(uid), old_user) batch_write.commit() return redirect(url_for("info.view_chapter", chapter_id=chapter_id))
def test_update_custom_user_claims(new_user): assert new_user.custom_claims is None claims = {'admin': True, 'package': 'gold'} auth.set_custom_user_claims(new_user.uid, claims) user = auth.get_user(new_user.uid) assert user.custom_claims == claims claims = {'admin': False, 'subscription': 'guest'} auth.set_custom_user_claims(new_user.uid, claims) user = auth.get_user(new_user.uid) assert user.custom_claims == claims auth.set_custom_user_claims(new_user.uid, None) user = auth.get_user(new_user.uid) assert user.custom_claims is None
def register(): conn, cur = get_database_connection() try: json = request.get_json() username = json['username'].lower() email = str(auth.get_user(g.uid).email) user = User(uid=g.uid, username=username, email=email) cur.execute( """ INSERT into \"users\" (uid, username, email, fcm_token, device_id, public_address, balance, transactions) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, [user.uid, user.username, user.email, user.fcm_token, user.device_id, user.public_address, user.balance, user.transactions] ) conn.commit() return jsonify(), 200 except Exception as e: print(e) sys.stdout.flush() return jsonify(), 500 finally: cur.close() conn.close()
def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if not auth_header: return None # raise NoAuthToken("No auth token provided") id_token = auth_header.split(" ").pop() decoded_token = None try: decoded_token = auth.verify_id_token(id_token) except Exception: raise InvalidAuthToken("Invalid auth token") if not id_token or not decoded_token: return None try: uid = decoded_token.get("uid") except Exception: raise FirebaseError() firebase_user = auth.get_user(uid) email = firebase_user.email if email is not None: user, created = User.objects.get_or_create(username=uid, email=email) else: user, created = User.objects.get_or_create(username=uid) return (user, None)
def test_last_refresh_timestamp(new_user_with_params: auth.UserRecord, api_key): # new users should not have a last_refresh_timestamp set assert new_user_with_params.user_metadata.last_refresh_timestamp is None # login to cause the last_refresh_timestamp to be set _sign_in_with_password(new_user_with_params.email, 'secret', api_key) # Attempt to retrieve the user 3 times (with a small delay between each # attempt). Occassionally, this call retrieves the user data without the # lastLoginTime/lastRefreshTime set; possibly because it's hitting a # different server than the login request uses. user_record = None for iteration in range(0, 3): user_record = auth.get_user(new_user_with_params.uid) if user_record.user_metadata.last_refresh_timestamp is not None: break time.sleep(2**iteration) # Ensure the last refresh time occurred at approximately 'now'. (With a # tolerance of up to 1 minute; we ideally want to ensure that any timezone # considerations are handled properly, so as long as we're within an hour, # we're in good shape.) millis_per_second = 1000 millis_per_minute = millis_per_second * 60 last_refresh_timestamp = user_record.user_metadata.last_refresh_timestamp assert last_refresh_timestamp == pytest.approx( time.time() * millis_per_second, 1 * millis_per_minute)
def post(self, uid, token): """Authenticate with Firebase uid and token.""" if not app.config['FEAT_TOGGLE_FIREBASE']: return "Firebase authentication is disabled", 501 try: decoded_token = auth.verify_id_token(token) except ValueError: return "Invalid firebase credentials", 401 if 'email' not in decoded_token: decoded_token['email'] = ( auth.get_user(uid).provider_data[0].email) try: user = User.query.filter_by(firebase_uid=uid).one() except NoResultFound: try: # no firebase user for this provider, but they may have # signed up with a different provider but the same email user = User.query.filter_by(email=decoded_token['email']).one() except NoResultFound: # no such user - create a new one user = create_firebase_user(uid, decoded_token) return sign_claims(user)
def test_import_users_with_password(api_key): uid, email = _random_id() password_hash = base64.b64decode( 'V358E8LdWJXAO7muq0CufVpEOXaj8aFiC7T/rcaGieN04q/ZPJ08WhJEHGjj9lz/2TT+/86N5VjVoc5DdBhBiw==' ) user = auth.ImportUserRecord(uid=uid, email=email, password_hash=password_hash, password_salt=b'NaCl') scrypt_key = base64.b64decode( 'jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA==' ) salt_separator = base64.b64decode('Bw==') scrypt = auth.UserImportHash.scrypt(key=scrypt_key, salt_separator=salt_separator, rounds=8, memory_cost=14) result = auth.import_users([user], hash_alg=scrypt) try: assert result.success_count == 1 assert result.failure_count == 0 saved_user = auth.get_user(uid) assert saved_user.email == email id_token = _sign_in_with_password(email, 'password', api_key) assert len(id_token) > 0 finally: auth.delete_user(uid)
def verify_login(): """ Handles the senduser request which will fetch the current user from firebase :return: """ if request.method != "POST": return {"message": "Not a Post Request"} data = request.get_json() if 'uid' in data: current_user = auth.get_user(data['uid'], default_app) email = get_user_info(current_user)['email'] print(email) #add account document to db if not present if not accountCheck(current_user): nameDict = {} nameDict["name"] = get_user_info(current_user)['name'] nameDict["profile_count"] = 0 nameDict["profiles"] = [] accounts.document(email).set(nameDict) print(get_user_info(current_user)) return {"message": "Request Successful", "status_code": 200} else: raise InvalidUID("The provided UID is invalid")
def login(): if request.method == "GET": if "redirect" in request.args: return render_template("login.html", redirect=request.args.get("redirect")) return render_template("login.html") try: idToken = request.json["idToken"] except KeyError: abort(400, "Request must include id token from login page") try: verified_dict = firebase_auth.verify_id_token(idToken) uid = verified_dict["uid"] except: abort(400, "Invalid ID token") session["uid"] = uid user_info = firebase_auth.get_user(uid) session["user"] = serialize_userrecord(user_info) print(session) if user_info.display_name: session["name"] = user_info.display_name else: session["name"] = "Click to setup profile" if "redirect" in request.json: return redirect(request.json["redirect"]) else: return redirect(url_for("bakesale.index"))
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
def test_email_verification(new_user_email_unverified, api_key): link = auth.generate_email_verification_link(new_user_email_unverified.email) assert isinstance(link, str) query_dict = _extract_link_params(link) user_email = _verify_email(query_dict['oobCode'], api_key) assert new_user_email_unverified.email == user_email assert auth.get_user(new_user_email_unverified.uid).email_verified
def authenticate_credentials(self, firebase_token): try: decoded_token = firebase_auth.verify_id_token( firebase_token, app=self.get_firebase_app(), check_revoked=self.check_revoked, ) except (ValueError, firebase_auth.InvalidIdTokenError) as e: # Token was either not a string or empty or not an valid Firebase ID token msg = _('The Firebase token was invalid.') raise AuthenticationFailed(msg) except firebase_auth.ExpiredIdTokenError: msg = _('The Firebase token has expired.') raise AuthenticationFailed(msg) except firebase_auth.RevokedIdTokenError: msg = _('The Firebase token has been revoked.') raise AuthenticationFailed(msg) except firebase_auth.CertificateFetchError: msg = _('Temporarily unable to verify the ID token.') raise AuthenticationFailed(msg) firebase_uid = decoded_token['uid'] firebase_user_record = firebase_auth.get_user( firebase_uid, app=self.get_firebase_app(), ) # This template method must be implemented in a subclass. user = self.get_django_user(firebase_user_record) if user is None: msg = _('No matching local user found.') raise AuthenticationFailed(msg) return user, firebase_token
def csignin(): email = request.json['email'] password = request.json['password'] if email is None or password is None: return jsonify( {'message': 'username and passowrd must not to be empty'}), 400 try: user = pb.auth().sign_in_with_email_and_password(email, password) carr = '' for x in user: if x == 'localId': carr = (user[x]) cuser1 = auth.get_user(carr) cuser2 = cuser1.custom_claims.get('owner') cuser3 = cuser1.email_verified # print(cuser2) if not cuser2: if cuser3: return user else: return jsonify( {'message': 'please verify your account with your mailId'}), 400 else: return jsonify({'message': 'You are not customer to access it'}), 400 except: return jsonify({ 'message': 'invalid crendentails please enter with valid credentials' }), 400
def post(self): args = request.get_json(force=True, silent=True) if (args is None): with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['AUTH_ERROR']['VALUE_ERROR'], 500 # pylint: disable=E1101 try: decoded_token = auth.verify_id_token(args['data']['token']) current_user = auth.get_user(decoded_token['uid']) try: user = User_model.objects.get(uuid=current_user.uid) except DoesNotExist: user = User_model(uuid=current_user.uid, name=current_user.display_name, photo_url=current_user.photo_url) user.save() return eval(dumps(user.id)), 200 except ValueError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['AUTH_ERROR']['VALUE_ERROR'], 500 except auth.InvalidIdTokenError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['AUTH_ERROR']['INVALID_IDTOKEN_ERROR'], 500 except auth.CertificateFetchError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['AUTH_ERROR']['CERTIFICATE_FETCH_ERROR'], 500
def edit_profile(): if "uid" not in session: return redirect(url_for("auth.login")) uid = session["uid"] user = firebase_auth.get_user(session["uid"]) if request.method == "GET": return render_template("edit_profile.html", user=user) try: if session["uid"] != request.form["uid"]: abort(400, "UID does not match session") phone = ''.join(c for c in request.form["phone"] if c.isdigit() or c == '+') if "+" not in phone: phone = "+1" + phone if user.display_name and request.form["name"] != user.display_name: user_ref = fireClient.collection("users").document(user.uid) user_dict = user_ref.get().to_dict() user_dict["name_array"] = request.form["name"].lower().split() user_ref.set(user_dict) firebase_auth.update_user( uid=session["uid"], display_name=request.form["name"], email=request.form["email"], phone_number=phone ) except Exception as e: abort(400, "Malformed edit profile request: " + str(e)) return redirect(url_for("info.view_profile", uid=session["uid"]))
def test_verify_session_cookie_revoked(new_user, api_key): custom_token = auth.create_custom_token(new_user.uid) id_token = _sign_in(custom_token, api_key) session_cookie = auth.create_session_cookie( id_token, expires_in=datetime.timedelta(days=1)) time.sleep(1) auth.revoke_refresh_tokens(new_user.uid) claims = auth.verify_session_cookie(session_cookie, check_revoked=False) user = auth.get_user(new_user.uid) # verify_session_cookie succeeded because it didn't check revoked. assert claims['iat'] * 1000 < user.tokens_valid_after_timestamp with pytest.raises(auth.AuthError) as excinfo: claims = auth.verify_session_cookie(session_cookie, check_revoked=True) assert excinfo.value.code == auth._SESSION_COOKIE_REVOKED assert str( excinfo.value) == 'The Firebase session cookie has been revoked.' # Sign in again, verify works. id_token = _sign_in(custom_token, api_key) session_cookie = auth.create_session_cookie( id_token, expires_in=datetime.timedelta(days=1)) claims = auth.verify_session_cookie(session_cookie, check_revoked=True) assert claims['iat'] * 1000 >= user.tokens_valid_after_timestamp
def login(self, uid): try: user_firebase = auth.get_user(uid) users = User.objects.filter(uid=user_firebase.uid) is_active = False if users: user = users[0] if user.is_active: is_active = True else: return HttpResponseBadRequest("User inactive") else: user = User.create(email=user_firebase.email, uid=user_firebase.uid, password=None, phone=user_firebase.phone_number, avatar_url=user_firebase.photo_url, name=user_firebase.display_name, role=Role.create(role_id=1, name="USER")) user.save() return user, is_active except UserNotFoundError: return HttpResponseBadRequest("User not found") except (ValueError, KeyError): return HttpResponseBadRequest( "Error when retrieve user info: invalid uid") except FirebaseError: return HttpResponseServerError( "Cannot retrieve user info from firebase")
def get_user_accounts(user_id): try: default_app = get_firebase_app() # Get Accounts from claims # user = auth.get_user(user_id) user_accounts = user.custom_claims.get("accounts") # TESTING # Get roles # user_roles = user.custom_claims.get("studioRoles") print(user_roles) print("User Id : {}".format(user_id)) print("User accounts : {}".format(user_accounts)) return user_accounts except Exception as ex: print("Error while getting user accounts.\n{}".format(ex)) return None
def view_profile(uid): try: user = firebase_auth.get_user(uid) except: abort(404, "User not found") return render_template("view_profile.html", user=user)