let's auth the user to the Service
            :param request: request object
            :return: callback url
            :rtype: string that contains the url to redirect after auth
558185
def auth(self, request):
        
        request_token = super(ServiceTrello, self).auth(request)
        callback_url = self.callback_url(request)

        # URL to redirect user to, to authorize your app
        auth_url_str = '{auth_url}?oauth_token={token}'
        auth_url_str += '&scope={scope}&name={name}'
        auth_url_str += '&expiration={expiry}&oauth_callback={callback_url}'
        auth_url = auth_url_str.format(auth_url=self.AUTH_URL,
                                       token=request_token['oauth_token'],
                                       scope=self.scope,
                                       name=self.app_name,
                                       expiry=self.expiry,
                                       callback_url=callback_url)

        return auth_url
1145571
def begin_auth(request):
    
    # Instantiate Twython with the first leg of our trip.
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET)

    # Request an authorization url to send the user to...
    callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks'))
    auth_props = twitter.get_authentication_tokens(callback_url)

    # Then send them over there, durh.
    request.session['request_token'] = auth_props

    request.session['next_url'] = request.GET.get('next',None)
    
    return HttpResponseRedirect(auth_props['auth_url'])
1153205
def get_connect_redirect_url(self, request, socialaccount):
        
        assert request.user.is_authenticated
        url = reverse('socialaccount_connections')
        return url
129003
def post_url(self, url, form):
        
        _r = self.br.open(url, form.click_request_data()[1])

        # check that we've not been redirected to the login page or an error occured
        if self.br.geturl().startswith(self.AUTH_URL):
            raise AuthRequiredException
        elif self.br.geturl().startswith(self.ERROR_URL):
            raise RequestErrorException
        else:
            return _r.read()
587481
def request(self, method, url, **kwargs):
        ""
        user_token = kwargs.pop('token', self.token)
        token, _ = self.parse_raw_token(user_token)
        if token is not None:
            params = kwargs.get('params', {})
            params['access_token'] = token
            kwargs['params'] = params
        return super(OAuth2Client, self).request(method, url, **kwargs)
281165
def make_request(self, url, params, auth=None):
        
        req = urllib2.Request(url + urllib.urlencode(params))

        if auth:
            req.add_header('AUTHORIZATION', 'Basic ' + auth)

        return urllib2.urlopen(req)
939668
def renew_service(request, pk):
    
    default_provider.load_services()
    service = get_object_or_404(ServicesActivated, pk=pk)
    service_name = str(service.name)
    service_object = default_provider.get_service(service_name)
    lets_auth = getattr(service_object, 'auth')
    getattr(service_object, 'reset_failed')(pk=pk)
    return redirect(lets_auth(request))
332776
def begin(request, provider):
    
    # store url to where user will be redirected
    request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL

    # start the authentication process
    backend = get_backend(provider)
    return backend.begin(request, dict(request.REQUEST.items()))
590506
function (auth, request, done) {
        var header,
            params = auth.get(AUTH_PARAMETERS),
            url = urlEncoder.toNodeUrl(request.url.toString(true));

        if (!params.username || !params.realm) {
            return done(); // Nothing to do if required parameters are not present.
        }

        request.removeHeader(AUTHORIZATION, {ignoreCase: true});

        params.method = request.method;
        params.uri = url.path;
        params.body = request.body && request.body.toString();

        try {
            header = this.computeHeader(params);
        }
        catch (e) { return done(e); }

        request.addHeader({
            key: AUTHORIZATION,
            value: header,
            system: true
        });

        return done();
    }
200072
def callback_url(self, request):
        
        service = self.service.split('Service')[1].lower()
        return_to = '{service}_callback'.format(service=service)
        return '%s://%s%s' % (request.scheme, request.get_host(), reverse(return_to))
713323
def logout(request):
    
    auth_logout(request)
    info(request, _("Successfully logged out"))
    return redirect(next_url(request) or get_script_prefix())
579
def login(self, request):
        
        try:
            user = authenticate(request)

            if not user:
                raise AuthenticationFailed("User not authenticated.")

            if not user.is_active:
                raise AuthenticationFailed("This user has been disabled.")

            login(request, user)

            return Response(UserSerializer(user).data)
        except AuthError as ex:
            # This indicates an error that may require attention by the
            # Treeherder or Taskcluster teams.  Logging this to New Relic to
            # increase visibility.
            newrelic.agent.record_exception()
            logger.exception("Error", exc_info=ex)
            raise AuthenticationFailed(str(ex))
873498
def get_request(self, request):
        """"""
        request.headers['authenticate'] = {
            'username': self.username,
            'apiKey': self.api_key,
        }
        return request
66410
def authenticate(self, request):
        
        access_token = self.get_access_token(request)

        if not access_token:
            return None

        try:
            user = self.backend.get_or_create_user(access_token, None, None)
        except HTTPError as exc:
            resp = exc.response

            # if the oidc provider returns 401, it means the token is invalid.
            # in that case, we want to return the upstream error message (which
            # we can get from the www-authentication header) in the response.
            if resp.status_code == 401 and 'www-authenticate' in resp.headers:
                data = parse_www_authenticate_header(resp.headers['www-authenticate'])
                raise exceptions.AuthenticationFailed(data['error_description'])

            # for all other http errors, just re-raise the exception.
            raise
        except SuspiciousOperation as exc:
            LOGGER.info('Login failed: %s', exc)
            raise exceptions.AuthenticationFailed('Login failed')

        if not user:
            msg = 'Login failed: No user found for the given access token.'
            raise exceptions.AuthenticationFailed(msg)

        return user, access_token
1314861
def callback(self, request, **kwargs):
        
        access_token = request.session['oauth_token'] + "#TH#"
        access_token += str(request.session['oauth_id'])
        kwargs = {'access_token': access_token}
        return super(ServiceGithub, self).callback(request, **kwargs)
1114522
async def login(self, client_name, request, redirect_uri=None, **params):
        
        client = self.client(client_name, logger=self.app.logger)

        redirect_uri = redirect_uri or self.cfg.redirect_uri or '%s://%s%s' % (
            request.scheme, request.host, request.path)
        session = await self.app.ps.session(request)

        if isinstance(client, OAuth1Client):
            oauth_verifier = request.query.get('oauth_verifier')
            if not oauth_verifier:

                # Get request credentials
                token, secret = await client.get_request_token(
                    oauth_callback=redirect_uri)

                # Save the credentials in current user session
                session['oauth_token'] = token
                session['oauth_token_secret'] = secret

                url = client.get_authorize_url()
                raise muffin.HTTPFound(url)

            # Check request_token
            oauth_token = request.query.get('oauth_token')
            if session['oauth_token'] != oauth_token:
                raise muffin.HTTPForbidden(reason='Invalid token.')

            client.oauth_token = oauth_token
            client.oauth_token_secret = session.get('oauth_token_secret')

            # Get access tokens
            return client, await client.get_access_token(oauth_verifier)

        if isinstance(client, OAuth2Client):
            code = request.query.get('code')
            if not code:

                # Authorize an user
                state = sha1(str(random()).encode('ascii')).hexdigest()
                session['oauth_secret'] = state
                url = client.get_authorize_url(
                    redirect_uri=redirect_uri, state=state, **params)
                raise muffin.HTTPFound(url)

            # Check state
            state = request.query.get('state')
            oauth_secret = session.pop('oauth_secret', '')
            if oauth_secret != state:
                raise muffin.HTTPForbidden(reason='Invalid token "%s".' % oauth_secret)

            # Get access token
            return client, await client.get_access_token(code, redirect_uri=redirect_uri)

        return client
1130411
def authenticate(self, request):
        
        authenticators = self._meta.authenticators

        if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:
            self.auth = AnonimousAuthenticator(self)
            return True

        error_message = "Authorization required."
        for authenticator in authenticators:
            auth = authenticator(self)
            try:
                if not auth.authenticate(request):
                    raise AssertionError(error_message)

                self.auth = auth
                auth.configure(request)
                return True
            except AssertionError, e:
                error_message = str(e)

        raise HttpError(error_message, status=status.HTTP_401_UNAUTHORIZED)