<login_decorator 추가>
1. utils.py에 login_decorator 함수 정의
import jwt
from functools import wraps
from django.http import JsonResponse
from users.models import User
from my_settings import SECRET_KEY, ALGORITHM
def login_decorator(func):
@wraps(func)
def wrapper(self, request, *args, **kwargs):
try:
access_token = request.headers.get('Authorization', None)
payload = jwt.decode(access_token, SECRET_KEY, ALGORITHM)
user = User.objects.get(id = payload['id'])
request.user = user
except jwt.exceptions.DecodeError:
return JsonResponse({'message' : 'INVALID_TOKEN'}, status = 400)
except User.DoesNotExist:
return JsonResponse({'message' : 'INVALID_USER'}, status = 400)
return func(self, request, *args, **kwargs)
return wrapper
2. 게시물, 게시물 댓글, 좋아요 등록시 login_decorator를 사용하여 user_id확인
import json
from django.http import JsonResponse
from django.views import View
from users.models import User
from postings.models import Posting, Comment, Like
from users.utils import login_decorator
class PostingView(View):
@login_decorator
def post(self, request):
data = json.loads(request.body)
try:
user_id = request.user.id
img_url = data['img_url']
content = data['content']
Posting.objects.create(
user = User.objects.get(id = user_id),
img_url = img_url,
content = content
)
return JsonResponse({'message':'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
@login_decorator
def get(self, request):
postings = Posting.objects.all()
results = []
for posting in postings:
results.append(
{
"user" : User.objects.get(id = posting.user_id).username,
"img_url" : posting.img_url,
"content" : posting.content,
"created_at" : posting.created_at
}
)
return JsonResponse({'resutls':results}, status=200)
class CommentView(View):
@login_decorator
def post(self, request):
data = json.loads(request.body)
try:
user_id = request.user.id
post_id = data['post_id']
content = data['content']
if not Posting.objects.filter(id = post_id).exists():
return JsonResponse({'message': "Posting Does Not Exist"}, status=404)
Comment.objects.create(
user_id = user_id,
post_id = post_id,
content = content
)
return JsonResponse({'message':'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'},status=400)
@login_decorator
def get(self, request):
comments = Comment.objects.all()
results = []
for comment in comments:
results.append(
{
"user" : User.objects.get(id = comment.user_id).username,
"posting_id" : Posting.objects.get(id = comment.post_id).id,
"content" : comment.content,
"created_at" : comment.created_at
}
)
return JsonResponse({'resutls':results}, status=200)
class LikeView(View):
@login_decorator
def post(self, request):
data = json.loads(request.body)
try:
user_id = request.user.id
post_id = data['post_id']
if not Posting.objects.filter(id = post_id).exists():
return JsonResponse({'message': "Posting Does Not Exist"}, status=404)
if Like.objects.filter(user = user_id, post = post_id).exists():
return JsonResponse({'message': "You've already pressed like"}, status=404)
Like.objects.create(
user_id = user_id,
post_id = post_id
)
return JsonResponse({'message':'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'},status=400)
3. 다른 계정 follow시 login_decorator를 사용하여 user_id확인
class FollowView(View):
@login_decorator
def post(self, request):
data = json.loads(request.body)
try:
followuser_id = request.user.id
followeduser_id = data['followeduser_id']
if followeduser_id == followuser_id:
return JsonResponse({'message' : 'It is the same user'},status=401)
if not User.objects.filter(id = followeduser_id).exists():
return JsonResponse({'message' : 'Followeduser Does Not Exist'},status=401)
if Follow.objects.filter(followuser_id = followuser_id, followeduser_id = followeduser_id).exists():
return JsonResponse({'message' : 'You have already followed'},status=401)
Follow.objects.create(
followuser_id = followuser_id,
followeduser_id = followeduser_id
)
return JsonResponse({'message':'SUCCESS'}, status=201)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'},status=400)
login_decorator
를 사용하여 존재하는 user임을 확인했으므로 user가 존재하는지 확인하지 않아도 된다!
http -v POST http://127.0.0.1:8080/postings/like
Authorization:"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mjl9.bJprZGfkw42uJfQ0JOn9tlie7RYo3g35KTQnLf4xWfk"
post_id=4
:
HTTP 헤더에 보낼 정보
-> access_token
을 헤더에 넣어서 보낸 후 로그인한 user인지 login_decorator
로 확인한다.
http -v POST http://127.0.0.1:8080/users/follow
Authorization:"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mjl9.bJprZGfkw42uJfQ0JOn9tlie7RYo3g35KTQnLf4xWfk"
followeduser_id:=29
:=
non-strings형식으로 바꿔주지 않으면 followeduser_id를 동일하게 입력했을 때 동일한 유저인 오류를 반환하지 못한다.
http -v POST http://127.0.0.1:8080/postings/comment
Authorization:"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Mjl9.bJprZGfkw42uJfQ0JOn9tlie7RYo3g35KTQnLf4xWfk"
post_id=4
content="please"