Authenticate the request dict
        
        :param dict request: request dict built from user input
        :raises SMCConnectionError: failure to connect
        :return: python requests session
        :rtype: requests.Session
776906
def _get_session(self, request):
        
        _session = requests.session()  # empty session
        
        response = _session.post(**request)
        logger.info('Using SMC API version: %s', self.api_version)
        
        if response.status_code != 200:
            raise SMCConnectionError(
                'Login failed, HTTP status code: %s and reason: %s' % (
                    response.status_code, response.reason))
        return _session
490895
def validate_request(self, request):
        
        token = get_token_from_header(request)
        return self.request_validator.validate_bearer_token(
            token, request.scopes, request)
659214
def get_jwt(self, request):
        
        try:
            authorization = request.authorization
        except ValueError:
            return None
        if authorization is None:
            return None
        authtype, token = authorization
        if authtype.lower() != self.auth_header_prefix.lower():
            return None
        return token
651854
def _get_authenticated_session(self):
        
        session = requests.Session()
        session.auth = self.auth
        return session
1340043
def process_request(self, request):
        
        # Initialize thread local storage
        threadlocal.auditlog = {
            'signal_duid': (self.__class__, time.time()),
            'remote_addr': request.META.get('REMOTE_ADDR'),
        }

        # In case of proxy, set 'original' address
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]

        # Connect signal for automatic logging
        if hasattr(request, 'user') and is_authenticated(request.user):
            set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid'])
            pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False)
1081404
def authenticate(self, request):
        
        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(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
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
1099270
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

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

        if len(auth) == 1:
            msg = _('Invalid basic header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid basic header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError):
            msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        return self.authenticate_credentials(userid, password)
709855
def request(self, request_path, data=None, do_authentication=True, is_json=True):
        
        uri = self.api_uri % request_path
        request = urllib2.Request(uri)

        # Build up the request
        if is_json:
            request.add_header("Content-Type", "application/json")
            if data is not None:
                request.add_data(json.dumps(data))
        elif data is not None:
            request.add_data(data)

        if do_authentication:
            if self.client_id is None or self.client_secret is None:
                raise Exception(u"You need to supply a client_id and client_secret to perform an authenticated request")
            basic_auth = base64.b64encode("%s:%s" % (self.client_id, self.client_secret))
            request.add_header("Authorization", "Basic %s" % basic_auth)

        try:
            response = self._make_request(request)
        except Exception as inst:
            raise # automatically re-raises the exception

        if 'status' in response:
            # Grab the status info if it exists
            self._last_status_code = response['status']['code']
            if 'message' in response['status']:
                self._last_status_message = response['status']['message']

            if 'data' in response:
                return response['data']

        return response
829904
def verify_request(self):
        
        if flask_request.method == 'POST':
            params = flask_request.form.to_dict()
        else:
            params = flask_request.args.to_dict()
        log.debug(params)
        log.debug('verify_request?')
        try:
            verify_request_common(self._consumers(), flask_request.url,
                                  flask_request.method, flask_request.headers,
                                  params)
            log.debug('verify_request success')

            # All good to go, store all of the LTI params into a
            # session dict for use in views
            for prop in LTI_PROPERTY_LIST:
                if params.get(prop, None):
                    log.debug("params %s=%s", prop, params.get(prop, None))
                    session[prop] = params[prop]

            # Set logged in session key
            session[LTI_SESSION_KEY] = True
            return True
        except LTIException:
            log.debug('verify_request failed')
            for prop in LTI_PROPERTY_LIST:
                if session.get(prop, None):
                    del session[prop]

            session[LTI_SESSION_KEY] = False
            raise
1101954
def get(self, request):
        
        try:
            client = request.session[self.get_client().get_session_key()]
            logger.debug("API returned: %s", request.GET)            
            client.complete(dict(request.GET.items()))
            request.session[self.get_client().get_session_key()] = client
            return HttpResponseRedirect(self.get_redirect())
        except KeyError:
            return self.error_to_response(request, {'error': "Session expired."})
        except OAuthError, error:
            return self.error_to_response(request, {'error': error})
        except socket.timeout:
            return self.error_to_response(request, {'error':
                _('Could not connect to service (timed out)')})
729943
def identify(self, request):
        
        try:
            authorization = request.authorization
        except ValueError:
            return NO_IDENTITY
        if authorization is None:
            return NO_IDENTITY
        authtype, params = authorization
        auth = parse_basic_auth(authtype, params)
        if auth is None:
            return NO_IDENTITY
        return Identity(userid=auth.username, password=auth.password)
485600
def authenticate(self, request, **credentials):
        
        username = credentials.get('username')
        password = credentials.get('password')
        login_server = credentials.get('login_server')
        port = credentials.get('port')

        user_model = get_user_model()
        try:
            user = user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            return None
        try:
            response = poplib.POP3_SSL(host=login_server, port=port)
            response.user(user=username)
            password_string = response.pass_(pswd=password)
            if b'OK' in password_string:
                response.quit()
                return user
        except poplib.error_proto:
            return None
        except (ValueError, TypeError) as e:
            raise e
1170777
def build_url_request(self):
        
        params = {}
        headers = {}
        self._authenticator(params, headers)
        self._grant(params)
        return Request(self._endpoint, urlencode(params), headers)
252144
def authenticated_session(username, password):
    
    session = requests.Session()
    session.headers.update(headers())

    response = session.get(url())
    login_path = path(response.text)
    login_url = urljoin(response.url, login_path)
    login_post_data = post_data(response.text, username, password)

    response = session.post(login_url, data=login_post_data)
    if response.headers['connection'] == 'close':
        raise Exception('Authencation failed')

    return session
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
945715
def process_request(self, request):
        
        token = request.GET.get(TOKEN_NAME)
        user = None if token is None else authenticate(url_auth_token=token)

        # If the sessions framework is enabled and the token is valid,
        # persist the login in session.
        if hasattr(request, 'session') and user is not None:
            login(request, user)
            # Once we persist the login in the session, if the authentication
            # middleware is enabled, it will set request.user in future
            # requests. We can get rid of the token in the URL by redirecting
            # to the same URL with the token removed. We only do this for GET
            # requests because redirecting POST requests doesn't work well. We
            # don't do this on Safari because it triggers the over-zealous
            # "Protection Against First Party Bounce Trackers" of ITP 2.0.
            if (
                hasattr(request, 'user') and
                request.method == 'GET' and
                not self.is_safari(request)
            ):
                return self.get_redirect(request)

        # If the authentication middleware isn't enabled, set request.user.
        # (This attribute is overwritten by the authentication middleware
        # if it runs after this one.)
        if not hasattr(request, 'user'):
            request.user = user if user is not None else AnonymousUser()