本文整理匯總了Python中social_django.utils.load_strategy方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.load_strategy方法的具體用法?Python utils.load_strategy怎麽用?Python utils.load_strategy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類social_django.utils
的用法示例。
在下文中一共展示了utils.load_strategy方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: saml_sp_metadata
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def saml_sp_metadata(request: HttpRequest, **kwargs: Any) -> HttpResponse: # nocoverage
"""
This is the view function for generating our SP metadata
for SAML authentication. It's meant for helping check the correctness
of the configuration when setting up SAML, or for obtaining the XML metadata
if the IdP requires it.
Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html
"""
if not saml_auth_enabled():
return redirect_to_config_error("saml")
complete_url = reverse('social:complete', args=("saml",))
saml_backend = load_backend(load_strategy(request), "saml",
complete_url)
metadata, errors = saml_backend.generate_metadata_xml()
if not errors:
return HttpResponse(content=metadata,
content_type='text/xml')
return HttpResponseServerError(content=', '.join(errors))
示例2: validate
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def validate(self, attrs):
request = self.context["request"]
if "state" in request.GET:
self._validate_state(request.GET["state"])
strategy = load_strategy(request)
redirect_uri = strategy.session_get("redirect_uri")
backend_name = self.context["view"].kwargs["provider"]
backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)
try:
user = backend.auth_complete()
except exceptions.AuthException as e:
raise serializers.ValidationError(str(e))
return {"user": user}
示例3: _validate_state
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def _validate_state(self, value):
request = self.context["request"]
strategy = load_strategy(request)
redirect_uri = strategy.session_get("redirect_uri")
backend_name = self.context["view"].kwargs["provider"]
backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)
try:
backend.validate_state()
except exceptions.AuthMissingParameter:
raise serializers.ValidationError(
"State could not be found in request data."
)
except exceptions.AuthStateMissing:
raise serializers.ValidationError(
"State could not be found in server-side session data."
)
except exceptions.AuthStateForbidden:
raise serializers.ValidationError("Invalid state has been provided.")
return value
示例4: make_headers
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def make_headers(self, auth_type, headers=None):
"""Make headers for Fitbit API request
`auth_type` the string 'basic' or 'bearer'
https://dev.fitbit.com/docs/basics/#language
"""
# refreshes token if necessary
if self.social_auth_user.access_token_expired():
from social_django.utils import load_strategy
access_token = self.social_auth_user.get_access_token(load_strategy())
self.social_auth_user = refresh(self.social_auth_user)
if auth_type == 'bearer':
auth_header = 'Bearer %s' % self.social_auth_user.extra_data['access_token']
else:
auth_header = 'Basic %s' % base64.b64encode('%s:%s' % (self.client_id, self.client_secret,))
_headers = {
'Authorization' : auth_header,
'Accept-Locale' : 'en_US',
'Accept-Language' : 'en_US',
}
if headers:
_headers.update(headers)
headers = _headers
return headers
示例5: test_response_parsing
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def test_response_parsing(self):
"""
Should have properly formed payload if working.
"""
eoo = EdxOrgOAuth2(strategy=load_strategy())
result = eoo.get_user_details({
'id': 5,
'username': 'darth',
'email': 'darth@deathst.ar',
'name': 'Darth Vader'
})
assert {
'edx_id': 'darth',
'username': 'darth',
'fullname': 'Darth Vader',
'email': 'darth@deathst.ar',
'first_name': '',
'last_name': ''
} == result
示例6: test_single_name
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def test_single_name(self):
"""
If the user only has one name, last_name should be blank.
"""
eoo = EdxOrgOAuth2(strategy=load_strategy())
result = eoo.get_user_details({
'id': 5,
'username': 'staff',
'email': 'staff@example.com',
'name': 'staff'
})
assert {
'edx_id': 'staff',
'username': 'staff',
'fullname': 'staff',
'email': 'staff@example.com',
'first_name': '',
'last_name': ''
} == result
示例7: post
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def post(self, request, *args, **kwargs):
backend = request.data.get("backend", None)
if backend is None:
return Response({
"backend": ["This field is required."]
}, status=status.HTTP_400_BAD_REQUEST)
association_id = request.data.get("association_id", None)
if association_id is None:
return Response({
"association_id": ["This field is required."]
}, status=status.HTTP_400_BAD_REQUEST)
strategy = load_strategy(request=request)
try:
backend = load_backend(strategy, backend, reverse(NAMESPACE + ":complete", args=(backend,)))
except MissingBackend:
return Response({"backend": ["Invalid backend."]}, status=status.HTTP_400_BAD_REQUEST)
backend.disconnect(user=self.get_object(), association_id=association_id, *args, **kwargs)
return Response(status=status.HTTP_204_NO_CONTENT)
示例8: merging_accounts
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def merging_accounts(request):
"""Email required page"""
strategy = load_strategy()
partial_token = request.GET.get('partial_token')
partial = strategy.partial_load(partial_token)
social = strategy.storage.user.get_social_auth(partial.backend, partial.data['kwargs']['uid'])
if social.user.id != request.user.id:
context = {
'logged_in_profile': Profile.objects.get(user=request.user),
'logging_in_profile': Profile.objects.get(user=social.user),
'partial_backend_name': partial.backend if partial else None,
}
return context
return {
'email_required': True,
'partial_backend_name': partial.backend if partial else None,
'partial_token': partial_token
}
示例9: psa
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def psa(f):
@wraps(f)
def wrapper(cls, root, info, provider, access_token, **kwargs):
strategy = load_strategy(info.context)
try:
backend = load_backend(strategy, provider, redirect_uri=None)
except MissingBackend:
raise exceptions.GraphQLSocialAuthError(_('Provider not found'))
if info.context.user.is_authenticated:
authenticated_user = info.context.user
else:
authenticated_user = None
user = backend.do_auth(access_token, user=authenticated_user)
if user is None:
raise exceptions.InvalidTokenError(_('Invalid token'))
user_model = strategy.storage.user.user_model()
if not isinstance(user, user_model):
msg = _('`{}` is not a user instance').format(type(user).__name__)
raise exceptions.DoAuthError(msg, user)
if not issubclass(cls, mixins.JSONWebTokenMixin):
_do_login(backend, user, user.social_user)
return f(cls, root, info, user.social_user, **kwargs)
return wrapper
示例10: get
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def get(self, request, *args, **kwargs):
redirect_uri = request.GET.get("redirect_uri")
if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS:
return Response(status=status.HTTP_400_BAD_REQUEST)
strategy = load_strategy(request)
strategy.session_set("redirect_uri", redirect_uri)
backend_name = self.kwargs["provider"]
backend = load_backend(strategy, backend_name, redirect_uri=redirect_uri)
authorization_url = backend.auth_url()
return Response(data={"authorization_url": authorization_url})
示例11: get_authorization_headers
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def get_authorization_headers(self):
headers = {}
if self.g_social_auth:
# refreshes token if necessary
if self.g_social_auth.access_token_expired():
from social_django.utils import load_strategy
access_token = self.g_social_auth.get_access_token(load_strategy())
self.g_social_auth = refresh(self.g_social_auth)
headers['Authorization'] = '%(token_type)s %(access_token)s' % self.g_social_auth.extra_data
return headers
示例12: get_service
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def get_service(user):
social = user.social_auth.get(provider='google-oauth2')
ls = load_strategy()
access_token = social.get_access_token(ls)
credentials = Credentials(access_token)
service = build('drive', 'v3', credentials=credentials)
return service
示例13: _send_refresh_request
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def _send_refresh_request(user_social):
"""
Private function that refresh an user access token
"""
strategy = load_strategy()
try:
user_social.refresh_token(strategy)
except HTTPError as exc:
if exc.response.status_code in (400, 401,):
raise InvalidCredentialStored(
message='Received a {} status code from the OAUTH server'.format(
exc.response.status_code),
http_status_code=exc.response.status_code
)
raise
示例14: require_email
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def require_email(request):
"""Email required page"""
strategy = load_strategy()
partial_token = request.GET.get('partial_token')
partial = strategy.partial_load(partial_token)
return {
'email_required': True,
'partial_backend_name': partial.backend if partial else None,
'partial_token': partial_token
}
示例15: common_context
# 需要導入模塊: from social_django import utils [as 別名]
# 或者: from social_django.utils import load_strategy [as 別名]
def common_context(authentication_backends, user=None, **extra):
"""Common view context"""
backends = load_backends(authentication_backends)
context = {
'user': user,
'available_backends': backends,
'associations': dict((name, None) for name in backends.keys())
}
strategy = load_strategy()
if user and is_authenticated(user):
if user.profile.github_account:
context['associations']['github'] = {
'confirmed': False,
'data': {'uid': user.profile.github_account.name},
}
if user.profile.steem_account:
context['associations']['steemconnect'] = {
'confirmed': False,
'data': {'uid': user.profile.steem_account.name},
}
context['associations'].update(dict(
(
association.provider,
{
'confirmed': True,
'data': association
}
)
for association in associations(user, strategy)
))
return dict(context, **extra)