Decorator

On a regular basisยท2021๋…„ 7์›” 25์ผ
0
post-thumbnail
post-custom-banner

๐Ÿš€ Decorator

๋…๋ฆฝ์ ์ธ HTTP ํ†ต์‹  ๋•Œ๋ฌธ์— ํŽ˜์ด์ง€๊ฐ€ ๋„˜์–ด๊ฐˆ๋•Œ ๋งˆ๋‹ค ์ƒˆ๋กœ์šด ์ธ์ฆ์„ ํ•ด์ค˜์•ผ ํ•œ๋‹ค.
์ƒˆ๋กœ์šด ํŽ˜์ด์ง€์—์„œ ์ธ์ฆ์„ ํ•ด์•ผํ•˜์ง€๋งŒ ์ธ์ฆ ์ฝ”๋“œ๊ฐ€ ๋งค๋ฒˆ ๋ชจ๋“  ์ฝ”๋“œ์— ๋ถ™์œผ๋ฉด ์ฝ”๋“œ๊ฐ€ ๋ณต์žกํ•ด์ง€๊ณ  ๊ธธ์–ด์ง„๋‹ค.
์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ๊ณผ ๊ฐ„๊ฒฐํ™”๋ฅผ ์œ„ํ•ด ์ธ์ฆ ๊ตฌํ˜„ํ›„ ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

import jwt

from django.http.response import JsonResponse

from my_settings  import SECRET_KEY, ALGORITHM
from users.models import User

def login_required(func):
    def wrapper(self, request, *args, **kwargs):
        try:
            access_token = request.headers.get('Authorization', None)
            # ํ”„๋ก ํŠธ๊ฐ€ http์š”์ฒญ์—์„œ ํ—ค๋”์— Authorization:key๊ฐ’, access_token:value๊ฐ’ ๋ฐฑ์—๊ฒŒ ๋ณด๋ƒ„! 
            # ๋ฐ์ฝ”๋ ˆ์ดํ„ฐํ•จ์ˆ˜๋Š” authorization ๊ฐ’์„ ์ฝ๊ณ , ํ† ํฐ์ด ๋งž๋Š”์ง€ ํ™•์ธ
            # ํ† ํฐ์ด ๋งž์œผ๋ฉด(์žˆ์œผ๋ฉด), ๊ทธ๊ฐ’์„ ๋ณตํ˜ธํ™”(decoding)ํ•ด์„œ ์‚ฌ์šฉ์ž id ์ฝ์–ด๋“ค์ด๊ณ  ํ•ด๋‹น ์‚ฌ์šฉ์ž์˜ ๋กœ๊ธด ์—ฌ๋ถ€ ํ™•์ธ   

            payload = jwt.decode(access_token, SECRET_KEY, algorithms=ALGORITHM)
            # ํ† ํฐ์„ ๋””์ฝ”๋”ฉํ•ด์„œ ๋‚˜์˜ค๊ฒŒ ๋  ์‚ฌ์šฉ์ž์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ payload์— ๋‹ด๋Š”๋‹ค.
            # ๋™์ผํ•œ ์‚ฌ์šฉ์ž๋ผ๋ฉด ๋ฐœํ–‰ํ•  ๋•Œ ๋‚˜์˜จ ํ† ํฐํ•˜๊ณ  ๋™์ผํ•œ ํ† ํฐ์ด payload์— ๋ฐ˜ํ™˜๋˜๊ฒ ์ง€
            # ๋””์ฝ”๋”ฉ์‹œ secret_key์™€ algorithm์€ ํ† ํฐ ๋ฐœํ–‰์‹œ ๋„ฃ์—ˆ๋˜ ์ •๋ณด์™€ ๊ฐ™์•„์•ผํ•จ!

            user = User.objects.get(id=payload['user_id']
            # ํ† ํฐ ๋””์ฝ”๋”ฉํ•ด์„œ ์–ป์€ ์‚ฌ์šฉ์ž ์ •๋ณด์™€ ๋งค์นญ๋˜๋Š” ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ user ๋ณ€์ˆ˜์— ์ €์žฅ!

            request.user = user
            # request๊ฐ์ฒด์— user๊ฐ์ฒด ๋„ฃ์–ด์ฃผ๊ธฐ. (request๊ฐ์ฒด has headers, body, startline)
            # request๊ฐ์ฒด์— ์ถ”๊ฐ€๋œ user๊ฐ์ฒด๋Š” ๊ทธ๋Œ€๋กœ ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋ฅผ ๋น ์ ธ๋‚˜์˜ค๋Š” ์ˆœ๊ฐ„ ์‚ฌ๋ผ์ง€์ง€์•Š๊ณ  views.py์— ์žˆ๋Š” Profileํด๋ž˜์Šค์˜ get๋งค์„œ๋“œ์— ์ „ํ•ด์ง„๋‹ค.

        except jwt.DecodeError:
            # ์—†๋Š” ํ† ํฐ๊ฐ’ ๋“ค์–ด์˜ค๋ฉด DecodeError ์ฒ˜๋ฆฌ!

            return JsonResponse({"message":"invalid_token"}, status=401)

        except User.DoesNotExist:
            # ์ž˜๋ชป๋œ ์œ ์ €๊ฐ€ ๋“ค์–ด์˜ค๋ฉด DoesNotExist ์ฒ˜๋ฆฌ!

            return JsonResponse({"message":"Unknown_user"}, status=400)
        return func(self, request, *args, **kwargs)
    return wrapper
    # ์กฐ๊ฑด์ด ๋ชจ๋‘ ๋งž์•„ ๋–จ์–ด์ง€๋ฉด ์‹œ์ž‘๋  ๋•Œ ๋ฐ›์€ parameter๋ฅผ ์ „๋ถ€ ๋‹ค ๋ฆฌํ„ด,
    # ๋งˆ์ง€๋ง‰์œผ๋กœ wrapperํ•จ์ˆ˜ ๋ฆฌํ„ด
profile
๊ฐœ๋ฐœ ๊ธฐ๋ก
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€