마이리얼트립 클론①Kakao Rest API

박민하·2022년 7월 18일
0

PROJECT

목록 보기
14/17
post-thumbnail

<Fake_trip>
국내 숙소 카테고리를 한정으로 검색, 조건별 필터링, 예약 기능 구현

✅ Kakao Rest API

✔ 카카오 로그인

https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api

✅ Token

#core>social_apis.py
import requests

class Kakao_Token_Error(Exception):
    def __init__(self):
        self.message = 'Invalid Token'

class KakaoAPI:
    def __init__(self, access_token):
        self.access_token = access_token
        self.user_url     = "https://kapi.kakao.com/v2/user/me"

    def get_kakao_user_information(self):
        headers = {"Authorization": f"Bearer {self.access_token}"}

        response = requests.get(self.user_url, headers = headers, timeout = 3)
        
        if not response.status_code == 200:
            raise Kakao_Token_Error
	
        return response.json()

✅ View

✔ import

#user>views.py
import jwt

from django.views           import View
from django.http            import JsonResponse

from users.models            import User
from faketrip.settings       import SECRET_KEY, ALGORITHM
from core.social_apis        import Kakao_Token_Error, KakaoAPI

✔ function

class SigninView(View):
    def get(self, request):
        try:
            access_token     = request.headers.get('Authorization')
            user_information = KakaoAPI(access_token).get_kakao_user_information()
            
            kakao_pk      = user_information.get('id')
            email         = user_information.get('kakao_account').get('email')
            nickname      = user_information.get('properties').get('nickname')
            phone_number = user_information.get('properties').get('phone_number')

            user, created = User.objects.get_or_create(\
            kakao_pk=kakao_pk, defaults = {"email" : email, "name" : nickname, 'phone_number' : None})
            
            if not created and not(user.email == email and user.name == nickname):
                user.email, user.name = email, nickname
                user.save()

            authorization = jwt.encode({'user_id' : user.id}, SECRET_KEY, ALGORITHM)

            return JsonResponse({'message' : 'SUCCESS'},\
            headers = {'Authorization' : authorization}, status = 200)
        
        except Kakao_Token_Error as error:
            return JsonResponse({'message' : error.message}, status = 401)

[사진출처]

profile
backend developer 🐌

0개의 댓글