11import logging
2+ from django .conf import settings
23from django .contrib .auth .models import AnonymousUser
4+ from django .core .cache import cache
5+ from django .utils .translation import gettext_lazy as _
36from rest_framework import authentication
4- from rest_framework .authentication import TokenAuthentication
7+ from rest_framework .authentication import TokenAuthentication , \
8+ get_authorization_header
9+ from rest_framework import exceptions
510
11+ from api .oauth import OAuthManager
612
713logger = logging .getLogger (__name__ )
814
@@ -27,3 +33,43 @@ def authenticate(self, request):
2733 except Exception as e :
2834 logger .debug (e )
2935 return AnonymousUser (), None
36+
37+
38+ class DryccTokenAuthentication (TokenAuthentication ):
39+ def authenticate (self , request ):
40+ if 'manager' in request .META .get ('HTTP_USER_AGENT' , '' ):
41+ auth = get_authorization_header (request ).split ()
42+
43+ if not auth or auth [0 ].lower () != self .keyword .lower ().encode ():
44+ return None
45+
46+ if len (auth ) == 1 :
47+ msg = _ ('Invalid token header. No credentials provided.' )
48+ raise exceptions .AuthenticationFailed (msg )
49+ elif len (auth ) > 2 :
50+ msg = _ ('Invalid token header. Token string should not contain spaces.' ) # noqa
51+ raise exceptions .AuthenticationFailed (msg )
52+
53+ try :
54+ token = auth [1 ].decode ()
55+ except UnicodeError :
56+ msg = _ ('Invalid token header. Token string should not contain invalid characters.' ) # noqa
57+ raise exceptions .AuthenticationFailed (msg )
58+ return self ._check_oauth_token (token )
59+ return super (DryccTokenAuthentication , self ).authenticate (request ) # noqa
60+
61+ def _check_oauth_token (self , key ):
62+ user = cache .get (key )
63+ if user :
64+ return user , None
65+ try :
66+ user_info = OAuthManager ().get_user_by_token (key )
67+ if not user_info .get ('email' ):
68+ user_info ['email' ] = OAuthManager ().get_email_by_token (key )
69+ except Exception as e :
70+ logger .info (e )
71+ raise exceptions .AuthenticationFailed (_ ('Verify token fail.' ))
72+ from api import serializers
73+ user = serializers .UserSerializer .update_or_create (user_info )
74+ cache .set (key , user , settings .OAUTH_USER_CACHE_TIME )
75+ return user , None
0 commit comments