Skip to content

Commit

Permalink
post_comment using token
Browse files Browse the repository at this point in the history
  • Loading branch information
GrGLeo committed Oct 29, 2024
1 parent f366ad2 commit 6a0abcd
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 26 deletions.
1 change: 0 additions & 1 deletion back/api_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ class UserModel(BaseModel):

class CommentModel(BaseModel):
activity_id: int
user_id: int
comment_text: str


Expand Down
6 changes: 3 additions & 3 deletions back/data/etl/comment_feeder.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@


class CommentFeeder(Feeder):
def __init__(self, comment: CommentModel):
self.user_id = comment.user_id
def __init__(self, comment: CommentModel, user_id: int):
self.user_id = user_id
self.text = comment.comment_text
self.schema = 'param'
super().__init__({}, comment.activity_id)
Expand All @@ -16,7 +16,7 @@ def process(self):
data = {
'comment': sanitized_comment
}
self.tables_processed = {'comment': pd.DataFrame([data])}
self.tables_processed = {'activity_comments': pd.DataFrame([data])}

def _sanitize_comment(self, text):
return bleach.clean(text)
10 changes: 9 additions & 1 deletion back/endpoints/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,17 @@ def create_jwt(data: dict, expire: timedelta = timedelta(hours=1)):
return jwt.encode(data, SECRET, algorithm=ALGORITHM)


def decode_jwt(token: str):
def decode_jwt(token: str) -> int:
if len(token.split(".")) != 3:
raise HTTPException(status_code=401, detail="Invalid JWT token structure")

payload = jwt.decode(token, SECRET, [ALGORITHM])
return payload["user_id"]


def retrieve_user_id(authorization: str) -> int:
if authorization is None:
raise HTTPException(status_code=401, detail="Missing authorization header")

token = authorization.split(" ")[1]
return decode_jwt(token)
27 changes: 27 additions & 0 deletions back/endpoints/comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from fastapi import APIRouter, HTTPException, Header
from back.api_model import CommentModel
from back.endpoints.auth import retrieve_user_id
from back.utils.logger import logger
from back.data.etl.comment_feeder import CommentFeeder


comment_router = APIRouter(prefix="/comments")


@comment_router.post("/post_comment/")
async def post_comment(comment: CommentModel, authorization: str = Header(None)):
user_id = retrieve_user_id(authorization)
if len(comment.comment_text.strip()) == 0:
logger.warning("Empty comment")
raise HTTPException(status_code=400, detail="Comment can not be empty")
try:
comment_feeder = CommentFeeder(comment, user_id)
comment_feeder.compute()
except Exception as e:
logger.error(e)
pass


@comment_router.get("/get_comment")
async def get_comment():
pass
19 changes: 2 additions & 17 deletions back/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,17 @@
from sqlalchemy import create_engine
from back.endpoints.auth import router, decode_jwt
from back.endpoints.db_query import db_router
from back.endpoints.comments import comment_router
from back.data.etl.running_feeder import RunningFeeder
from back.data.etl.comment_feeder import CommentFeeder
from back.data.etl.event_feeder import EventFeeder
from back.data.etl.cycling_feeder import CyclingFeeder
from back.data.etl.threshold_feeder import ThresholdFeeder
from back.data.etl.futur_wkt_feeder import FuturWorkoutFeeder
from back.data.tables import Base
from back.utils.data_handler import get_data
from back.utils.logger import logger
from back.fit.fit_writer import WorkoutWriter
from back.api_model import (
EventModel,
CommentModel,
ThresholdModel,
FuturWktModel
)
Expand All @@ -29,6 +27,7 @@
app = FastAPI()
app.include_router(router)
app.include_router(db_router)
app.include_router(comment_router)


@app.on_event("startup")
Expand Down Expand Up @@ -87,20 +86,6 @@ async def upload_file(
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail='An error occured while uploading activity')


@app.post("/post_comment")
async def post_comment(comment: CommentModel):
if len(comment.comment_text.strip()) == 0:
logger.warning("Empty comment")
raise HTTPException(status_code=400, detail="Comment can not be empty")

try:
comment_feeder = CommentFeeder(comment)
comment_feeder.compute()
except Exception as e:
logger.error(e)
pass


@app.post("/post_event")
async def post_event(event: EventModel, authorization: str = Header(None)):
if authorization is None:
Expand Down
9 changes: 5 additions & 4 deletions front/utilities/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,24 @@
@st.dialog('Add a comment')
def add_comment(activity_id):
comment = st.text_area("Write your comment here")
headers = {"Authorization": f"Bearer {st.session_state["user_token"]["access_token"]}"}

if st.button("Submit"):
json = {
"activity_id": activity_id,
"comment_text": comment,
"user_id": st.session_state['user_token']
}
response = requests.post(
f"{API}/post_comment",
json=json
f"{API}/comments/post_comment",
json=json,
headers=headers
)
if response.status_code != 200:
raise Exception(f'Error {response.status_code}')


def write_comment(conn, activity_id):
query = "select * from param.comment where activity_id = :activity_id"
query = "select * from param.activity_comments where activity_id = :activity_id"
comments = conn.query(query, params={'activity_id': activity_id})
comment_section = """
<div style='
Expand Down

0 comments on commit 6a0abcd

Please sign in to comment.