200706 ~ 200717 (2주)
class KakaoView(View):
def post(self, request):
access_token = request.headers['Authorization']
kakao_request = requests.get(
'https://kapi.kakao.com/v2/user/me',
headers = {
"Host" : "kapi.kakao.com",
"Authorization" : f"Bearer {access_token}",
"Content-type" : "application/x-www-from-urlencoded;charset=utf-8"
}
,timeout = 2)
kakao_id = kakao_request.json().get('id')
kakao_properties = kakao_request.json().get('properties')
kakao_account = kakao_request.json().get('kakao_account')
try:
if Account.objects.filter(is_social_user = kakao_id).exists():
user = Account.objects.get(is_social_user = kakao_id)
token = jwt.encode({'user_id' : user.id }, SECRET_KEY, algorithm = ALGORITHM)
return JsonResponse({"access_token":token.decode('utf-8')}, status = 200)
else:
Account(
is_social_user = kakao_id,
gender = Gender.objects.get(name=kakao_account['gender']),
user_email = kakao_account['email'],
name = kakao_properties['nickname'],
birthdate = kakao_account['birthday']
).save()
user = Account.objects.get(is_social_user = kakao_id)
token = jwt.encode({'user_id' : user.id }, SECRET_KEY, algorithm = ALGORITHM)
return JsonResponse({"access_token":token.decode('utf-8')}, status = 200)
except KeyError:
return JsonResponse({"message":"INVALID_KEYS"}, status = 400)
class KakaoLoginTest(TestCase):
def setUp(self):
Gender(
id =1,
name = "male"
).save()
Account(
name = "홍길동",
password = bcrypt.hashpw('p1234'.encode('utf-8'), bcrypt.gensalt()).decode('utf-8'),
birthdate = "19880705",
gender = Gender.objects.get(name="male"),
phone_number = "01012345678",
user_email = "test@gmail.com"
).save()
@patch('account.views.requests')
def test_kakao_signin_success(self, mocked_request):
class FakeResponse:
def json(self):
return {
"id" : 12345,
"properties" : {"nickname": "test_user"},
"kakao_account" : {"email":"test@gmail.com","gender":"male","birthday":"18000908"}
}
mocked_request.get = MagicMock(return_value = FakeResponse())
client = Client()
header = {'HTTP_Authorization':'fake_token.1234'}
response = client.post('/account/kakao-login', content_type='applications/json', **header)
self.assertEqual(response.status_code, 200)
@patch('account.views.requests')
def test_kakao_signin_keyerror(self, mocked_request):
class FakeResponse:
def json(self):
return {
"id" : 12345,
"properties" : {"username": "test_user"},
"kakao_account" : {"email":"test@gmail.com","gender":"male","birthday":"18000908"}
}
mocked_request.get = MagicMock(return_value = FakeResponse())
client = Client()
header = {'HTTP_Authorization':'fake_token.1234'}
response = client.post('/account/kakao-login', content_type='applications/json', **header)
self.assertEqual(response.status_code, 400)
if __name__ == '__main__':
unittest.main()