def test_unexpected_error_response(self, user_mgt_app): _instrument_user_manager(user_mgt_app, 500, '{}') with pytest.raises(exceptions.InternalError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert str(excinfo.value) == 'Unexpected error response: {}'
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 test_unexpected_response(self, user_mgt_app): _instrument_user_manager(user_mgt_app, 200, '{}') with pytest.raises(auth.UnexpectedResponseError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert excinfo.value.code == exceptions.UNKNOWN assert 'Failed to create session cookie' in str(excinfo.value)
def test_error_with_details(self, user_mgt_app): _instrument_user_manager( user_mgt_app, 500, '{"error":{"message": "INVALID_ID_TOKEN: More details."}}') with pytest.raises(auth.InvalidIdTokenError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert excinfo.value.code == exceptions.INVALID_ARGUMENT expected = 'The provided ID token is invalid (INVALID_ID_TOKEN). More details.' assert str(excinfo.value) == expected
def test_error(self, user_mgt_app): _instrument_user_manager(user_mgt_app, 500, '{"error":"test"}') with pytest.raises(auth.AuthError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert excinfo.value.code == _token_gen.COOKIE_CREATE_ERROR assert '{"error":"test"}' in str(excinfo.value)
def test_unexpected_response(self, user_mgt_app): _instrument_user_manager(user_mgt_app, 200, '{}') with pytest.raises(auth.AuthError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert excinfo.value.code == _token_gen.COOKIE_CREATE_ERROR assert 'Failed to create session cookie' in str(excinfo.value)
def test_unexpected_error_code(self, user_mgt_app): _instrument_user_manager(user_mgt_app, 500, '{"error":{"message": "SOMETHING_UNUSUAL"}}') with pytest.raises(exceptions.InternalError) as excinfo: auth.create_session_cookie('id_token', expires_in=3600, app=user_mgt_app) assert str(excinfo.value ) == 'Error while calling Auth service (SOMETHING_UNUSUAL).'
def _login(email, password, expires=5): with open('private/apikey.txt') as f: api_key = f.read() url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={}'.format( api_key) headers = {'Content-type': 'application/json'} data = json.dumps({ 'email': email, 'password': password, 'returnSecureToken': True }) result = requests.post( url=url, headers=headers, data=data, ) result = result.json() print(result) # エラーがある場合 if 'error' in result: return result, None # セッションクッキーの作成 session_cookie = auth.create_session_cookie(result['idToken'], timedelta(days=expires)) return result, session_cookie
def login(): if '_session' in request.cookies: return jsonify({'status': 'success'}) # Get the ID token sent by the client id_token = request.json['idToken'] # To ensure that cookies are set only on recently signed in users, check auth_time in # ID token before creating a cookie. try: decoded_claims = auth.verify_id_token(id_token) uid = decoded_claims['uid'] user = auth.get_user(uid) print('Successfully fetched user data: {0}'.format(user.email)) # Only process if the user signed in within the last 5 minutes. if time.time() - decoded_claims['auth_time'] < 5 * 60: expires_in = datetime.timedelta(days=5) expires = datetime.datetime.now() + expires_in session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = jsonify({'status': 'success'}) response.set_cookie( '_session', session_cookie, expires=expires, httponly=True, secure=True) return response # User did not sign in recently. To guard against ID token theft, require # re-authentication. return abort(401, 'Recent sign in required') except auth.InvalidIdTokenError: return abort(401, 'Invalid ID token') except exceptions.FirebaseError: return abort(401, 'Failed to create a session cookie')
def sessionLogin(): # Get the ID token sent by the client idToken = request.data # Set session expiration to 5 days. expires_in = datetime.timedelta(days=5) try: # Create the session cookie. This will also verify the ID # token in the process. The session cookie will have the # same claims as the ID token. session_cookie = auth.create_session_cookie(idToken, expires_in=expires_in) decoded_claims = auth.verify_session_cookie(session_cookie) session['sub'] = decoded_claims['uid'] session['name'] = decoded_claims['name'] response = jsonify({'status': 'success'}) # Set cookie policy for session cookie. expires = datetime.datetime.now() + expires_in response.set_cookie( 'token', session_cookie, expires=expires, httponly=True ) return response except auth.AuthError: return abort(401, 'Failed to create a session cookie')
def post(self): id_token = request.json['idToken'] uid = request.json['uid'] expires_in = datetime.timedelta(days=2) try: userInfo = pymongo.collection.Collection(db, 'userInfo') userInfos = userInfo.find() user = [] for u in userInfos: if u['uid'] == uid: user.append({ 'email': u['email'], 'name': u['name'], 'address': u['address'], 'phoneNumber': u['phoneNumber'], 'cardNum': u['cardNum'], 'level': u['level'], 'total_order': u['total_order'], 'uid': u['uid'], 'staff': u['staff'] }) session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = jsonify({'status': 'success', 'userInfo': user}) expires = datetime.datetime.now() + expires_in response.set_cookie('session', session_cookie, expires=expires, httponly=True) return response except Exception.FirebaseError: return abort(401, "Failed")
def session_login(): """ Session login :return: """ print("Session Login") # Get the ID token sent by the client # id_token = request.headers.get('csfToken') id_token = request.values.get('idToken') # Set session expiration to 5 days. expires_in = datetime.timedelta(days=5) try: # Create the session cookie. This will also verify the ID token in the process. # The session cookie will have the same claims as the ID token. session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = jsonify({'status': 'success'}) # Set cookie policy for session cookie. expires = datetime.datetime.now() + expires_in response.set_cookie('session', session_cookie, expires=expires, httponly=True, secure=True) return response except exceptions.FirebaseError: return abort(401, 'Failed to create a session cookie')
def user_login(): if (request.method == "POST"): user_email = request.form['userEmail'] user_password = request.form['userPassword'] flash_msg = None try: user_recode = user_auth.sign_in_user_with_email_password( user_email, user_password) # get idToken user_id_token = user_recode.get('idToken') # get a session cookie using id token and set it in sessions # this will automatically create secure cookies under the hood user_session_cookie = auth.create_session_cookie( user_id_token, expires_in=datetime.timedelta(days=14)) session['session_id'] = user_session_cookie # if username passwd valid then redirect to index page return redirect(url_for('index_page')) except requests.HTTPError as e: if ("EMAIL_NOT_FOUND" in str(e)): flash_msg = "Please register before login" elif ("INVALID_EMAIL" in str(e)): flash_msg = "Please enter a valid email address" elif ("INVALID_PASSWORD" in str(e)): flash_msg = "Email or Password is wrong" else: flash_msg = "Something is wrong!!" flash(flash_msg) # return login page for GET request flash_msg = None return render_template("login.html")
async def check_user(auth_infos: Authorization, response: Response) -> dict: """ Cria um cookie de sessão para um usuario valido. Args: auth_infos (Authorization): informações necessarias para autenticar um usuario no firebase, nesse caso é email e senha. response (Response): Objeto response que vai ser devolvido para o cliente. Returns: dict: dicionario informando que o login foi bem sucedido. """ user_metadata = sign_in_with_email_password(auth_infos) id_token = user_metadata['idToken'] expires_in = datetime.timedelta(days=5) try: session_cookie = auth.create_session_cookie(user_metadata['idToken'], expires_in=expires_in) expires = datetime.datetime.now() + expires_in response.set_cookie(key="session", value=session_cookie) return {'message': 'Logado com sucesso'} except Exception as e: logger.exception(e)
def client_ID_to_session_token(): # Get the ID token sent by the client id_token = request.json['idToken'] # Set session expiration to 5 days. expires_in = datetime.timedelta(days=5) # To ensure that cookies are set only on recently signed in users, check auth_time in ID token before creating a cookie. try: decoded_claims = auth.verify_id_token(id_token) # Only process if the user signed in within the last 5 minutes. if time.time() - decoded_claims['auth_time'] < 5 * 60: expires_in = datetime.timedelta(days=5) expires = datetime.datetime.now() + expires_in session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = jsonify({'status': 'success'}) response.set_cookie('session', session_cookie, expires=expires, httponly=False, secure=False) return response # User did not sign in recently. To guard against ID token theft, require # re-authentication. return abort(401, 'Recent sign in required') except auth.InvalidIdTokenError: return abort(401, 'Invalid ID token') except: return abort(401, 'Failed to create a session cookie')
def sign_user() -> wrappers.Response: """ User SIGN in token verification and cookie creation """ payload = request.json idToken = payload["idToken"] try: authClaims = auth.verify_id_token(idToken) except Exception: return failure(code=401) expiry = timedelta(days=7) timeLimitedAuthToken = auth.create_session_cookie(idToken, expires_in=expiry) userDetails = { "access_token": timeLimitedAuthToken, "email": authClaims["email"] } response = success("user_details", userDetails, 200) response.set_cookie('accessToken', timeLimitedAuthToken, secure=True, domain="awesome-erp.github.io", httponly=True, samesite="Strict") return response
def login(): if request.method == 'POST': resp = request.get_json() if resp == None: abort(400) # Header wasn't formatted correctly for json token = resp['auth_token'] decoded_token = verify_id_token(token) user = User(uid=decoded_token['user_id'], email=decoded_token['email'], role='default', authenticated=True) login_user(user, remember=True) if not user_exists(decoded_token['uid']): add_user(user) print('Adding user') expires_in = datetime.timedelta(days=1) try: session_cookie = create_session_cookie(token, expires_in=expires_in) response = jsonify({'status': 'success'}) expires = datetime.datetime.now() + expires_in response.set_cookie('session', session_cookie, expires=expires, httponly=True, secure=True) return response except FirebaseError: return abort(401, 'Failed to create a session cookie!') return render_template('auth/login.html')
def establish_auth_session(request: webapp2.Request, response: webapp2.Response) -> None: """Sets login cookies to maintain a user's sign-in session. Args: request: webapp2.Request. The request with the authorization to begin a new session. response: webapp2.Response. The response to establish the new session upon. """ claims = _get_auth_claims_from_session_cookie(_get_session_cookie(request)) # If the request already contains a valid session cookie, then there's no # action necessary; the session is already established. if claims is not None: return fresh_cookie = firebase_auth.create_session_cookie( _get_id_token(request), feconf.FIREBASE_SESSION_COOKIE_MAX_AGE) response.set_cookie( constants.FIREBASE_AUTH_SESSION_COOKIE_NAME, value=fresh_cookie, max_age=feconf.FIREBASE_SESSION_COOKIE_MAX_AGE, overwrite=True, # Toggles https vs http. The production server uses https, but the local # developement server uses http. secure=(not constants.EMULATOR_MODE), # Using the HttpOnly flag when generating a cookie helps mitigate the # risk of client side script accessing the protected cookie (if the # browser supports it). # Learn more: https://owasp.org/www-community/HttpOnly. httponly=True)
def check_auth_time(id_token, flask): # [START check_auth_time] # To ensure that cookies are set only on recently signed in users, check auth_time in # ID token before creating a cookie. try: decoded_claims = auth.verify_id_token(id_token) # Only process if the user signed in within the last 5 minutes. if time.time() - decoded_claims['auth_time'] < 5 * 60: expires_in = datetime.timedelta(days=5) expires = datetime.datetime.now() + expires_in session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = flask.jsonify({'status': 'success'}) response.set_cookie('session', session_cookie, expires=expires, httponly=True, secure=True) return response # User did not sign in recently. To guard against ID token theft, require # re-authentication. return flask.abort(401, 'Recent sign in required') except ValueError: return flask.abort(401, 'Invalid ID token') except auth.AuthError: return flask.abort(401, 'Failed to create a session cookie')
def create_session_cookie(id_token, expires_in): try: session_claims = auth.create_session_cookie(id_token, expires_in) except ValueError: raise exceptions.AuthenticationFailed('Invalid Cookie Parameters') except FirebaseError: raise exceptions.AuthenticationFailed('Firebase error while creating cookie') return session_claims
def test_valid_args(self, user_mgt_app, expires_in): _, recorder = _instrument_user_manager(user_mgt_app, 200, '{"sessionCookie": "cookie"}') cookie = auth.create_session_cookie('id_token', expires_in=expires_in, app=user_mgt_app) assert cookie == 'cookie' request = json.loads(recorder[0].body.decode()) assert request == {'idToken': 'id_token', 'validDuration': 3600}
def validate_session(request, id_token): # Calculate the session cookie expiration time relative to now. expires_in = timedelta(seconds=settings.SESSION_COOKIE_AGE) # Create a session cookie using the ID token. session_cookie = FirebaseAuth.create_session_cookie(id_token, expires_in) # Set the session cookies. request.session[SESSION_COOKIE] = session_cookie request.session[SESSION_COOKIE_LASTCHECKED] = time()
def create_session_cookie(id_token: str, expires_in: timedelta = None) -> bytes: """Create a session cookie. Args: id_token (str): A user ID token passed from the client. expires_in (timedelta): The time until the session will expire. Returns: (bytes): A session cookie in bytes. """ if expires_in is None: expires_in = timedelta(days=7) return auth.create_session_cookie(id_token, expires_in=expires_in)
def session_login(): debug(f'[session_login - INFO]: Starting.') # Get the ID token sent by the client id_token = request.json['idToken'] # Set session expiration to 5 days. expires_in = datetime.timedelta(days=14) session_cookie = auth.create_session_cookie(id_token, app=auth_app, expires_in=expires_in) response = jsonify({'status': 'success', 'token': session_cookie}) return response
def create_session_cookie(self, id_token, expires_in): try: # Create the session cookie. This will also verify the ID token in the process. # The session cookie will have the same claims as the ID token. session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) return session_cookie except Exception as e: # Possible Exceptions: # - ValueError - If input parameters are invlaid # - FirebseError - If an error occurs while creating a session cookie print(e) raise e
def test_session_cookies(api_key): dev_claims = {'premium' : True, 'subscription' : 'silver'} custom_token = auth.create_custom_token('user3', dev_claims) id_token = _sign_in(custom_token, api_key) expires_in = datetime.timedelta(days=1) session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) claims = auth.verify_session_cookie(session_cookie) assert claims['uid'] == 'user3' assert claims['premium'] is True assert claims['subscription'] == 'silver' assert claims['iss'].startswith('https://session.firebase.google.com') estimated_exp = int(time.time() + expires_in.total_seconds()) assert abs(claims['exp'] - estimated_exp) < 5
def login(request, id_token): """ Login the user and create session for the logged user. Keep user data in sessions """ if not id_token: return try: decoded_token = auth.verify_id_token(id_token, check_revoked=True) except (auth.RevokedIdTokenError, auth.InvalidIdTokenError): return if not decoded_token.get('email_verified'): logger.debug("login: email not verified.") raise AuthenticationError("email not verified") if FIREBASE_USER in request.session: if request.session[FIREBASE_USER]['uid'] != decoded_token['uid']: # avoid reusing another user session request.session.flush() else: request.session.cycle_key() logger.debug("login: check session completed") # session validity is set to id token validity, so that cloud function # calls wont due to authentication (401 error) session_cookies = auth.create_session_cookie( id_token, expires_in=datetime.timedelta(hours=1)) logger.debug("login: cookie created") request.session[FIREBASE_SESSION_COOKIES] = session_cookies request.session[USER_TOKEN] = id_token update_user_attr(request, decoded_token) profile_doc = firestore_db.collection(u'users').document( decoded_token['uid']) logger.debug("login: Get profile doc") # no uids in log profile = wait_for_doc(profile_doc).to_dict() logger.debug("login: Got profile data") request.session[FIREBASE_USER].update(profile) request.session.modified = True rotate_token(request) user = User() user.set_attributes(request.session[FIREBASE_USER]) request.user = user
def user_register(): if (request.method == "POST"): user_name = request.form['userName'] user_email = request.form['userEmail'] user_password = request.form['userPassword'] flash_msg = None try: user_recode = user_auth.create_user_with_email_password( user_email, user_password) # get idToken user_id_token = user_recode.get('idToken') # get a session cookie using id token and set it in sessions # this will automatically create secure cookies under the hood user_session_cookie = auth.create_session_cookie( user_id_token, expires_in=datetime.timedelta(days=14)) session['session_id'] = user_session_cookie # add user document to users collection session["id"] = user_recode.get('localId') users_coll.add( { "name": user_name, "email": user_email, "model_desc": '', "saved_tweets": [], "model_file": { "model_id": 0, "model_name": '' } }, user_recode.get('localId')) session["status"] = "Success" # if registration is valid then redirect to index page return redirect(url_for('index_page')) except requests.HTTPError as e: if ("EMAIL_EXISTS" in str(e)): flash_msg = "You have already registerd! Please log in." elif ("INVALID_EMAIL" in str(e)): flash_msg = "Please enter a valid email address" elif ("WEAK_PASSWORD" in str(e)): flash_msg = "Please use a strong password" else: flash_msg = "Something is wrong!!" + str(e) session["status"] = flash_msg #+str(e) return render_template('sign-up-img.html', status=session["status"]) # return to login page for GET return render_template('sign-up-img.html')
def session_login(): id_token = request.headers.get("Authorization") expires_in = datetime.timedelta(days=5) try: # Create the session cookie. This will also verify the ID token in the process. # The session cookie will have the same claims as the ID token. session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in) response = jsonify({'status': 'success'}) # Set cookie policy for session cookie. expires = datetime.datetime.now() + expires_in response.set_cookie( 'session', session_cookie, expires=expires, secure=True) resp = make_response(render_template("analysis.html")) resp.set_cookie('session', session_cookie) return resp except: return abort(401, 'Failed to create a session cookie')
def test_verify_session_cookie_disabled(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)) # Disable the user record. auth.update_user(new_user.uid, disabled=True) # Verify the session cookie without checking revocation. This should # not raise. claims = auth.verify_session_cookie(session_cookie, check_revoked=False) assert claims['sub'] == new_user.uid # Verify the session cookie while checking revocation. This should # raise an exception. with pytest.raises(auth.UserDisabledError) as excinfo: auth.verify_session_cookie(session_cookie, check_revoked=True) assert str(excinfo.value) == 'The user record is disabled.'