-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
users(views): register/login views com social auth
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |