Example #1
0
 def perform_create(self, serializer):
     user = serializer.save()
     if serializer.validated_data.get('access_token'):
         self.request.social_strategy = load_strategy(self.request)
         if not hasattr(self.request, 'strategy'):
             self.request.strategy = self.request.social_strategy
             self.request.backend = load_backend(self.request.social_strategy, "facebook",
                                                 reverse("accounts:token-auth"))
         self.request.social_strategy = load_strategy(self.request)
         self.request.backend = load_backend(self.request.social_strategy, 'facebook', None)
         self.request.backend.do_auth(serializer.validated_data.get("access_token"), None, user=user, is_new=True)
     return user
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
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
Example #4
0
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'])
Example #5
0
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
Example #6
0
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 
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 )
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
Example #9
0
    def get_request_and_strategy(self, auth_entry=None, redirect_uri=None):
        """Gets a fully-configured request and strategy.

        These two objects contain circular references, so we create them
        together. The references themselves are a mixture of normal __init__
        stuff and monkey-patching done by python-social-auth. See, for example,
        social.apps.django_apps.utils.strategy().
        """
        request = self.request_factory.get(
            pipeline.get_complete_url(self.backend_name) +
            '?redirect_state=redirect_state_value&code=code_value&state=state_value'
        )
        request.user = auth_models.AnonymousUser()
        request.session = cache.SessionStore()
        request.session[self.backend_name + '_state'] = 'state_value'

        if auth_entry:
            request.session[pipeline.AUTH_ENTRY_KEY] = auth_entry

        strategy = social_utils.load_strategy(request=request)
        request.social_strategy = strategy
        request.backend = social_utils.load_backend(strategy,
                                                    self.backend_name,
                                                    redirect_uri)

        return request, strategy
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)
    def get_officevideo_embed_code(self, officevideo_url):

        embed_code = ''
        try:
            django_user_social = User.objects.get(
                id=self.xmodule_runtime.user_id).social_auth.get(
                    provider='azuread-oauth2')
            if int(django_user_social.extra_data['expires_on']) < int(
                    time.time()):
                django_user_social.refresh_token(load_strategy())
                django_user_social = User.objects.get(
                    id=self.xmodule_runtime.user_id).social_auth.get(
                        provider='azuread-oauth2')
            url = self.video_url
            parsed = urlparse.urlparse(url)
            query_params = urlparse.parse_qs(parsed.query)
            resp = requests.get("https://" + parsed.netloc +
                                "/portals/hub/_api/VideoService/Channels('" +
                                query_params['chid'][0] + "')/Videos('" +
                                query_params['vid'][0] +
                                "')/GetVideoEmbedCode",
                                headers={
                                    'Authorization':
                                    'Bearer ' + django_user_social.tokens,
                                    'Content-Type':
                                    'application/json;odata=verbose'
                                })
            root = ET.fromstring(resp._content)
            embed_code = unicode(root.text, "utf-8")
        except:
            embed_code = '<a target="_blank" href="' + officevideo_url + '">Office 365 Video</a>'

        return embed_code
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=settings.SOCIAL_AUTH_REDDIT_REDIRECT)
Example #13
0
 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)
Example #14
0
    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)
    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)
Example #16
0
 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)
Example #17
0
 def github_token(self):
     strategy = load_strategy()
     github_auth = self.contributor.user.social_auth.filter(
         provider='github')
     if github_auth.count():
         github_auth = github_auth[0]
         github_auth.refresh_token(strategy)
     if github_auth:
         return github_auth.access_token
    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
        )
Example #19
0
 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)
Example #20
0
 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"))
Example #21
0
File: apis.py Project: joway/Chirp
 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)
Example #22
0
    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)
Example #23
0
 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']
Example #24
0
    def create(self, request, *args, **kwargs):
        """
        Override `create` instead of `perform_create` to access request
        request is necessary for `load_strategy`
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        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 = load_strategy(request)
        backend = load_backend(strategy=strategy,
                               name=provider,
                               redirect_uri=None)

        if isinstance(backend, BaseOAuth1):
            token = {
                'oauth_token': request.data['access_token'],
                'oauth_token_secret': request.data['access_token_secret'],
            }
        elif isinstance(backend, BaseOAuth2):
            token = request.data['access_token']

        try:
            user = backend.do_auth(token, user=authed_user)
        except AuthAlreadyAssociated:
            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']:
                auth_created.extra_data['access_token'] = token
                auth_created.save()

            # Allow client to send up password to complete auth flow
            if not authed_user and 'password' in request.data:
                password = base64.decodestring(request.data['password'])
                user.set_password(password)
                user.save()

            # Set instance since we are not calling `serializer.save()`
            serializer.instance = user
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data,
                            status=status.HTTP_201_CREATED,
                            headers=headers)
        else:
            return Response({"errors": "Error with social authentication"},
                            status=status.HTTP_400_BAD_REQUEST)
Example #25
0
    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及使用者帳號
Example #26
0
 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)
Example #27
0
 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
Example #28
0
 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)
Example #29
0
    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)
Example #30
0
    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)
Example #31
0
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))
Example #32
0
    def create(self, request, *args, **kwargs):
        if 'backend' not in request.data:
            return Response({"errors": 'Specify backend type'},
                            status=status.HTTP_400_BAD_REQUEST)
        elif request.data['backend'] != 'google':
            return Response({"errors": 'Wrong backend type'},
                            status=status.HTTP_400_BAD_REQUEST)
        else:
            provider = GOOGLE_PROVIDER

        if 'access_token' not in request.data or not request.data[
                'access_token']:
            return Response({"errors": 'Access_token is not provided'},
                            status=status.HTTP_400_BAD_REQUEST)

        authed_user = request.user if not request.user.is_anonymous() else None
        strategy = load_strategy(request)
        backend = load_backend(strategy=strategy,
                               name=provider,
                               redirect_uri=None)
        token = request.data['access_token']
        is_new = False
        try:
            user = backend.do_auth(token, user=authed_user)
            is_new = user.is_new
        except AuthAlreadyAssociated:
            return Response(
                {"errors": "That social media account is already in use"},
                status=status.HTTP_400_BAD_REQUEST)
        except HTTPError:
            try:
                user = User.objects.get(token=token)
                user.social_auth.get(provider=provider).refresh_token(strategy)
            except:
                return Response({"errors": "Unauthorized token for url"},
                                status=status.HTTP_403_FORBIDDEN)
        if user and user.is_active:
            auth_created = user.social_auth.get(provider=provider)
            if auth_created.access_token != user.token:
                user.token = auth_created.access_token
                user.save()
            resp = {'token': user.token, 'is_new': is_new, 'user_id': user.id}
            serializer = self.get_serializer(data=resp)
            serializer.is_valid(raise_exception=True)
            headers = self.get_success_headers(serializer.data)
            status_response = status.HTTP_201_CREATED if is_new else status.HTTP_200_OK
            return Response(serializer.data,
                            status=status_response,
                            headers=headers)
        else:
            return Response({"errors": "Error with social authentication"},
                            status=status.HTTP_400_BAD_REQUEST)
Example #33
0
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
Example #34
0
File: tasks.py Project: 1flow/1flow
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))
Example #35
0
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
    if request.data['accessToken'] is None:
        msg = 'No access token provided.'
        return msg
    else:
        access_token = request.data['accessToken']

    # Real authentication takes place here
    user = backend.do_auth(access_token)
    return user
Example #36
0
 def __init__(self, provider, uid, data):
     self.strategy = load_strategy()
     self.provider = provider
     self.uid = uid
     self.data = data
     self.user = None
     self.social = None
     self.is_new = True
     self.new_assoc = True
     self.username = None
     self.details = None
     self.is_validated = False
     self.cleaned_data = {}
     self.load_proper_backend()
Example #37
0
 def __init__(self, provider, uid, data):
     self.strategy = load_strategy()
     self.provider = provider
     self.uid      = uid
     self.data     = data
     self.user     = None
     self.social   = None
     self.is_new   = True
     self.new_assoc= True
     self.username = None
     self.details  = None
     self.is_validated = False
     self.cleaned_data = {}
     self.load_proper_backend()
Example #38
0
 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)
Example #39
0
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
Example #40
0
def register_by_access_token(request, backend):
    access_token = request.DATA.get('access_token', None)
    if not access_token:
        return Response("missing access_token", status=400)
    try:
        user = request.strategy.backend.do_auth(access_token=access_token)
    except Exception as err:
        return Response(str(err), status=400)
    if user:
        social_fb_api.enrich_via_facebook(user)
        strategy = load_strategy(request=request, backend=backend)
        login(strategy.request, user)
        serializer = LoginSerializer(instance=user, context={'request': request})
        return Response(data=serializer.data, status=status.HTTP_200_OK)
    else:
        return Response("Bad Credentials", status=403)
Example #41
0
def do_auth(oauth_token):
    strategy = load_strategy()
    path = NAMESPACE + ":complete"
    backend = 'github'
    backend = load_backend(strategy, backend,
                           reverse(path, args=(backend,)))
    try:
        user = backend.do_auth(access_token=oauth_token)
    except requests.HTTPError as e:
        raise AuthenticationFailed(e.response.json())
    if not user:
        raise AuthenticationFailed('Bad credentials')
    social = user.social_auth.get(provider='github')
    social.extra_data['access_token'] = oauth_token
    social.save()
    return user
Example #42
0
def saml_metadata_view(request):
    """
    Get the Service Provider metadata for this edx-platform instance.
    You must send this XML to any Shibboleth Identity Provider that you wish to use.
    """
    if not SAMLConfiguration.is_enabled():
        raise Http404
    complete_url = reverse('social:complete', args=("tpa-saml", ))
    if settings.APPEND_SLASH and not complete_url.endswith('/'):
        complete_url = complete_url + '/'  # Required for consistency
    saml_backend = load_backend(load_strategy(request), "tpa-saml", redirect_uri=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))
Example #43
0
def saml_metadata_view(request):
    """
    Get the Service Provider metadata for this edx-platform instance.
    You must send this XML to any Shibboleth Identity Provider that you wish to use.
    """
    if not SAMLConfiguration.is_enabled():
        raise Http404
    complete_url = reverse('social:complete', args=("tpa-saml", ))
    if settings.APPEND_SLASH and not complete_url.endswith('/'):
        complete_url = complete_url + '/'  # Required for consistency
    saml_backend = load_backend(load_strategy(request), "tpa-saml", redirect_uri=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))
Example #44
0
 def get_access_token_for_user(self, user=None):
     """
     Retrieve social_auth token for given user, fall back to default user if
     none given. This is only for demo/R&D purposes.
     """
     self.logger.debug('get acces token debug test')
     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)
     # get a new access token using the refresh token if necessary
     if social.extra_data['expires'] == 0:
         self.logger.debug("""access token expired, retrieving new token
                           using refresh token""")
         strategy = load_strategy(backend='google-oauth2')
         social.refresh_token(strategy)
     return social.extra_data['access_token']
Example #45
0
    def post(self, request):
        auth_token = request.data.get('access_token', None)
        backend = request.data.get('backend', None)

        if auth_token and backend:
            try:
                user = auth_by_token(request, backend)
            except Exception as err:
                return Response(str(err), status=400)
            if user:
                strategy = load_strategy(request=request)
                token, created = Token.objects.get_or_create(user=user)
                return Response({'key': token.key})
            else:
                return Response("Bad Credentials", status=403)
        else:
            return Response("Bad request", status=400)
Example #46
0
 def get(self, request, *args, **kwargs):
     from social.apps.django_app.utils import load_backend, load_strategy
     complete_url = reverse('social:complete', args=('saml', ))
     saml_backend = load_backend(
         load_strategy(request),
         'saml',
         redirect_uri=complete_url,
     )
     try:
         metadata, errors = saml_backend.generate_metadata_xml()
     except Exception as e:
         logger.exception('unable to generate SAML metadata')
         errors = e
     if not errors:
         return HttpResponse(content=metadata, content_type='text/xml')
     else:
         return HttpResponse(content=str(errors), content_type='text/plain')
Example #47
0
    def post(self, request):
        serializer = self.social_serializer(data=request.DATA,
                                            files=request.FILES)

        if serializer.is_valid():
            backend = serializer.data['backend']
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        strategy = load_strategy(request=request, backend=backend)
        try:
            kwargs = dict({(k, i)
                           for k, i in serializer.data.items()
                           if k != 'backend'})
            user = request.user
            kwargs['user'] = user.is_authenticated() and user or None
            user = strategy.backend.do_auth(**kwargs)
        except AuthAlreadyAssociated:
            data = {
                'error_code': 'social_already_accociated',
                '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)

        _do_login(strategy, user)

        if not self.user_serializer:
            msg = 'SocialAuthView.user_serializer should be a serializer.'
            raise ImproperlyConfigured(msg)
        serializer = self.user_serializer(user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #48
0
def social_register(request):
    auth_token = request.data.get('access_token', None)
    backend = request.data.get('backend', None)
    if auth_token and backend:
        try:
            user = auth_by_token(request, backend)
        except Exception, err:
            return Response(str(err), status=400)
        if user:
            uri = ''
            strategy = load_strategy(request)
            backend = load_backend(strategy, backend, uri)
            _do_login(backend , user, strategy)

            return Response( "User logged in", status=status.HTTP_200_OK )
        else:
            return Response("Bad Credentials", status=403)
Example #49
0
 def api_request(self, url, params={}, refresh=True):
     s = self.get_social_auth()
     params.update({"format": "json"})
     params.update({"access_token": s.access_token})
     r = requests.get("https://ion.tjhsst.edu/api/{}".format(url),
                      params=params)
     if r.status_code == 401:
         if refresh:
             try:
                 self.get_social_auth().refresh_token(load_strategy())
             except:
                 client.captureException()
             return self.api_request(url, params, False)
         else:
             client.captureMessage("Ion API Request Failure: {} {}".format(
                 r.status_code, r.json()))
     return r.json()
Example #50
0
def sync_youtube_videos(userobj=None):
    playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None).\
        filter(youtube_last_err=None)
    playlist_users = Playlist.objects.exclude(youtube_pl_id__exact=None)
    if userobj:
        playlist_users = playlist_users.filter(user=userobj)

    for user_items in playlist_users:
        userobj = user_items.user.social_auth.get(provider='google-oauth2')
        credentials = AccessTokenCredentials(
            userobj.extra_data.get('access_token'),  'friendlyvibe/1.0')
        youtube = build(
            'youtube', 'v3', http=credentials.authorize(httplib2.Http()))

        for plitem in user_items.playlistitem_set.filter(youtube_synced=None):
            video_add = {}
            try:
                video_add = youtube.playlistItems().insert(
                    part="snippet",
                    body=dict(
                        snippet=dict(
                            playlistId=user_items.youtube_pl_id,
                            resourceId=dict(
                                kind='youtube#video',
                                videoId=plitem.item_obj.source_identifier
                            ),
                            position=0
                        )
                    )
                ).execute()
            except AccessTokenCredentialsError, e:
                # refresh the token
                strategy = load_strategy(backend='google-oauth2')
                userobj.refresh_token(strategy)
            except Exception, e:
                # record the error so next time we won't attempt to send it
                plitem.playlist_obj.youtube_last_err = str(e)
                plitem.playlist_obj.save()

            # make a note of the successfull answer
            if video_add.get('id'):
                plitem.youtube_synced = True
                plitem.youtube_data = simplejson.dumps(video_add)
                plitem.youtube_synced = datetime.datetime.now()
                plitem.save()
    def authenticate(self, request):
        """
        Returns two-tuple of (user, token) if authentication succeeds,
        or None otherwise.
        """
        auth_header = get_authorization_header(request).decode(
            HTTP_HEADER_ENCODING)
        auth = auth_header.split()

        if not auth or auth[0].lower() != 'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid token header. No backend provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) == 2:
            msg = 'Invalid token header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 3:
            msg = 'Invalid token header. Token string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        token = auth[2]
        backend = auth[1]

        strategy = load_strategy(request=request)

        try:
            backend = load_backend(
                strategy, backend,
                reverse(SOCIAL_AUTH_NAMESPACE + ':complete', args=(backend, )))
        except MissingBackend:
            msg = 'Invalid token header. Invalid backend.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = backend.do_auth(access_token=token)
        except requests.HTTPError as e:
            msg = e.response.text
            raise exceptions.AuthenticationFailed(msg)

        if not user:
            msg = 'Bad credentials.'
            raise exceptions.AuthenticationFailed(msg)
        return user, token
    def post(self, request):
        serializer = self.social_serializer(data=request.DATA,
                                            files=request.FILES)

        if serializer.is_valid():
            backend = serializer.data['backend']
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        strategy = load_strategy(request=request, backend=backend)
        try:
            kwargs = dict({(k, i) for k, i in serializer.data.items()
                          if k != 'backend'})
            user = request.user
            kwargs['user'] = user.is_authenticated() and user or None
            user = strategy.backend.do_auth(**kwargs)
        except AuthAlreadyAssociated:
            data = {
                'error_code': 'social_already_accociated',
                '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)

        _do_login(strategy, user)

        if not self.user_serializer:
            msg = 'SocialAuthView.user_seriliser should be a serializer.'
            raise ImproperlyConfigured(msg)
        serializer = self.user_serializer(user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #53
0
	def _authenticate_with_facebook(self, request):
		# WARNING! not rest_framework.Request, nor django.Request
		# but oauthlib.oauth.common.Request
		fb_token = getattr(request, 'fb_token', None)
		if not fb_token:
			return None
		strategy = load_strategy(backend='facebook')
		user = FacebookBackend(strategy=strategy).do_auth(fb_token)

		if user and user.is_active:
			f_uid = UserSocialAuth.objects.values('uid').get(user_id=user.pk)['uid']
			img = FACEBOOK_IMG_URL % f_uid

			if user.img != img:
				user.img = img
				user.save()

		return user
Example #54
0
    def post(self, request, *args, **kwargs):
        """

        :param request:here we get post request with access token
        :return:this function use that access token and authenticate with backend and create a user
                and return response code 201 for created

        """
        try:
            provider = 'google-oauth2'
            authed_user = request.user if not request.user.is_anonymous else None

            strategy = load_strategy(request)

            backend = load_backend(strategy=strategy,
                                   name=provider,
                                   redirect_uri=None)

            if isinstance(backend, BaseOAuth1):

                token = {
                    'oauth_token': request.data['access_token'],
                    'oauth_token_secret': request.data['access_token_secret'],
                }
            elif isinstance(backend, BaseOAuth2):

                token = request.data['access_token']
            try:
                user = backend.do_auth(token, user=authed_user)
            except AuthAlreadyAssociated:

                return Response(
                    {"errors": "That social media account is already in use"},
                    status=status.HTTP_400_BAD_REQUEST)

            if user and user.is_active:
                return Response('logged in', status=status.HTTP_201_CREATED)
            else:
                return Response({"errors": "Error with social authentication"},
                                status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            smd = Smd_Response()
            return smd
Example #55
0
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.DATA,
                                         files=request.FILES)

        if serializer.is_valid():
            self.pre_save(serializer.object)
            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 = load_strategy(request)
            backend = load_backend(strategy=strategy,
                                   name=provider,
                                   redirect_uri=None)

            if isinstance(backend, BaseOAuth1):
                token = {
                    'oauth_token': request.DATA['access_token'],
                    'oauth_token_secret': request.DATA['access_token_secret'],
                }
            elif isinstance(backend, BaseOAuth2):
                token = request.DATA['access_token']

            user = backend.do_auth(token, user=authed_user)
            serializer.object = user

            if user and user.is_active:
                if not authed_user and request.DATA['password']:
                    password = base64.decodestring(request.DATA['password'])
                    user.set_password(password)
                    user.save()
                self.post_save(serializer.object, created=True)
                headers = self.get_success_headers(serializer.data)
                return Response(serializer.data,
                                status=status.HTTP_201_CREATED,
                                headers=headers)
            else:
                return Response({"errors": "Error with social authentication"},
                                status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #56
0
    def post(self, request):

        from social.apps.django_app.utils import load_strategy
        from urllib2 import unquote

        strategy = load_strategy()
        uid      = request.POST.get('uid')
        provider = request.POST.get('provider')
        details  = json.loads(unquote(request.DATA.get('details')))
        response = json.loads(unquote(request.DATA.get('response')))

        try:
            social = UserSocialAuth.objects.get(provider=provider,uid=uid)
            return Response(user_dict(social.user))
        except UserSocialAuth.DoesNotExist:
            manager = SocialAuthManager(provider, uid, details)
            if manager.user.pk:
                profile = profile_activation(manager.user)
            manager_data = manager.is_valid()
            return Response(user_dict(manager.user))
Example #57
0
    def __crest(self):
        """
        Helper function to occasionally refresh the access token whenever it
        expires.
        """

        provider = self.social_auth.get(provider='eveonline')

        difference = (datetime.strptime(provider.extra_data['expires'],
                                        "%Y-%m-%dT%H:%M:%S") -
                      datetime.now()).total_seconds()

        if difference < 10:
            provider.refresh_token(load_strategy())
            expiry = datetime.now() + timedelta(seconds=1200)
            provider.extra_data['expires'] = expiry.strftime(
                "%Y-%m-%dT%H:%M:%S")
            provider.save()

        return provider.extra_data
Example #58
0
def social_sign_up(request):
    data = {}
    status = 400
    try:
        provider = request.data['provider']
        a_user = request.user if not request.user.is_anonymous() else None
        strategy = load_strategy(request)
        backend = load_backend(strategy=strategy,
                               name=provider,
                               redirect_uri=None)
        if isinstance(backend, BaseOAuth1):
            access_token = {
                'oauth_token': request.data['access_token'],
                'oauth_token_secret': request.data['access_token_secret'],
            }
        else:
            # We assume that if our backend is not instance of BaseOAuth1,
            # it is instance of BaseOAuth2
            access_token = request.data['access_token']

        user = backend.do_auth(access_token, user=a_user)

        if user and user.is_active:
            social = user.social_auth.get(provider=provider)
            if social.extra_data['access_token']:
                social.extra_data['access_token'] = access_token
                social.save()

        login(request, user)
        token = Token.objects.get(user=user)
        data = {'username': user.username, 'id': user.id, 'token': token.key}
        status = 200

    except KeyError as k:
        data['detail'] = ['{} parameter is missed'.format(k)]

    except Exception as exc:
        data['detail'] = [str(exc)]
    finally:
        return Response(data, status=status)