Skip to content

Commit

Permalink
users(views): register/login views com social auth
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusvrs committed Oct 13, 2023
1 parent 0e20355 commit 6e376dd
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions api/users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from rest_framework import status
from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from users.backends.utils import get_backend
from users.simplejwt.decorators import move_refresh_token_to_cookie


class Register(TokenObtainPairView):

@move_refresh_token_to_cookie
def post(self, request: Request, *args, **kwargs) -> Response:
token = request.data.get('access_token')

backend = get_backend(kwargs['oauth2'])
if not backend:
return Response(
{
'errors': f'Invalid provider {kwargs["oauth2"]}'
}, status=status.HTTP_400_BAD_REQUEST)

user_data = backend.get_user_data(token)
if user_data:
user = backend.do_auth(user_data)

serializer = self.get_serializer()
refresh = serializer.get_token(user)
data = {
'access': str(refresh.access_token),
'refresh': str(refresh),
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
}

return Response(data, status.HTTP_200_OK)

return Response(
{
'errors': 'Invalid token'
}, status.HTTP_400_BAD_REQUEST)


class RefreshJWTView(TokenRefreshView):

@move_refresh_token_to_cookie
def post(self, request, *args, **kwargs):
try:
request.data['refresh'] = request.COOKIES['refresh']
except KeyError:
raise exceptions.NotAuthenticated('Refresh cookie error.')

return super().post(request, *args, **kwargs)

0 comments on commit 6e376dd

Please sign in to comment.