From d11a65eeb8383ac7e9cbcb9a8945ce963cad4aa0 Mon Sep 17 00:00:00 2001 From: Raphael Odini Date: Sun, 22 Sep 2024 23:36:01 +0200 Subject: [PATCH] refactor(users): update is_moderator in login --- open_prices/api/auth/views.py | 5 ++++- open_prices/common/openfoodfacts.py | 6 ++++++ open_prices/users/utils.py | 10 ++++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/open_prices/api/auth/views.py b/open_prices/api/auth/views.py index 81c2ae67..19f7f8e2 100644 --- a/open_prices/api/auth/views.py +++ b/open_prices/api/auth/views.py @@ -57,8 +57,11 @@ def post(self, request: Request) -> Response: # fetch the user_id from the response # We also need to lowercase the user_id as it's case-insensitive user_id = response.json()["user_id"].lower().strip() + is_moderator = response.json()["user"]["moderator"] == 1 token = create_token(user_id) - get_or_create_session(user_id=user_id, token=token) + get_or_create_session( + user_id=user_id, token=token, is_moderator=is_moderator + ) # set the cookie if requested response = Response({"access_token": token, "token_type": "bearer"}) if request.GET.get("set_cookie") == "1": diff --git a/open_prices/common/openfoodfacts.py b/open_prices/common/openfoodfacts.py index 05fed4aa..ee4981d6 100644 --- a/open_prices/common/openfoodfacts.py +++ b/open_prices/common/openfoodfacts.py @@ -35,6 +35,12 @@ def authenticate(username, password): + """ + Request: POST with form data + Response: + - 200: {"status":1,"status_verbose":"user signed-in","user":{"admin":0,"cc":"fr","country":"en:france","moderator":1,"name":"Prenom","preferred_language":"fr"},"user_id":"username"} # noqa + - 403: {"status": 0,"status_verbose": "user not signed-in"} + """ data = {"user_id": username, "password": password, "body": 1} return requests.post(f"{settings.OAUTH2_SERVER_URL}", data=data) diff --git a/open_prices/users/utils.py b/open_prices/users/utils.py index e90f5ac5..daffc236 100644 --- a/open_prices/users/utils.py +++ b/open_prices/users/utils.py @@ -3,8 +3,14 @@ from open_prices.users.models import Session, User -def get_or_create_session(user_id: str, token: str): - user, user_created = User.objects.get_or_create(user_id=user_id) +def get_or_create_session(user_id: str, token: str, is_moderator=False): + user, user_created = User.objects.get_or_create( + user_id=user_id, defaults={"is_moderator": is_moderator} + ) + # update is_moderator if it has changed + if not user_created and user.is_moderator != is_moderator: + user.is_moderator = is_moderator + user.save() session, session_created = Session.objects.get_or_create(user=user, token=token) session.last_used = timezone.now() session.save()