Skip to content

Commit

Permalink
Revert "feat: add sessions (#56)"
Browse files Browse the repository at this point in the history
This reverts commit 4f7fc0d.
  • Loading branch information
megasanjay authored Aug 1, 2024
1 parent 45e4f5c commit f78ff2e
Show file tree
Hide file tree
Showing 9 changed files with 45 additions and 280 deletions.
33 changes: 0 additions & 33 deletions alembic/versions/3ffefbd9c03b_email_verified_type.py

This file was deleted.

27 changes: 0 additions & 27 deletions alembic/versions/9698369d7a8c_create_session_table.py

This file was deleted.

68 changes: 19 additions & 49 deletions apis/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import uuid
from datetime import timezone
from typing import Any, Union
import time

import jwt
from email_validator import EmailNotValidError, validate_email
from flask import g, make_response, request
from flask_restx import Namespace, Resource, fields
from jsonschema import FormatChecker, ValidationError, validate

import model

api = Namespace("Authentication", description="Authentication paths", path="/")
Expand Down Expand Up @@ -233,37 +233,32 @@ def validate_is_valid_email(instance):
# If not testing, directly use the 'config' module
config = config_module

expired_in = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=180
)
jti = str(uuid.uuid4())
encoded_jwt_code = jwt.encode(
{
"user": user.id,
"exp": expired_in,
"jti": jti,

"exp": datetime.datetime.now(timezone.utc)
+ datetime.timedelta(minutes=180), # noqa: W503
"jti": str(uuid.uuid4()),
}, # noqa: W503
config.FAIRHUB_SECRET,
algorithm="HS256",
)

resp = make_response(user.to_dict())

resp.set_cookie(
"token", encoded_jwt_code, secure=True, httponly=True, samesite="None"
)
g.token = jti
added_session = model.Session.from_data(jti, expired_in.timestamp(), user)
model.db.session.add(added_session)
model.db.session.commit()
resp.status_code = 200

return resp


def authentication():
"""it authenticates users to a study, sets access and refresh token.
In addition, it handles error handling of expired token and non existed users"""
g.user = None
g.token = None

if "token" not in request.cookies:
return
token: str = (
Expand Down Expand Up @@ -291,20 +286,7 @@ def authentication():
token_blacklist = model.TokenBlacklist.query.get(decoded["jti"])
if token_blacklist:
return
# decode user
user = model.User.query.get(decoded["user"])
# decode session
session = model.Session.query.get(decoded["jti"])
if not session:
g.user = None
g.token = None
return

if session.expires_at < time.time():
g.user = None
g.token = None
return
g.token = decoded["jti"]
g.user = user


Expand Down Expand Up @@ -415,7 +397,6 @@ class Logout(Resource):
@api.response(400, "Validation Error")
def post(self):
"""simply logges out user from the system"""

resp = make_response()
resp.set_cookie(
"token",
Expand All @@ -426,16 +407,6 @@ def post(self):
expires=datetime.datetime.now(timezone.utc),
)
resp.status_code = 204

if g.user and g.token:
remove_session = (
model.Session.query
.filter(model.Session.id == g.token)
.first()
)
if remove_session:
model.db.session.delete(remove_session)
model.db.session.commit()
return resp


Expand Down Expand Up @@ -502,21 +473,20 @@ def confirm_new_password(instance):

data: Union[Any, dict] = request.json
user = model.User.query.get(g.user.id)

user.set_password(data["new_password"])

model.db.session.commit()
session_logout()
return "Password updated successfully", 200


def session_logout():
if g.user and g.token:
remove_sessions = model.Session.query.filter(
model.Session.user_id == g.user.id
).all()
# @api.route("/auth/current-users")
# class CurrentUsers(Resource):
# """function is used to see all logged users in
# the system. For now, it is used for testing purposes"""

for session in remove_sessions:
model.db.session.delete(session)
model.db.session.commit()
# return "Sessions are removed successfully", 200
# @api.response(200, "Success")
# @api.response(400, "Validation Error")
# def get(self):
# """returns all logged users in the system"""
# if not g.user:
# return None
# return g.user.to_dict()
48 changes: 20 additions & 28 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from growthbook import GrowthBook
from sqlalchemy import MetaData, inspect, text
from sqlalchemy import MetaData, inspect
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.schema import DropTable
from waitress import serve
Expand Down Expand Up @@ -77,8 +77,7 @@ def create_app(config_module=None, loglevel="INFO"):
caching.cache.init_app(app)

cors_origins = [
"https://brave-ground-.*-.*.centralus.2.azurestaticapps.net",
# noqa E501 # pylint: disable=line-too-long # pylint: disable=anomalous-backslash-in-string
"https://brave-ground-.*-.*.centralus.2.azurestaticapps.net", # noqa E501 # pylint: disable=line-too-long # pylint: disable=anomalous-backslash-in-string
"https://staging.app.fairhub.io",
"https://app.fairhub.io",
"https://staging.fairhub.io",
Expand Down Expand Up @@ -126,6 +125,16 @@ def create_schema():
with engine.begin():
model.db.create_all()

@app.cli.command("destroy-schema")
def destroy_schema():
"""Create the database schema."""
# If DB is Azure, Skip
if config.FAIRHUB_DATABASE_URL.find("azure") > -1:
return
engine = model.db.session.get_bind()
with engine.begin():
model.db.drop_all()

@app.cli.command("cycle-schema")
def cycle_schema():
"""Destroy then re-create the database schema."""
Expand All @@ -150,17 +159,6 @@ def list_schemas():
for schema_name in schema_names:
print(schema_name)

@app.cli.command("destroy-schema")
def destroy_schema():
"""Create the database schema."""
# If DB is Azure, Skip
if config.FAIRHUB_DATABASE_URL.find("azure") > -1:
return
engine = model.db.session.get_bind()
with engine.begin() as conn:
model.db.drop_all()
conn.execute(text("DROP TABLE IF EXISTS alembic_version")) # type: ignore

@app.cli.command("inspect-schema")
@click.argument("schema")
def inspect_schema(schema=None):
Expand Down Expand Up @@ -223,7 +221,7 @@ def on_after_request(resp):
if request.path.startswith(route):
return resp

if "token" not in request.cookies or not g.token:
if "token" not in request.cookies:
return resp

token: str = request.cookies.get("token") or "" # type: ignore
Expand Down Expand Up @@ -256,22 +254,15 @@ def on_after_request(resp):
if token_blacklist:
resp.delete_cookie("token")
return resp

expired_in = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=180
)
session = model.Session.query.get(g.token)
session_expires_at = datetime.datetime.fromtimestamp(session.expires_at, timezone.utc)

if expired_in - session_expires_at < datetime.timedelta(minutes=90):

new_token = jwt.encode(
{"user": decoded["user"], "exp": expired_in, "jti": decoded["jti"]},
config.FAIRHUB_SECRET,
algorithm="HS256",
)
resp.set_cookie("token", new_token, secure=True, httponly=True, samesite="None")
session.expires_at = expired_in.timestamp()
new_token = jwt.encode(
{"user": decoded["user"], "exp": expired_in, "jti": decoded["jti"]},
config.FAIRHUB_SECRET,
algorithm="HS256",
)
resp.set_cookie("token", new_token, secure=True, httponly=True, samesite="None")

app.logger.info("after request")
app.logger.info(request.headers.get("Origin"))
Expand All @@ -287,6 +278,7 @@ def on_after_request(resp):
# ] = "Content-Type, Authorization, Access-Control-Allow-Origin,
# Access-Control-Allow-Credentials"
app.logger.info(resp.headers)

return resp

@app.errorhandler(ValidationException)
Expand Down
2 changes: 0 additions & 2 deletions model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
from .user import User
from .user_details import UserDetails
from .version import Version
from .session import Session
from .version_readme import VersionReadme

__all__ = [
Expand Down Expand Up @@ -103,5 +102,4 @@
"UserDetails",
"Notification",
"VersionReadme",
"Session",
]
36 changes: 0 additions & 36 deletions model/session.py

This file was deleted.

1 change: 0 additions & 1 deletion model/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def __init__(self, password):
user_details = db.relationship("UserDetails", uselist=False, back_populates="user")
token_blacklist = db.relationship("TokenBlacklist", back_populates="user")
notification = db.relationship("Notification", back_populates="user")
session = db.relationship("Session", back_populates="user")

def to_dict(self):
return {
Expand Down
6 changes: 0 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,12 +307,6 @@ def clients(flask_app):
)
assert response.status_code == 200

meta = db.metadata
for table in reversed(meta.sorted_tables):
if table.name == 'session':
session_entries = db.session.execute(table.select()).fetchall()
assert len(session_entries) == 5

yield _logged_in_client, _admin_client, _editor_client, _viewer_client

ctx.pop()
Loading

0 comments on commit f78ff2e

Please sign in to comment.