Chomu's Blog.

>

Posts

GitHub

11월 04일 원티드 프리온보딩 백엔드 10일차 TIL

목차

:one: 진행상황

:two: 진행상황리뷰

# views.py
...
from rest_framework_simplejwt.tokens import RefreshToken
...
class LoginView(APIView):
    def post(self, request: Request) -> Response:
...
        token: Final[RefreshToken] = RefreshToken.for_user(user)
        refresh: Final[RefreshToken] = str(token)
        access: Final = str(token.access_token)
        response = Response({"user": user.id})
        response.set_cookie(key="refresh", value=refresh, httponly=True)
        response.set_cookie(key="access", value=access, httponly=True)
        return response
 
class LogoutView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
 
    def post(self, request: Request) -> Response:
        ...
        # get token from request cookie
        refresh: Final = request.data.get("refresh")
        ...
        try:
            # delete token from database
            token: Final = RefreshToken(refresh)
            token.blacklist()
        except Exception:
            raise ParseError("Refresh token is invalid.")
        # delete token from cookie
        response = Response({"status": True})
        response.delete_cookie("refresh")
        response.delete_cookie("access")
        return response
 
# tests.py
class TestUserView(APITestCase):
    ...
    def test_logout(self):
    ...
        # get tokens
        refresh = logged_response.cookies["refresh"].value
        access = logged_response.cookies["access"].value
        # request logout with tokens
        response: Final[Response] = self.client.post(
            "/api/v1/users/logout/",
            {"refresh": refresh},
            HTTP_AUTHORIZATION=f"Bearer {access}",
        )

:three: Today I Learned

JWT

djangorestframework-simplejwt