• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.load_strategy函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中social.apps.django_app.utils.load_strategy函数的典型用法代码示例。如果您正苦于以下问题:Python load_strategy函数的具体用法?Python load_strategy怎么用?Python load_strategy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了load_strategy函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: refresh_access

def refresh_access(user):
	if user and user.is_authenticated():
		social = user.social_auth.get(provider="reddit")
		#social.refresh_token(redirect_uri=SOCIAL_AUTH_REDDIT_REDIRECT)
		#social.refresh_token(social.extra_data["refresh_token"], redirect_uri=SOCIAL_AUTH_REDDIT_REDIRECT)
		strategy = load_strategy()
		social.refresh_token(strategy, redirect_uri=SOCIAL_AUTH_REDDIT_REDIRECT)
开发者ID:TheEnigmaBlade,项目名称:reddit-modmail-ticketer,代码行数:7,代码来源:reddit_util.py


示例2: register_by_access_token

def register_by_access_token(request, *args, **kwargs):
    # TODO: make me pretty, decorator? api_view
    # LD: looks fine :)
    # print request.META
    social_serializer = SocialTokenSerializer(data=request.data)
    social_serializer.is_valid(raise_exception=True)
    try:
        # TODO: this is really bad!
        client_id, client_secret = _get_client_id_and_secret(request)
        try:
            app = Application.objects.get(client_id=client_id)
        except ObjectDoesNotExist:
            return Response({"errors": ["client_id doesn't exist"]}, status=status.HTTP_400_BAD_REQUEST)
        data = social_serializer.data
        strategy = load_strategy(request)
        backend = load_backend(strategy, data['backend'], None)
        user = backend.do_auth(data['social_token'])
        if user:
            if not user.last_login:
                login(request, user)
                serializer = UserSerializer(user, context={'request': request})
                returned_json = {
                    'user': serializer.data,
                    'token': get_access_token(user, app)
                }
                return JsonResponse({'data': returned_json})
            else:
                return Response({"errors": ["user already registered"]}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return _facebook_login_error("after token user is none")
    except HTTPError as e:
        return _facebook_login_error(e.message + " when connecting to " + data['backend'])
开发者ID:SolutionCode,项目名称:WinkBackend,代码行数:32,代码来源:views.py


示例3: social_login

def social_login(request):
    """
    Returns two-tuple of (user, token) if authentication succeeds,
    or None otherwise.
    """
    token = request.DATA.get('access_token', None)
    backend = request.DATA.get('backend', None)
    strategy = load_strategy(request=request)
    try:
        backend = load_backend(strategy, backend, reverse(NAMESPACE + ":complete", args=(backend,)))
    except MissingBackend:
        msg = 'Invalid token header. Invalid backend.'
        return Response(str(msg), status=400)
    try:
        user = backend.do_auth(access_token=token)
    except requests.HTTPError as e:
        msg = e.response.text
        return Response(str(msg), status=400)
    if not user:
        msg = 'Bad credentials.'
        return Response(str(msg), status=400)

    login(request, user)
    serialized = AccountSerializer(user)
    return Response(serialized.data, status=status.HTTP_200_OK )
开发者ID:jejimenez,项目名称:matching_map_routes_vs_points,代码行数:25,代码来源:views.py


示例4: home

def home(request):
	tracks = []
	soundcloud_auth = False
	pnos=0
	next_page = 0
	prev_page = 0
	current_page = request.GET.get('current_page',1)
	current_page = int(current_page)
	print 'current_page is'
	print current_page

	if request.user and request.user.is_anonymous() is False and request.user.is_superuser is False:
		try:
			soundcloud_auth = UserSocialAuth.objects.get(user=request.user,provider="soundcloud")

			if soundcloud_auth:
				soundcloud_auth = True
		except Exception, e:
			#Nothing to worry , Sound cloud isn't connected
			print e

		#Try refreshing the token	
		try: 
			if soundcloud_auth:
				User = get_user_model()
				suser = User.objects.get(id=request.user.id)
				social = suser.social_auth.get(provider='soundcloud')
				social.refresh_token(load_strategy())
		except Exception, e:
			print 'refresh token error'
			print e 
开发者ID:ebradbury,项目名称:SoundFunnel,代码行数:31,代码来源:views.py


示例5: register_by_access_token

def register_by_access_token(request, backend):
    uri=''
    strategy = load_strategy(request)
    backend = load_backend(strategy, backend, uri)
    # Split by spaces and get the array
    auth = get_authorization_header(request).split()

    if not auth:
        msg= 'No auth provided'
        return msg


    if not auth or auth[0].lower() != b'bearer':
        msg = 'No token header provided.'
        return msg

    if len(auth) == 1:
        msg = 'Invalid token header. No credentials provided.'
        return msg

    access_token = auth[1].decode(encoding='UTF-8')

    user = backend.do_auth(access_token)

    return user
开发者ID:cloudsan,项目名称:Temperature-Sensor-Abu-Dhabi,代码行数:25,代码来源:views.py


示例6: refresh_user_course_permissions

def refresh_user_course_permissions(user):
    """
    Refresh user course permissions from the auth server.

    Arguments
        user (User) --  User whose permissions should be refreshed
    """
    backend = EdXOpenIdConnect(strategy=load_strategy())
    user_social_auth = user.social_auth.filter(provider=backend.name).first()

    if not user_social_auth:
        raise UserNotAssociatedWithBackendError

    access_token = user_social_auth.extra_data.get('access_token')

    if not access_token:
        raise InvalidAccessTokenError

    courses = _get_user_courses(access_token, backend)

    # If the backend does not provide course permissions, assign no permissions and log a warning as there may be an
    # issue with the backend provider.
    if not courses:
        logger.warning('Authorization server did not return course permissions. Defaulting to no course access.')
        courses = []

    set_user_course_permissions(user, courses)

    return courses
开发者ID:Chirram,项目名称:edx-analytics-dashboard,代码行数:29,代码来源:permissions.py


示例7: setUp

 def setUp(self):
     super(AccessTokenExchangeFormTest, self).setUp()
     self.request = RequestFactory().post("dummy_url")
     redirect_uri = 'dummy_redirect_url'
     SessionMiddleware().process_request(self.request)
     self.request.social_strategy = social_utils.load_strategy(self.request)
     # pylint: disable=no-member
     self.request.backend = social_utils.load_backend(self.request.social_strategy, self.BACKEND, redirect_uri)
开发者ID:189140879,项目名称:edx-platform,代码行数:8,代码来源:test_forms.py


示例8: __init__

    def __init__(self, user, request=None, provider='google-oauth2'):
        self.user = user
        self.request = request
        self.provider = provider

        self.strategy = load_strategy(request)
        self.user_social = UserSocialAuth.get_social_auth_for_user(user=self.user, provider=self.provider)[0]
        self.backend = self.user_social.get_backend_instance(strategy=self.strategy)
开发者ID:chwnam,项目名称:lifemotif,代码行数:8,代码来源:auth_dishes.py


示例9: _fn

 def _fn(self, *args, **kwargs):
     try:
         return fn(self, *args, **kwargs)
     except HTTPError:
         s = load_strategy(backend='google-oauth2')
         sa = self._user.social_auth.get()
         sa.refresh_token(s)
         sa.save()
         return fn(self, *args, **kwargs)
开发者ID:paultag,项目名称:glass,代码行数:9,代码来源:social_auth.py


示例10: _fake_strategy

    def _fake_strategy(self):
        """Simulate the strategy passed to the pipeline step. """
        request = RequestFactory().get(pipeline.get_complete_url(self.BACKEND_NAME))
        request.user = self.user
        request.session = cache.SessionStore()

        return social_utils.load_strategy(
            backend=self.BACKEND_NAME, request=request
        )
开发者ID:mrgnr,项目名称:edx-platform,代码行数:9,代码来源:test_change_enrollment.py


示例11: get_fb_user_token

 def get_fb_user_token(self):
     """
     Retrieve facebook user token from python-social-auth lib
     """
     user = User.objects.get(username=settings.ADMIN_USER) #this should not be static
     #get the oath2 token for user haike
     social = user.social_auth.get(provider='facebook')
     strategy = load_strategy(backend='facebook')
     social.refresh_token(strategy)
     return social.extra_data['access_token']
开发者ID:haikezegwaard,项目名称:buzzart,代码行数:10,代码来源:fbmanager.py


示例12: obj_create

 def obj_create(self, bundle, request=None, **kwargs):
     provider = bundle.data['provider']
     access_token = bundle.data['access_token']
     strategy = load_strategy(backend=provider)
     user = strategy.backend.do_auth(access_token)
     if user and user.is_active:
         bundle.obj = user
         return bundle
     else:
         raise BadRequest(_("Error authenticating user with this provider"))
开发者ID:schocco,项目名称:mds-web,代码行数:10,代码来源:api.py


示例13: bind

 def bind(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = request.user
     oauth = Oauth.objects.create(access_token=serializer.data['access_token'], user=user, provider=Providers.Github)
     strategy = load_strategy(request=request)
     kwargs = dict({(k, i) for k, i in serializer.data.items() if k != 'backend'})
     # 使用者驗證
     tmp = strategy.backend.do_auth(**kwargs)
     return Response(data={'message': '绑定成功'}, status=status.HTTP_200_OK)
开发者ID:joway,项目名称:Chirp,代码行数:10,代码来源:apis.py


示例14: post

    def post(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            backend = serializer.data['backend']
            access_token = serializer.data['access_token']
            jwt = serializer.data.get('jwt_token', None)

        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        # 讀取python-social-auth strategy
        strategy = load_strategy(request=request)
        backend = load_backend(strategy, backend, 'next')

        try:
            kwargs = dict({(k, i) for k, i in serializer.data.items() if k != 'backend'})
            if jwt:
                # Get user from provided jwt
                try:
                    payload = jwt_decode_handler(jwt)
                    user = User.objects.get(id=payload['user_id'])
                    if user.is_authenticated():
                        kwargs['user'] = user
                    else:
                        raise Exception('not authenticated')
                except:
                    kwargs['user'] = None
                    pass

            user = backend.do_auth(**kwargs)

        except AuthAlreadyAssociated:
            data = {
                'error_code': 'social_already_associated',
                'status': 'Auth associated with another user.',
            }
            return Response(data, status=status.HTTP_403_FORBIDDEN)

        if not user:
            data = {
                'error_code': 'social_no_user',
                'status': 'No associated user.',
            }
            return Response(data, status=status.HTTP_403_FORBIDDEN)

        if not user.is_active:
            data = {
                'error_code': 'social_inactive',
                'status': 'Associated user is inactive.'
            }
            return Response(data, status=status.HTTP_403_FORBIDDEN)

        payload = jwt_payload_handler(user)
        return Response({'token': jwt_encode_handler(payload), 'username': user.username}) # 回傳JWT token及使用者帳號
开发者ID:genxstylez,项目名称:mooq,代码行数:55,代码来源:views.py


示例15: __getattr__

 def __getattr__(self, name, **kwargs):
     """Translate an HTTP verb into a request method."""
     try:
         return super(DjangoSoundcloudClient, self).__getattr__(name,
                                                                **kwargs)
     except HTTPError:
         strategy = load_strategy()
         django_user.social_auth.get().refresh_token(strategy)
     finally:
         return super(DjangoSoundcloudClient, self).__getattr__(name,
                                                                **kwargs)
开发者ID:systemizer,项目名称:friendjamradio,代码行数:11,代码来源:utils.py


示例16: refresh_access_token_for_user

 def refresh_access_token_for_user(self, user=None):
     """
     Get a new access token using the refresh token
     """
     if user is None:
         user = User.objects.get(username=settings.SOCIAL_AUTH_FALLBACK_USERNAME)
     # get the stored oauth2 access token for user
     social = user.social_auth.get(provider='google-oauth2', user=user)
     strategy = load_strategy(backend='google-oauth2')
     new_token = social.refresh_token(strategy)
     return new_token
开发者ID:haikezegwaard,项目名称:buzzart,代码行数:11,代码来源:analyticsmanager.py


示例17: create

    def create(self, request, *args, **kwargs):
        provider = request.data['provider']

        # If this request was made with an authenticated user, try to associate this social
        # account with it
        authed_user = request.user if not request.user.is_anonymous() else None

        # `strategy` is a python-social-auth concept referencing the Python framework to
        # be used (Django, Flask, etc.). By passing `request` to `load_strategy`, PSA
        # knows to use the Django strategy
        strategy = load_strategy(request)
        # Now we get the backend that corresponds to our user's social auth provider
        # e.g., Facebook, Twitter, etc.
        backend = load_backend(strategy=strategy, name=provider, redirect_uri=None)

        if isinstance(backend, BaseOAuth1):
            # Twitter, for example, uses OAuth1 and requires that you also pass
            # an `oauth_token_secret` with your authentication request
            token = {
                'oauth_token': request.data['access_token'],
                'oauth_token_secret': request.data['access_token_secret'],
            }
        elif isinstance(backend, BaseOAuth2):
            # We're using oauth's implicit grant type (usually used for web and mobile
            # applications), so all we have to pass here is an access_token
            token = request.data['access_token']

        try:
            # if `authed_user` is None, python-social-auth will make a new user,
            # else this social account will be associated with the user you pass in
            user = backend.do_auth(token, user=authed_user)
            login(request, user)
        except AuthAlreadyAssociated:
            # You can't associate a social account with more than user
            return Response({"errors": "That social media account is already in use"},
                            status=status.HTTP_400_BAD_REQUEST)

        if user and user.is_active:
            # if the access token was set to an empty string, then save the access token
            # from the request
            auth_created = user.social_auth.get(provider=provider)
            if not auth_created.extra_data['access_token']:
                # Facebook for example will return the access_token in its response to you.
                # This access_token is then saved for your future use. However, others
                # e.g., Instagram do not respond with the access_token that you just
                # provided. We save it here so it can be used to make subsequent calls.
                auth_created.extra_data['access_token'] = token
                auth_created.save()

            return get_access_token(user)
        else:
            return Response({"errors": "Error with social authentication"},
                            status=status.HTTP_400_BAD_REQUEST)
开发者ID:akiokio,项目名称:crispyLake,代码行数:53,代码来源:views.py


示例18: complete

    def complete(self, **kwargs):
        # Before we proceed the auth, clear the session to ensure that no
        # half-backed registrations are left over (this would result in a
        # redirect to extradata after login even if the logged in user has a
        # complete profile.
        self.request.session.clear()

        # Load social strategy to ensure this request looks like a social auth
        # request.
        self.request.social_strategy = load_strategy(backend='username')

        return complete(self.request, 'username', **kwargs)
开发者ID:EnTeQuAk,项目名称:doit,代码行数:12,代码来源:views.py


示例19: auth_by_token

def auth_by_token(request, backend):
    uri = ''
    strategy = load_strategy(request)
    backend = load_backend(strategy, backend, uri)
    user = request.user
    user = backend.do_auth(
        access_token=request.data.get('access_token'),
        user=user.is_authenticated() and user or None
    )
    if user and user.is_active:
        return user# Return anything that makes sense here
    else:
        return None
开发者ID:snetdev1,项目名称:snetDjango,代码行数:13,代码来源:views.py


示例20: refresh_access_tokens

def refresh_access_tokens():
    """ Refresh all social access tokens in turn.

    This should avoid hitting http://dev.1flow.net/webapps/1flow/group/664/
    """

    start_time = now()

    users = User.objects.all()

    # sleep_time = 1500 / count
    count  = users.count()
    done   = 0
    errors = 0
    nosoc  = 0

    django_stategy = load_strategy()

    for user in users:
        # See http://django-social-auth.readthedocs.org/en/latest/use_cases.html#token-refreshing # NOQA
        # LOGGER.warning(u'Refreshing invalid access_token for user %s.',
        #               user.username)

        social_accounts = user.social_auth.filter(provider='google-oauth2')

        if social_accounts.count() == 0:
            nosoc += 1
            continue

        for social in social_accounts:
            try:
                social.refresh_token(django_stategy)

            except:
                LOGGER.exception(u'Access token could not be refreshed for '
                                 u'user %s, forcing re-authentication at '
                                 u'next login.', user.username)

                # With `associate_by_email` in the social-auth pipeline,
                # a reconnecting user will be re-associated with his
                # existing Django account, getting back all his preferences
                # and 1flow data. We delete here only the association.
                social.delete()
                errors += 1
            else:
                done += 1

    LOGGER.warning(u'refresh_access_tokens finished, %s/%s refreshed, '
                   u'%s error(s), %s not associated, duration: %s.',
                   done, count, errors, nosoc,
                   humanize.time.naturaldelta(now() - start_time))
开发者ID:1flow,项目名称:1flow,代码行数:51,代码来源:tasks.py



注:本文中的social.apps.django_app.utils.load_strategy函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python views.complete函数代码示例发布时间:2022-05-27
下一篇:
Python models.UserSocialAuth类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap