Django Assignment 1 | Westagram 11)

김기현·2022년 2월 26일
0
post-thumbnail

JWT Decorator 구현을 하였으니, 각 뷰에 적용할 차례입니다. 이제 각 뷰에 일일이 로그인 시 발행한 토큰을 확인하는 코드를 작성할 필요가 없어집니다!

JWT Decorator 적용

Decorator란 사전적 의미로는 “장식가” 또는 “인테리어 디자이너” 등의 의미를 가지고 있습니다. 이름 그대로, 자신의 방을 벽지나 커튼으로 장식을 하듯이, 기존의 코드에 여러가지 기능을 추가하는 파이썬 구문입니다.

로그인 인증 데코레이터 만들기

사용자의 토큰을 확인하기 위한 로그인 인증 데코레이터는 해당 함수 위에 붙여 사용합니다.

  • PostingView
# postings/view
.
.
.
from users.utils import login_decorator

class PostingView(View):
    @login_decorator
    # 로그인 데코레이터를 가져옵니다.
    def post(self, request):
        try:
            data         = json.loads(request.body)
            post_title   = data["post_title"]
            post_content = data["post_content"]
            user         = request.user
            # 토큰을 확인하는 HTTP request에는 토큰을 제외하고 사용자의 정보가 겂기에 'user'값을 저장해 활용

            
            Post.objects.create(
                post_title   = post_title,
                post_content = post_content,
                image_url    = data["image_url"],
                user_id      = user.id
                # id로 값을 보내기 위해 유저의 아이디로 인스턴스 비교 
            )

            return JsonResponse({"MESSAGE": "Post created!"}, status=201)
        
        except KeyError:
            return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)

이제는 token과 payload가 데코레이터로 이동했기 때문에 삭제합니다.

Post를 만들 때 user_id = user로 보내면 지정된 조회 매개 변수와 일치하는 인스턴스가 없기 때문에 TypeError를 내뱉습니다. 따라서 user_id = user.id로 수정합니다.

  • CommentView
# postings/view
.
.
.
class CommentView(View):
    @login_decorator
    def post(self, request):
        try:
            data    = json.loads(request.body)
            comment = data['comment']
            post_id = data['post_id']
            user    = request.user


            if not User.objects.filter(id = user.id).exists():
                return JsonResponse({'MESSAGE': "User Does Not Exist"}, status=404)

            if not Post.objects.filter(id = post_id).exists(): 
                return JsonResponse({'MESSAGE': "Posting Does Not Exist"}, status=404)
            
            Comment.objects.create(
                comment = comment,
                user_id = user.id,
                post_id = post_id,
            )

            return JsonResponse({"MESSAGE": "Comment created!"}, status=201)
   
        except KeyError:
            return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)

포스팅뷰 때와 마찬가지로 token과 payload가 데코레이터로 이동했기 때문에 삭제합니다.

토큰 정보를 확인하는 HTTP Request에는 토큰을 제외하고는 사용자 정보가 들어오지 않기 때문이며,user값을 request.user에 저장해서 이후 활용합니다.

user_id = payload['user_id']의 변수에서 payload 또한 데코레이터로 이동하기 때문에 user_id = user.id로 변수를 변경합니다.

  • LikeView
# postings/view
.
.
.
class LikeView(View):
    @login_decorator
    def post(self, request):
        try:        
            data    = json.loads(request.body)
            post_id = data['post_id'] 
            user    = request.user

            if not User.objects.filter(id = user.id).exists():
                return JsonResponse({'MESSAGE': "User Does Not Exist"}, status=404)    
            
            if not Post.objects.filter(id = post_id).exists():
                return JsonResponse({'MESSAGE': "Post Does Not Exist"}, status=404)    
            
            if Like.objects.filter(user = user.id, post=post_id).exists():
                return JsonResponse({'MESSAGE': "Already Liked Post"}, status=404)    
            

            Like.objects.create(
                user_id = user.id,
                post_id = post_id,
            )
            return JsonResponse({'messasge':'SUCCESS'}, status=201) 

        except KeyError:
            return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)

포스팅뷰 때와 마찬가지로 token과 payload가 데코레이터로 이동했기 때문에 삭제합니다.
user_id = payload['user_id']는 데코레이터로 갔으니 user = request.user로 변수로 저장해 사용하고 사용자의 id로 값을 넣기 위해 user.id로 바꿔줍니다.

Tada~

  • FollowView
# users/views
class FollowView(View):
    @login_decorator
    def post(self, request):
        data = json.loads(request.body)
        user = request.user

        try:
            followeduser = data['followeduser_id']
            followuser = user

            try:
                get_follow    = Follow.objects.get(followeduser_id = followeduser)
                get_following = Follow.objects.get(followuser_id = followuser)

                if get_follow.id == get_following.id:
                    get_follow.delete()
                    return JsonResponse({"message" : "delete LIKE SUCCESS"}, status = 201)
            except:
                pass

            if followeduser == '' and followuser == '':
                return JsonResponse({"message" : "Please type id"}, status = 400)

            if Follow.objects.filter(followuser_id = followuser, followeduser_id = followeduser).exists():
                return JsonResponse({'message' : 'You have already followed'},status=401) 
      
            else:
                Follow.objects.create(
                    followuser   = followuser,
                    followeduser_id = followeduser,
                )
                return JsonResponse({"message" : "SUCCESS"}, status = 201)       


        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'},status=400)

followuser = request.user로 변수를 지정하고 create할 때 해당의 변수를 사용합니다.

JjaZhaan~

profile
피자, 코드, 커피를 사랑하는 피코커

0개의 댓글