-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthentications.py
More file actions
49 lines (41 loc) · 2.08 KB
/
authentications.py
File metadata and controls
49 lines (41 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import requests
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.tokens import AccessToken
from usr.models import User
from config.settings import APP_LOGGER
import logging # 로그 작성을 위해서 사용됩니다.
logger = logging.getLogger(APP_LOGGER)
class CustomAuthentication(BaseAuthentication):
# authenticate 메소드 오버라이딩
def authenticate(self, request):
auth_header = request.headers.get('Authorization') # Authorization 헤더 정보를 얻습니다.
if not auth_header:
return None # None으로 반환하는 경우 Django의 AnonymousUser로 인식됩니다.
try:
prefix, access_token = auth_header.split(' ')
except ValueError:
raise AuthenticationFailed('Invalid Bearer Prefix')
if prefix != 'Bearer':
raise AuthenticationFailed('Invalid Bearer Prefix')
# 사용자 정보를 받아옵니다.
try:
# 액세스 토큰 검증을 시도합니다.
payload = AccessToken(access_token)
sub = payload['sub']
user = User.objects.get(sub=sub)
logger.info(f'username: {user.username}(sub: {sub}) User attempting to access backend Api')
return user, access_token
except User.DoesNotExist: # 사용자 정보가 없을 경우
logger.info('New User attempting to access backend Api')
return None
except Exception as e:
logger.info(f'Authentication Failed: {e} - Exception code (a40)')
raise AuthenticationFailed(f'Authentication Failed - {e}')
def validate_kakao_access_token(self, access_token):
end_point = 'https://kapi.kakao.com/v1/user/access_token_info' # 유효성 검증 url
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get(end_point, headers=headers)
if response.status_code != 200:
raise AuthenticationFailed('Invalid Kakao Access Token')
return response.json()