Python/DjangoDjango DRF Session 인증과 CSRF (3) - 로그인/로그아웃
https://cloud-dragon.tistory.com/3
Python/DjangoDjango DRF Session 인증과 CSRF (2) - 회원가입
https://cloud-dragon.tistory.com/2 Django DRF Session 인증과 CSRF (1) - project setting 회원에 대한 인증을 하는 방법에는 크게 Session과 JWT와 같은 토큰을 사용하는 방법이 존재한다. 이번 포스트에서는 Django Sessio
cloud-dragon.tistory.com
이전 포스트에 이어서 이번에는 로그인/로그아웃 기능을 구현해 본다.
로그인 뷰
로그인 기능은 django.auth에서 제공하는 authenticate, login 메서드를 사용할 것이다.
1. authenticate
- 코드(accounts/views.py)
from operator import itemgetter
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from user_profile.models import UserProfile
...
@method_decorator(csrf_protect, name='dispatch')
class LoginView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request):
data = self.request.data
username, password = itemgetter('username', 'password')(data)
try:
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return Response(data={"username": username}, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
except:
return Response(data={"error": "Something went wrong when login"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
authentication
user = auth.authenticate(username=username, password=password)
request body의 username, password를 꺼낸 뒤 authenticate 메서드의 인자로 넘겨준다.
authenticate 메서드는 username, password를 이용하여 DB에 해당 정보의 유저가 있는지 확인 후 있다면 user 객체를 생성하여 return 한다. 만약 username 또는 password가 일치하지 않을 경우 None을 return 한다.
2. login
if user is not None:
auth.login(request, user)
return Response(data={"username": username}, status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_404_NOT_FOUND)
authentication이 정상적으로 이루어졌다면 login 메서드를 호출한다. 인자로는 request 객체와 user 객체를 넘겨준다. login 메서드는 username, password를 Django의 session에 저장한다.(즉 DB에 세션을 생성해 준다)
로그아웃 뷰
로그아웃 역시 마찬가지로 django.auth 에서 제공하는 logout 메서드를 사용할 것이다.
- 코드 (accounts/views.py)
from operator import itemgetter
from django.contrib import auth
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from user_profile.models import UserProfile
...
class LogoutView(APIView):
def post(self, request):
try:
auth.logout(request)
return Response(status=status.HTTP_200_OK)
except:
return Response({'error': 'something went wrong when logging out'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
로그아웃의 경우 간단하다 request 객체를 logout 메서드의 인자로 넘겨주기만 하면 된다.
logout 메서드는 request 객체가 가지고 있는 sessionid를 통해 기존에 세션에 저장된 데이터는 완전히 지워준다.
[github 주소] https://github.com/yongun2/Django-Session-Authentication-And-CSRF
yongun2/Django-Session-Authentication-And-CSRF
Contribute to yongun2/Django-Session-Authentication-And-CSRF development by creating an account on GitHub.
github.com
오류 또는 잘못된 점이 있다면 댓글에 남겨주세요 매우 감사합니다.