当前位置: 首页>>代码示例>>Python>>正文


Python utils.load_strategy函数代码示例

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


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


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