Re-authenticate using the refresh token if available.
        Otherwise log in using the username and password
        if it was used to authenticate initially.

        :return: The authentication response or `None` if not available
178257
def refresh_session(self):
        

        if not self._refresh_token:
            if self._username and self._password:
                return self.login(self._username, self._password)

            return

        return self._authenticate(
            grant_type='refresh_token',
            refresh_token=self._refresh_token,
            client_id=self._client_id,
            client_secret=self._client_secret
        )
332774
def resolve(self, authorization: http.Header):
        
        if authorization is None:
            return None

        scheme, token = authorization.split()
        if scheme.lower() != 'basic':
            return None

        username, password = base64.b64decode(token).decode('utf-8').split(':')
        user = authenticate(username=username, password=password)

        return user
903098
def rebuild_auth(self, prepared_request, response):
        
        headers = prepared_request.headers
        url = prepared_request.url

        if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):
            # If we get redirected to a new host, we should strip out any
            # authentication headers.
            del headers['Authorization']

        # .netrc might have more auth for us on our new host.
        new_auth = get_netrc_auth(url) if self.trust_env else None
        if new_auth is not None:
            prepared_request.prepare_auth(new_auth)

        return
1057337
def refresh_token(self, **kwargs):
        
        if 'client_secret' not in kwargs:
            kwargs.update(client_secret=self.client_secret)
        if 'client_id' not in kwargs:
            kwargs.update(client_id=self.client_id)
        return self.session.refresh_token(token_url, **kwargs)
850253
def authenticate(self):
        """"""
        if self.__token:
            try:
                resp = self._refresh_token()
            except exceptions.TVDBRequestException as err:
                # if a 401 is the cause try to login
                if getattr(err.response, 'status_code', 0) == 401:
                    resp = self._login()
                else:
                    raise
        else:
            resp = self._login()

        self.__token = resp.get('token')
        self._token_timer = timeutil.utcnow()
196459
def _do_refresh_request(self, unused_http_request):
        
        relative_url = 'instance/service-accounts/{0}/token'.format(
            self.__service_account_name)
        try:
            response = _GceMetadataRequest(relative_url)
        except exceptions.CommunicationError:
            self.invalid = True
            if self.store:
                self.store.locked_put(self)
            raise
        content = response.read()
        try:
            credential_info = json.loads(content)
        except ValueError:
            raise exceptions.CredentialsError(
                'Could not parse response as JSON: %s' % content)

        self.access_token = credential_info['access_token']
        if 'expires_in' in credential_info:
            expires_in = int(credential_info['expires_in'])
            self.token_expiry = (
                datetime.timedelta(seconds=expires_in) +
                datetime.datetime.utcnow())
        else:
            self.token_expiry = None
        self.invalid = False
        if self.store:
            self.store.locked_put(self)
647791
def access_token(self) -> str:
        
        if self._token_expires_at < time.time() + self._REFRESH_THRESHOLD:
            self.request_token()

        return self._token["access_token"]
996233
def re_login?(e)
      auth_error =
        (e.response_code == 403 && e.message =~ %r(.*cookie is expired or invalid)) ||
        e.response_code == 401

      renewable_creds =
        (@instance_token || (@email && (@password || @password_base64)) || @refresh_token)

      auth_error && renewable_creds
    end
1001695
def authenticate_using_session
    return if current_user
    session_uid = session[:authpwn_suid]
    user = session_uid && Tokens::SessionUid.authenticate(session_uid)
    self.current_user = user if user && !user.instance_of?(Symbol)
  end
512960
def authenticate(self):
        
        if self._auth_token is None or self._token_expiry < time.time():
            self._perform_auth()

        yield self._auth_token
281316
def authenticate(user=None):  # noqa: E501
    
    if connexion.request.is_json:
        user = UserAuth.from_dict(connexion.request.get_json())  # noqa: E501

    credentials = mapUserAuthToCredentials(user)
    auth = ApitaxAuthentication.login(credentials)
    if(not auth):
        return ErrorResponse(status=401, message="Invalid credentials")

    access_token = create_access_token(identity={'username': user.username, 'role': auth['role']})
    refresh_token = create_refresh_token(identity={'username': user.username, 'role': auth['role']})

    return AuthResponse(status=201, message='User ' + user.username + ' was authenticated as ' + auth['role'], access_token=access_token, refresh_token=refresh_token, auth=UserAuth(username=auth['credentials'].username, api_token=auth['credentials'].token))
719938
def refresh_authorization(self):
        
        response = self.request_handler.post(
            endpoint='oauth/token',
            omit_api_version=True,
            data={
                'grant_type': 'refresh_token',
                'client_id': self.auth.client_id,
                'client_secret': self.auth.client_secret,
                'refresh_token': self.auth.refresh_token,
            }
        )
        data = response.json()
        token_expiration = (datetime.datetime.utcnow() + datetime.timedelta(seconds=data['expires_in']))
        self.auth.update(
            token_expiration=token_expiration,
            access_token=data['access_token'],
            refresh_token=data['refresh_token'],
        )
        return {
            'access_token': self.auth.access_token,
            'refresh_token': self.auth.refresh_token,
            'token_expiration': format_event_time(self.auth.token_expiration),
        }
471789
def authenticate(self, req, resp, resource):
        
        payload = self._decode_jwt_token(req)
        user = self.user_loader(payload)
        if not user:
            raise falcon.HTTPUnauthorized(
                description='Invalid JWT Credentials')

        return user
154107
def refresh_token(self, refresh_token, **kwargs):
        
        return self._token_request(grant_type='refresh_token',
                                   refresh_token=refresh_token, **kwargs)
709779
def verify_refresh_token(self, expired_token) -> bool:
        
        try:
            decoded_token = jwt.decode(
                Security.decrypt(expired_token),
                self.app_secret,
                options={'verify_exp': False})
            if 'refresh_token' in decoded_token and \
                    decoded_token['refresh_token'] is not None:
                try:
                    jwt.decode(decoded_token['refresh_token'], self.app_secret)
                    self.data = decoded_token
                    return True
                except (Exception, BaseException) as error:
                    self.errors.append(error)
                    return False
        except (Exception, BaseException) as error:
            self.errors.append(error)
            return False
        return False
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))
1248356
def _refresh_token(self):
        

        # use basic auth with API key and secret
        client_auth = requests.auth.HTTPBasicAuth(self.api_key, self.api_secret)

        # make request
        post_data = {"grant_type": "client_credentials"}
        response = requests.post(self.auth, auth=client_auth, data=post_data, proxies=self.proxies)
        self.last_response = response

        # raise exception if status code indicates an error
        if 400 <= response.status_code < 600:
            message = "{} {} Error (Trace-Id: {}): {}".format(response.status_code,
                                                              "Client" if response.status_code < 500 else "Server",
                                                              self._get_trace_id(response),
                                                              "unable to get token")
            raise HTTPError(message, response=response)

        # set token property to the received token
        self.token = response.json()["access_token"]