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