Check authentication and perform actual API request and relogin if needed
779756
def call(self, method, params=None):
        """"""
        start_time = time()
        self.check_auth()
        self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method)
        self.log(DEBUG, '\twith parameters: %s', params)

        try:
            return self.do_request(self.json_obj(method, params=params))
        except ZabbixAPIError as ex:
            if self.relogin_interval and any(i in ex.error['data'] for i in self.LOGIN_ERRORS):
                self.log(WARNING, 'Zabbix API not logged in (%s). Performing Zabbix API relogin', ex)
                self.relogin()  # Will raise exception in case of login error
                return self.do_request(self.json_obj(method, params=params))
            raise  # Re-raise the exception
        finally:
            self.log(INFO, '[%s-%05d] Zabbix API method "%s" finished in %g seconds',
                     start_time, self.id, method, (time() - start_time))
258671
function ensureValidJWTCookie(request) {
    const originalRequest = request;
    const isAuthUrl = authenticatedAPIClient.isAuthUrl(originalRequest.url);
    const accessToken = authenticatedAPIClient.getDecodedAccessToken();
    const tokenExpired = authenticatedAPIClient.isAccessTokenExpired(accessToken);
    if (isAuthUrl || !tokenExpired) {
      return request;
    }

    if (!queueRequests) {
      queueRequests = true;
      authenticatedAPIClient.refreshAccessToken()
        .then(() => {
          queueRequests = false;
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: true });
        })
        .catch((error) => {
          // If no callback is supplied frontend-auth will (ultimately) redirect the user to login.
          // The user is redirected to logout to ensure authentication clean-up, which in turn
          // redirects to login.
          if (authenticatedAPIClient.handleRefreshAccessTokenFailure) {
            authenticatedAPIClient.handleRefreshAccessTokenFailure(error);
          } else {
            authenticatedAPIClient.logout();
          }
          PubSub.publishSync(ACCESS_TOKEN_REFRESH, { success: false });
        });
    }

    return new Promise((resolve, reject) => {
      logInfo(`Queuing API request ${originalRequest.url} while access token is refreshed`);
      PubSub.subscribeOnce(ACCESS_TOKEN_REFRESH, (msg, { success }) => {
        if (success) {
          logInfo(`Resolving queued API request ${originalRequest.url}`);
          resolve(originalRequest);
        } else {
          reject(originalRequest);
        }
      });
    });
  }
644187
def relogin(self):
        """"""
        try:
            self.__auth = None  # reset auth before relogin
            self.login()
        except ZabbixAPIException as e:
            self.log(ERROR, 'Zabbix API relogin error (%s)', e)
            self.__auth = None  # logged_in() will always return False
            raise
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
406489
def do(self, params):
        """"""
        request_params = self.create_basic_params()
        request_params.update(params)
        response_data = self.request(request_params)
        try:
            format_json_data = self.format_response_data(response_data)
        # pylint: disable=broad-except
        except Exception:
            # Caused by server force logged out
            return None
        return_data = self.fix_error_data(format_json_data)
        try:
            self.check_login_status(return_data)
        except exceptions.NotLoginError:
            self.autologin()
        return return_data
461964
function checkCollabAuthenticated(req, res, next) {
		if (req.user) {
			req.user.workspaceDir = options.workspaceDir + (req.user.workspace ? "/" + req.user.workspace : "");
			next();
		} else if (req.headers['authorization'] && checkCollabServerToken(req.headers['authorization'])){
			next();
		} else {
			api.writeError(401, res, "Not authenticated");
		}
	}
887290
def _request_token(self, force=False):
        
        if self.login_data is None:
            raise RuntimeError("Don't have a token to refresh")

        if not force:
            if not self._requires_refresh_token():
                # no need to refresh as token is valid
                return True

        headers = {
            "Accept": "application/json",
            'Authorization':
                'Bearer ' + self.login_data['token']['accessToken']
        }

        url = self.api_base_url + "account/RefreshToken"

        response = requests.get(url, headers=headers, timeout=10)

        if response.status_code != 200:
            return False

        refresh_data = response.json()

        if 'token' not in refresh_data:
            return False

        self.login_data['token']['accessToken'] = refresh_data['accessToken']
        self.login_data['token']['issuedOn'] = refresh_data['issuedOn']
        self.login_data['token']['expiresOn'] = refresh_data['expiresOn']

        return True
450587
function(doRecentCheck, req, res, next) {
  var app = req.app;
  var config = app.loadConfig('auth');

  var failed = !req.isAuthenticated();
  if (!failed && doRecentCheck && !req.session.impersonated) {
    //skip recent check if login is impersonated
    //note: loginTime maybe a string since sessions are serialized as json
    failed = !req.session.loginTime ||
      !(new Date() - new Date(req.session.loginTime) <= config.recentLoginTimeoutSeconds*1000);
    if (failed) { //force reauthentication (e.g. for facebook login for example)
      req.session.reauthenticate  = true;
    }
  }

  // if user is not authenticated, redirect to login
  if (failed) {
    // remember original requested url
    req.session.returnTo = req.url;
    req.session.returnToMethod = req.method;
    req.flash('login.danger', req.session.reauthenticate ? 'You need to login again to access this page.' : 'You need to login to access this page.');
    res.redirect('/login');
    return;
  }

  if (config.requireEmailVerification
      && req.user && !req.user.local.verified) {
    if (config.requireEmailVerification == 'nag') {
      req.flash('warning', 'Please confirm your email address by clicking the link sent to <strong>'+ req.user.local.email +"</strong>.&nbsp;&nbsp;<a class='send-resend' href='#'>Resend confirmation email</a>.");
    } else if (config.requireEmailVerification == 'require') {
      // redirect to the email verification page
      req.session.returnTo = req.url;
      req.session.returnToMethod = req.method;
      res.redirect('/verification-required');
      return;
    }
  }

  return next();
}
752036
def authenticate(self):
        """"""
        endpoint = os.path.join(self.config.get('napps', 'api'), 'auth', '')
        username = self.config.get('auth', 'user')
        password = getpass("Enter the password for {}: ".format(username))
        response = requests.get(endpoint, auth=(username, password))
        if response.status_code != 201:
            LOG.error(response.content)
            LOG.error('ERROR: %s: %s', response.status_code, response.reason)
            sys.exit(1)
        else:
            data = response.json()
            KytosConfig().save_token(username, data.get('hash'))
            return data.get('hash')
388282
def auth(self):
        """"""
        response = requests.post(
            parse.urljoin(self.base_url, '/api/auth'),
            timeout=self.timeout,
            data={'username': self.username, 'password': self.password})
        response.raise_for_status()
        json = response.json()
        if 'jwt' not in json:
            raise ValueError("Not authorized: didn't receive token, check username or password.")
        self.jwt = json['jwt']
        return json
455542
def authenticate(self, api_key):
        """"""
        self._api_key = api_key

        # Attach auth to session.
        self._session.auth = ('', self._api_key)

        return self._verify_api_key()
124269
def process_request(self, request):
        """"""
        assert hasattr(request, 'user')
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(reverse(settings.LOGIN_URL))
1123680
def _require_authenticate(func):
    ''''''

    def wrapped(self):
        if not hasattr(self, 'authenticated'):
            self.authenticated = None
        if self.authenticated:
            return func(self)

        auth = self.headers.get(u'Authorization')
        if auth is None:
            msg = u"You are not allowed to access this page. Please login first!"
            return _error_401(self, msg)

        token, fields = auth.split(' ', 1)
        if token != 'Digest':
            return _error_401(self, 'Unsupported authentication type')

        # Check the header fields of the request.
        cred = parse_http_list(fields)
        cred = parse_keqv_list(cred)
        keys = u'realm', u'username', u'nonce', u'uri', u'response'
        if not all(cred.get(key) for key in keys):
            return _error_401(self, 'Incomplete authentication header')
        if cred['realm'] != self.server.realm:
            return _error_401(self, 'Incorrect realm')
        if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred):
            return _error_401(self, 'qop with missing nc or cnonce')

        # Check the username.
        username = cred['username']
        password = self.server.get_password(username)
        if not username or password is None:
            return _error_401(self, 'Invalid username or password')

        # Check the digest string.
        location = u'%s:%s' % (self.command, self.path)
        location = md5hex(location.encode('utf8'))
        pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password))

        if 'qop' in cred:
            info = (cred['nonce'],
                    cred['nc'],
                    cred['cnonce'],
                    cred['qop'],
                    location)
        else:
            info = cred['nonce'], location

        expect = u'%s:%s' % (pwhash, ':'.join(info))
        expect = md5hex(expect.encode('utf8'))
        if expect != cred['response']:
            return _error_401(self, 'Invalid username or password')

        # Success!
        self.authenticated = True
        return func(self)

    return wrapped
910122
def whoami(ctx, opts):
    """"""
    click.echo("Retrieving your authentication status from the API ... ", nl=False)

    context_msg = "Failed to retrieve your authentication status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            is_auth, username, email, name = get_user_brief()

    click.secho("OK", fg="green")
    click.echo("You are authenticated as:")
    if not is_auth:
        click.secho("Nobody (i.e. anonymous user)", fg="yellow")
    else:
        click.secho(
            "%(name)s (slug: %(username)s, email: %(email)s)"
            % {
                "name": click.style(name, fg="cyan"),
                "username": click.style(username, fg="magenta"),
                "email": click.style(email, fg="green"),
            }
        )
1055000
def do_authenticated_request(method, url, options = {})
      begin
        response = case client
                   when BasicAuthClient
                     self.class.send(method, api_url(url), options.merge(:basic_auth => client.credentials))
                   when OauthClient
                     # We have to wrap the result of the access_token request into an HTTParty::Response object
                     # to keep duck typing with HTTParty
                     result = client.send(method, api_url(url), options)
                     content_type = Parser.format_from_mimetype(result.content_type)
                     parsed_response = Parser.call(result.body, content_type)

                     HTTParty::Response.new(nil, result, lambda { parsed_response })
                   else
                     raise CredentialsMissing
                   end
        check_response_codes(response)
        response.parsed_response
      rescue Timeout::Error
        raise Unavailable.new('Service Unavailable')
      end
    end
890519
function authRequired (req, res, next) {
  if (!req.user) {
    req.session.oauth2return = req.originalUrl;
    return res.redirect('/login');
  }
  if (req.session.allowedDomain && req.session.allowedDomain !== req.user.domain) {
    return res.redirect('/login');
  }
  next();
}
1022736
def login_request(self, login_urls, is_retry=False):
        """"""
        try:
            login_url = login_urls.pop(0)
        except IndexError:
            _LOGGER.error("Could not login to blink servers.")
            return False

        _LOGGER.info("Attempting login with %s", login_url)

        response = api.request_login(self,
                                     login_url,
                                     self._username,
                                     self._password,
                                     is_retry=is_retry)
        try:
            if response.status_code != 200:
                response = self.login_request(login_urls)
            response = response.json()
            (self.region_id, self.region), = response['region'].items()

        except AttributeError:
            _LOGGER.error("Login API endpoint failed with response %s",
                          response,
                          exc_info=True)
            return False

        except KeyError:
            _LOGGER.warning("Could not extract region info.")
            self.region_id = 'piri'
            self.region = 'UNKNOWN'

        self._login_url = login_url
        return response