LANEIGE clone 프로젝트 과정(3)

JM·2020년 7월 19일
0

Project

목록 보기
7/11

utils.py

import json
import bcrypt
import jwt
import requests
import hashlib
import hmac
import base64
import time

from django.http import JsonResponse

from account.models import Account
from laneige.settings import (
    SECRET_KEY,
    ACCESS_KEY,
    NAVER_SECRET_KEY,
    NAVER_SMS_URI,
    NAVER_URI,
    ALGORITHM,
    SMS_PHONE_NUM
)

def login_required(func): 
    def wrapper(self, request, *args, **kwargs):

        if "Authorization" not in request.headers:
            return JsonResponse({"error_code" : "INVALID_LOGIN"}, status=401)

        encode_token = request.headers["Authorization"]
        try:
            data = jwt.decode(encode_token, SECRET_KEY, algorithms=ALGORITHM)                      
            user = Account.objects.get(id = data["user_id"])
            request.user_id = user
            
        except jwt.DecodeError:
            return JsonResponse({"error_code":"INVALID_TOKEN"}, status=401)

        except Account.DoesNotExist:
            return JsonResponse({"error_code":"UNKNOWN_USER"}, status=401)

        return func(self, request, *args, **kwargs)
    
    return wrapper
        
def send_sms(phone_number):

    timestamp = int(time.time() * 1000)
    timestamp = str(timestamp)
    access_key = ACCESS_KEY
    secret_key = NAVER_SECRET_KEY
    secret_key = bytes(secret_key, 'UTF-8')
    method = "POST"
    uri = NAVER_URI
    message = method + " " + uri + "\n" + timestamp + "\n" + access_key
    message = bytes(message, 'UTF-8')
    signingKey = base64.b64encode(
        hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())

    headers = {
        'Content-Type': 'application/json; charset=utf-8',
        'x-ncp-apigw-timestamp': timestamp,
        'x-ncp-iam-access-key': access_key,
        'x-ncp-apigw-signature-v2': signingKey,
    }

    payload = {
                'type'          : 'SMS',
                'contentType'   : 'COMM',
                'countryCode'   : "82",
                'from'          : 'SMS_PHONE_NUM',
                'messages'      : [{'to':phone_number}],
                'content'       : "마요네즈 회원 가입을 축하합니다"
            }
    
    requests.post(NAVER_SMS_URI, headers=headers, json=payload)


def send_sms_reservation(**kwargs):
    timestamp   = int(time.time() * 1000)
    timestamp   = str(timestamp)
    access_key  = ACCESS_KEY
    secret_key  = NAVER_SECRET_KEY
    secret_key  = bytes(secret_key, 'UTF-8')
    method      = "POST"
    uri         = NAVER_URI
    message     = method + " " + uri + "\n" + timestamp + "\n"+ access_key
    message     = bytes(message, 'UTF-8')
    signingKey  = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())
    headers = {
        'Content-Type'              : 'application/json; charset=utf-8',
        'x-ncp-apigw-timestamp'     : timestamp,
        'x-ncp-iam-access-key'      : access_key,
        'x-ncp-apigw-signature-v2'  : signingKey,
    }
    payload = {
        'type'          : 'SMS',
        'contentType'   : 'COMM',
        'countryCode'   : "82",
        'from'          : 'SMS_PHONE_NUM',
        'messages'      : [{'to':kwargs['u_phone']}],
        'content'       : f"{kwargs['u_name']} 회원님,\n예약 번호 : {kwargs['u_number']} 로 예약이 완료되었습니다. 감사합니다.\n- 마요네즈"           
    }
    requests.post(NAVER_SMS_URI, headers=headers, json=payload)
  • Decorater를 사용하여 웹사이트 내 다양한 곳에서 로그인을 검증하였다.
  • 이때 객체를 통째로 토큰화 시키는 것과 객체에 대한 id_number만 보내는 것에 큰 차이가 있는 것을 알았다.
  • 이번 프로젝트의 경우 객체를 토큰화 시켜 사용을 하였는데 다양한 곳에서 활용도가 높았다.
  • 회원 가입 시 SMS를 보내게 되는데 kakao_login을 통해 RESTful API를 조금이나마 이해하고 사용하였다.(+ 한국님의 도움)
  • 서비스 예약 시에도 SMS를 보내는데 같은 방식으로 구현하였다.

0개의 댓글