Skip to content

Commit

Permalink
updates to JWT auth
Browse files Browse the repository at this point in the history
everytime a JWT is verified it now stores the users details in Users ORM, if user already exists, details are updated
  • Loading branch information
Taseen18 committed Mar 26, 2024
1 parent 775868e commit 910495b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
Binary file modified backend/to_do_list/__pycache__/authentication.cpython-311.pyc
Binary file not shown.
26 changes: 21 additions & 5 deletions backend/to_do_list/authentication.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# authentication.py in your Django app
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework import authentication, exceptions
Expand All @@ -15,11 +14,28 @@ def authenticate(self, request):
try:
payload = jwt.decode(token, settings.SUPABASE_SECRET_KEY, algorithms=['HS256'], audience='authenticated')
user_id = payload['sub']
user, created = User.objects.get_or_create(username=user_id, defaults={'first_name': 'SupabaseUser'})
email = payload.get('email', '')
first_name = payload.get('user_metadata', {}).get('first_name', '')
last_name = payload.get('user_metadata', {}).get('last_name', '')

# Check if the user exists and update/create accordingly
user, created = User.objects.get_or_create(username=user_id, defaults={
'first_name': first_name,
'last_name': last_name,
'email': email
})

# If the user was not created (i.e., it already exists), update its details
if not created:
user.first_name = first_name
user.last_name = last_name
user.email = email
user.save()

if created:
print("\nuser created")
print("\nNew user authenticated and created")
else:
print("\nuser authenticated")
print("User authenticated")

return (user, token)

Expand All @@ -28,4 +44,4 @@ def authenticate(self, request):
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed('Invalid token')
except Exception as e:
raise exceptions.AuthenticationFailed('Unexpected error during authentication', e)
raise exceptions.AuthenticationFailed(f'Unexpected error during authentication: {e}')

0 comments on commit 910495b

Please sign in to comment.