def categories():
    db_session = DBSession()
    categories = db_session.query(Category).all()
    new_items = db_session.query(Item).order_by(
        Item.timestamp.desc()
    ).limit(5).all()

    session_cookie = request.cookies.get('token')
    # Verify the session cookie. In this case an
    # additional check is added to detect if the
    # user's Firebase session was revoked, user
    # deleted/disabled, etc.
    try:
        auth.verify_session_cookie(
            session_cookie,
            check_revoked=True
        )
        return render_template('index.html', items=new_items, logged=True)
    except ValueError as e:
        # Session cookie is unavailable or invalid. Force user to login.
        print(e)
        return render_template('index.html', items=new_items, logged=False)
    except auth.AuthError as e:
        # Session revoked. Force user to login.
        print(e)
        return render_template('index.html', items=new_items, logged=False)
Beispiel #2
0
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_revoked_cookie_check_revoked(self, user_mgt_app, revoked_tokens, cookie):
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     _instrument_user_manager(user_mgt_app, 200, revoked_tokens)
     with pytest.raises(auth.AuthError) as excinfo:
         auth.verify_session_cookie(cookie, app=user_mgt_app, check_revoked=True)
     assert excinfo.value.code == 'SESSION_COOKIE_REVOKED'
     assert str(excinfo.value) == 'The Firebase session cookie has been revoked.'
 def test_certificate_request_failure(self, user_mgt_app):
     _overwrite_cert_request(user_mgt_app, testutils.MockRequest(404, 'not found'))
     with pytest.raises(auth.CertificateFetchError) as excinfo:
         auth.verify_session_cookie(TEST_SESSION_COOKIE, app=user_mgt_app)
     assert 'Could not fetch certificates' in str(excinfo.value)
     assert isinstance(excinfo.value, exceptions.UnknownError)
     assert excinfo.value.cause is not None
     assert excinfo.value.http_response is None
    def test_verify_session_cookie_timeout(self, options, timeout):
        app = firebase_admin.initialize_app(MOCK_CREDENTIAL, options=options)
        recorder = self._instrument_session(app)

        auth.verify_session_cookie(TEST_SESSION_COOKIE)

        assert len(recorder) == 1
        assert recorder[0]._extra_kwargs['timeout'] == timeout
 def test_expired_cookie(self, user_mgt_app):
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     cookie = self.invalid_cookies['ExpiredCookie']
     with pytest.raises(auth.ExpiredSessionCookieError) as excinfo:
         auth.verify_session_cookie(cookie, app=user_mgt_app)
     assert isinstance(excinfo.value, auth.InvalidSessionCookieError)
     assert 'Token expired' in str(excinfo.value)
     assert excinfo.value.cause is not None
     assert excinfo.value.http_response is None
Beispiel #7
0
 def test_check_disabled_before_revoked(self, user_mgt_app,
                                        user_disabled_and_revoked, cookie):
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     _instrument_user_manager(user_mgt_app, 200, user_disabled_and_revoked)
     with pytest.raises(auth.UserDisabledError) as excinfo:
         auth.verify_session_cookie(cookie,
                                    app=user_mgt_app,
                                    check_revoked=True)
     assert str(excinfo.value) == 'The user record is disabled.'
Beispiel #8
0
def index():
    session_cookie = request.cookies.get('session')
    if not session_cookie:
        return redirect('/login')
    try:
        auth.verify_session_cookie(session_cookie, check_revoked=True)
        return 'Index Page'
    except auth.InvalidSessionCookieError:
        return redirect('/login')
Beispiel #9
0
def verify_session_token(request):
    try:
        idToken = extract_bearer_token(request)
        return auth.verify_session_cookie(idToken, check_revoked=True)
    except:
        try:
            cookie = request.cookies.get("accessToken")
            return auth.verify_session_cookie(cookie, check_revoked=True)
        except:
            raise BaseException("Invalid access Token")
 def test_invalid_cookie(self, user_mgt_app, cookie_key):
     cookie = self.invalid_cookies[cookie_key]
     if _is_emulated() and cookie_key in self.cookies_accepted_in_emulator:
         self._assert_valid_cookie(cookie, user_mgt_app)
         return
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     with pytest.raises(auth.InvalidSessionCookieError) as excinfo:
         auth.verify_session_cookie(cookie, app=user_mgt_app)
     assert isinstance(excinfo.value, exceptions.InvalidArgumentError)
     assert excinfo.value.http_response is None
 def decorated_function(*args, **kwargs):
     print('in decorator')
     session_cookie = request.cookies.get('firebase')
     if not session_cookie:
         # Session cookie is unavailable. Force user to login.
         return redirect(url_for('auth.login', next=request.url))
     try:
         # Verify the session cookie. In this case an additional check is added to detect
         # if the user's Firebase session was revoked, user deleted/disabled, etc.
         auth.verify_session_cookie(session_cookie, check_revoked=True)
         return f(*args, **kwargs)
     except auth.InvalidSessionCookieError:
         # Session cookie is invalid, expired or revoked. Force user to login.
         return redirect(url_for('auth.login', next=request.url))
def _get_auth_claims_from_session_cookie(cookie):
    """Returns claims from the session cookie, or None if invalid.

    Args:
        cookie: str|None. The session cookie to extract claims from.

    Returns:
        AuthClaims|None. The claims from the session cookie, if available.
        Otherwise returns None.
    """
    # It's OK for a session cookie to be None, it just means that the request
    # isn't authenticated.
    if cookie:
        try:
            with _firebase_admin_context():
                return _create_auth_claims(
                    firebase_auth.verify_session_cookie(cookie))
        # NOTE: Session cookies only provide temporary authentication, so they
        # are expected to become obsolete over time. The following errors are
        # situations where this can happen.
        except (firebase_auth.ExpiredSessionCookieError,
                firebase_auth.RevokedSessionCookieError):
            # NOTE: logging.exception appends the stack trace automatically.
            logging.exception('User session has ended and must be renewed')
    return None
def login_checker():
    # user的資料
    auth_user = {
        'is_login': False,
        # 設計一個權限概念
        'is_admin': False,
        'user': {}
    }
    # 取得session_cookie
    session_cookie = request.cookies.get(cookie_name)
    # 驗證session_cookie
    try:
        # 透過session_cookie取得user的資料
        user = auth.verify_session_cookie(session_cookie)
        # 設定為登入狀態
        auth_user['is_login'] = True
        auth_user['user'] = user
        # 取回文件 admins/{EMAIL},即使文件不存在還是會要回一個空字串
        admin_doc = db.document(f'admins/{user["email"]}').get()
        # 檢查文件是否存在
        if admin_doc.exists:
            # 設定此人是管理者
            auth_user['is_admin'] = True
    except:
        print("驗證失敗")
    # 回傳auth_user給每一個模板
    return dict(auth_user=auth_user)  # dict是context_processor的特別規定
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 editItem(item_id):
    session_cookie = request.cookies.get('token')
    decoded_claims = auth.verify_session_cookie(session_cookie,
                                                check_revoked=True)

    db_session = DBSession()
    item = db_session.query(Item).get(item_id)
    if item.sub != decoded_claims['uid']:
        return abort(401, 'Insufficient permissions')

    categories = db_session.query(Category).all()
    if request.method == 'GET':
        return render_template('edit_item.html', categories=categories,
                               item=item, logged=True)
    else:
        category_id = request.form['category']
        category = db_session.query(Category).get(category_id)

        item.name = request.form['name']
        item.description = request.form['description']
        item.price = request.form['price']
        item.image = request.form['image']
        item.category = category
        db_session.add(item)
        db_session.commit()
        flash("Item updated correctly!")
        return redirect(url_for('item', item_id=item_id))
def newItem():
    session_cookie = request.cookies.get('token')
    decoded_claims = auth.verify_session_cookie(session_cookie,
                                                check_revoked=True)

    db_session = DBSession()
    categories = db_session.query(Category).all()
    new_items = db_session.query(Item).order_by(
        Item.timestamp.desc()
    ).limit(5).all()
    if request.method == 'GET':
        return render_template('new_item.html', items=new_items,
                               logged=True)
    else:
        category_id = request.form['category']
        category = db_session.query(Category).get(category_id)
        newItem = Item(
            name=request.form['name'],
            description=request.form['description'],
            price=request.form['price'],
            image=request.form['image'],
            category=category,
            sub=decoded_claims['uid']
        )
        db_session.add(newItem)
        db_session.commit()
        flash("New Item created!")
        return redirect(url_for('item', item_id=newItem.id))
Beispiel #17
0
def index_page():
    flash_msg = None
    if ("session_id" in session):
        try:
            # verify session_id
            decoded_clamis = auth.verify_session_cookie(session["session_id"])
            #flash(decoded_clamis)
            session['email_addr'] = decoded_clamis['email']
            session['user_id'] = decoded_clamis['user_id']
            #
            # Trying to implement users connected chats list
            #
            user_doc = users_coll.document(decoded_clamis['user_id'])
            user_details = user_doc.get().to_dict()
            connected_chats = user_details.get("connected_chats")
            #flash(decoded_clamis)
            connected_chats_list = []
            for i in connected_chats:
                connected_chats_list.append(i.get().to_dict())
            return render_template("index.html",
                                   user_name=user_details.get('name'),
                                   chats_list=connected_chats_list[::-1])
        except Exception as e:
            # if unable to verify session_id for any reason
            # maybe invalid or expired, redirect to login
            flash_msg = "Your session is expired!"
            flash(flash_msg)
            return redirect(url_for("user_login"))
    return redirect(url_for("user_login"))
def _get_auth_claims_from_session_cookie(
        cookie: Optional[str]) -> Optional[auth_domain.AuthClaims]:
    """Returns claims from the session cookie, or None if invalid.

    Args:
        cookie: str|None. The session cookie to extract claims from.

    Returns:
        AuthClaims|None. The claims from the session cookie, if available.
        Otherwise returns None.

    Raises:
        InvalidAuthSessionError. The cookie has an invalid value.
        StaleAuthSessionError. The cookie has lost its authority.
    """
    # It's OK for a session cookie to be None or empty, it just means that the
    # request hasn't been authenticated.
    if not cookie:
        return None
    try:
        claims = firebase_auth.verify_session_cookie(cookie,
                                                     check_revoked=True)
    except firebase_auth.ExpiredSessionCookieError:
        raise auth_domain.StaleAuthSessionError('session has expired')
    except firebase_auth.RevokedSessionCookieError:
        raise auth_domain.StaleAuthSessionError('session has been revoked')
    except (firebase_exceptions.FirebaseError, ValueError) as error:
        raise auth_domain.InvalidAuthSessionError('session invalid: %s' %
                                                  error)
    else:
        return _create_auth_claims(claims)
Beispiel #19
0
def authCookies(request_data):
    session_cookie = ''
    user_id = None
    err = ''

    try:
        # Extract the firebase token from the HTTP header

        session_cookie = request.headers['Authorization'].replace(
            'Bearer ', '')
    except:
        err = f'No "session" cookie information given.'
        # else return an error
        return request_data, user_id, err

    # Verify the cookie while checking if the cookie is revoked by
    # passing check_revoked=True.
    try:
        # Validate the cookie
        decoded_cookie = auth.verify_session_cookie(session_cookie,
                                                    app=auth_app,
                                                    check_revoked=True)
        # Token is valid and not revoked.
        user_id = decoded_cookie['uid']
        request_data['userID'] = user_id
    except Exception as e:
        err = f'Unable to authenticate the user, err = {e}'

    # else return an error
    return request_data, user_id, err
Beispiel #20
0
def get_token_from_context(ctx):
    try:
        token = auth.verify_session_cookie(ctx.cookies.get('session'),
                                           check_revoked=True)
        return token
    except Exception:
        return None
Beispiel #21
0
def checkPermission(request: Request) -> Dict[str, str]:
    token = _cookieValid(request)
    if not token:
        token = _authorizationHeader(request)
    try:
        return auth.verify_session_cookie(token)
    except Exception:
        raise BaseException("Invalid access Token")
Beispiel #22
0
 def decorated_function(*args, **kwargs):
     session_cookie = request.cookies.get('unique-key')
     try:
         g.user = auth.verify_session_cookie(session_cookie,
                                             check_revoked=True)
         return f(*args, **kwargs)
     except Exception as exp:
         return redirect('/login')
def get_user(request):
    """
    Return the firebase user instance associated with the given request session.
    If no user, return user with is_authenticated False
    """
    user = User()
    if FIREBASE_USER not in request.session:
        return user

    try:
        auth.verify_session_cookie(request.session[FIREBASE_SESSION_COOKIES],
                                   check_revoked=True)
        user.set_attributes(request.session[FIREBASE_USER])
    except auth.InvalidSessionCookieError:
        request.session.flush()

    return user
Beispiel #24
0
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.'
Beispiel #25
0
 def test_valid_cookie_check_revoked(self, user_mgt_app, cookie):
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     _instrument_user_manager(user_mgt_app, 200, MOCK_GET_USER_RESPONSE)
     claims = auth.verify_session_cookie(cookie,
                                         app=user_mgt_app,
                                         check_revoked=True)
     assert claims['admin'] is True
     assert claims['uid'] == claims['sub']
Beispiel #26
0
 def test_revoked_cookie_does_not_check_revoked(self, user_mgt_app,
                                                revoked_tokens, cookie):
     _overwrite_cert_request(user_mgt_app, MOCK_REQUEST)
     _instrument_user_manager(user_mgt_app, 200, revoked_tokens)
     claims = auth.verify_session_cookie(cookie,
                                         app=user_mgt_app,
                                         check_revoked=False)
     assert claims['admin'] is True
     assert claims['uid'] == claims['sub']
 def session_logout():
     session_cookie = flask.request.cookies.get('session')
     try:
         decoded_claims = auth.verify_session_cookie(session_cookie)
         auth.revoke_refresh_tokens(decoded_claims['sub'])
         response = flask.make_response(flask.redirect('/login'))
         response.set_cookie('session', expires=0)
         return response
     except ValueError:
         return flask.redirect('/login')
Beispiel #28
0
 def logout():
     oreo = request.cookies.get("uauuccu_oreo")
     try:
         profile = auth.verify_session_cookie(oreo)
         auth.revoke_refresh_tokens(profile["user_id"])
         print("[Logged out]")
     except Exception as e:
         print(e)
         print("[Failed to log out]")
     return redirect("/")
 def post(self):
     try:
         session_cookie = request.cookies.get('session')
         decoded_claims = auth.verify_session_cookie(session_cookie)
         auth.revoke_refresh_tokens(decoded_claims['sub'])
         response = jsonify({})
         response.set_cookie('session', expires=0)
         return response
     except:
         return {'message': 'Session lost, just logout'}
 def test_project_id_option(self):
     app = firebase_admin.initialize_app(
         testutils.MockCredential(), options={'projectId': 'mock-project-id'}, name='myApp')
     _overwrite_cert_request(app, MOCK_REQUEST)
     try:
         claims = auth.verify_session_cookie(TEST_SESSION_COOKIE, app=app)
         assert claims['admin'] is True
         assert claims['uid'] == claims['sub']
     finally:
         firebase_admin.delete_app(app)