Skip to content

Commit

Permalink
refactor(users): update is_moderator on login (#456)
Browse files Browse the repository at this point in the history
  • Loading branch information
raphodn authored Sep 22, 2024
1 parent c6122be commit 67caa6f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 4 additions & 1 deletion open_prices/api/auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
6 changes: 6 additions & 0 deletions open_prices/common/openfoodfacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
10 changes: 8 additions & 2 deletions open_prices/users/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 67caa6f

Please sign in to comment.