Authenticates using the given *authenticate*, retrying if the token needs
    to be replaced.
428115
def try_replace_token(authenticate, **kwargs):
    

    try:
        return authenticate(**kwargs)
    except errors.BinstarError as err:
        if kwargs.get('fail_if_already_exists') and len(err.args) > 1 and err.args[1] == 400:
            logger.warning('It appears you are already logged in from host %s' % socket.gethostname())
            logger.warning('Logging in again will remove the previous token. (This could cause troubles with virtual '
                           'machines with the same hostname)')
            logger.warning('Otherwise you can login again and specify a different hostname with "--hostname"')

            if bool_input("Would you like to continue"):
                kwargs['fail_if_already_exists'] = False
                return authenticate(**kwargs)

        raise
418219
def authenticate(self, reauth=False):
        
        auth_url = BASE_URL + "/rest/user"
        payload = {'email': self.email, 'password': self.password}
        arequest = requests.get(auth_url, params=payload)
        status = arequest.status_code
        if status != 200:
            if reauth:
                _LOGGER.error("Reauthentication request failed. " + status)
            else:
                _LOGGER.error("Authentication request failed, please check credintials. " + status)
        self.token = arequest.json().get('usertoken')
        if reauth:
            _LOGGER.info("Reauthentication was successful, token updated.")
        else:
            _LOGGER.info("Authentication was successful, token set.")
1046467
def authenticate():
        """"""
        key = PyGraphistry.api_key()
        #Mocks may set to True, so bypass in that case
        if (key is None) and PyGraphistry._is_authenticated == False:
            util.error('API key not set explicitly in `register()` or available at ' + EnvVarNames['api_key'])
        if not PyGraphistry._is_authenticated:
            PyGraphistry._check_key_and_version()
            PyGraphistry._is_authenticated = True
470706
def authenticate(cls, request, route, server_config):
        
        if not server_config.getboolean("auth", False):
            return

        user = server_config.get("user", "").strip()
        password = server_config.get("password", "").strip()

        if len(user) == 0:
            return

        if "AUTHORIZATION" in request.headers:
            if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
                return

        log.error("Invalid auth. Username should %s", user)

        response = Response(request=request, route=route)
        response.set_status(401)
        response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
        # Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
        # this happen only for the first query send by the client.
        response.force_close()
        return response
834246
function authenticateClient (req, res, next) {
  Client.authenticate(req, function (err, client) {
    if (err) { return next(err) }
    req.client = client
    next()
  })
}
28722
def authenticate(self, retries=3):
        

        username = self.username or self._getuser(self.base)
        password = self.password

        while retries > 0:
            if password is None:
                password = self._getpass(self.base, username)

            try:
                resp = self.post(self.base+'/authenticate', params={'username': username, 'password': password})

                schema = UserSchema()
                u = self.decode(schema, resp)

                if u.token is not None:
                    self.lock.acquire()
                    self.token = u.token
                    self.lock.release()
                    break
            except CDRouterError as cde:
                password = None
                retries -= 1
                if retries == 0:
                    raise cde

        return self.token
899761
public Account authenticate(AuthenticationToken authenticationToken) {

        if (accountCache != null) {
            Account account = accountCache.getIfPresent(authenticationToken);
            if (account != null) {
                return account;
            }
        }

        Account authenticatedAccount = null;
        for (Realm realm : allRealms) {
            if (realm.canAuthenticate(authenticationToken)) {
                Account account = realm.authenticate(authenticationToken);
                if (account != null && !account.isDisabled()) {
                    // create a sanitized copy of this account
                    authenticatedAccount = new Account(account.getName(), account.getCredentials().sanitize());
                    break;
                }
            }
        }

        // no authentication
        if (authenticatedAccount == null) {
            return null;
        }

        // aggregate metadata, roles, & permissions
        final Account aggregateAccount = authenticatedAccount;
        allRealms.stream()
                .filter(realm -> realm.hasAccount(aggregateAccount.getUsername()))
                .map(realm -> realm.getAccount(aggregateAccount.getUsername()))
                .filter(account -> account.isEnabled())
                .forEach(account -> {
                    if (Strings.isNullOrEmpty(aggregateAccount.getName())) {
                        aggregateAccount.setName(account.getName());
                    }
                    aggregateAccount.addEmailAddresses(account.getEmailAddresses());
                    aggregateAccount.addTokens(account.getTokens());
                    aggregateAccount.getAuthorizations()
                            .addRoles(account.getAuthorizations().getRoles())
                            .addPermissions(account.getAuthorizations().getPermissions());
                });

        if (accountCache != null) {
            // cache this assembled account
            accountCache.put(authenticationToken, aggregateAccount);
        }

        return aggregateAccount;
    }
172645
def authenticate(self, request, url_auth_token=None):
        
        try:
            return self.parse_token(url_auth_token)
        except TypeError:
            backend = "%s.%s" % (self.__module__, self.__class__.__name__)
            logger.exception("TypeError in %s, here's the traceback before "
                             "Django swallows it:", backend)
            raise
1429
@Override
    public Subject authenticate(@Sensitive byte[] tokenBytes) throws AuthenticationException {
        AuthenticationData authenticationData = createAuthenticationData(tokenBytes);
        return authenticationService.authenticate(jaasEntryName, authenticationData, null);
    }
1356614
function Authenticate() {
		$response = $this->MakeAPICall("POST", "session");
		
		if ($response['success']) {
			$this->last_token = $response['results'][0]['AuthToken'];
			$this->last_token_expire = $response['results'][0]['Expires'];
			
			if ($this->cache) {
				$this->cache->set($this->cache_prefix . 'authtoken', $this->last_token, 86400);
			}
			
			if ( is_callable($this->access_change_callback) ) {
				call_user_func($this->access_change_callback, 'api', array('auth_token' => $this->last_token) );
			}
			
			return true;
		}
		
		return false;
	}
367498
def authenticate(self, credentials):
        
        auth.authenticate(credentials, self)
        self.authset.add(credentials)
711477
def _authenticate(self):
        """"""
        self.cleanup_headers()
        url = LOGIN_ENDPOINT
        data = self.query(
            url,
            method='POST',
            extra_params={
                'email': self.__username,
                'password': self.__password
            })

        if isinstance(data, dict) and data.get('success'):
            data = data.get('data')
            self.authenticated = data.get('authenticated')
            self.country_code = data.get('countryCode')
            self.date_created = data.get('dateCreated')
            self.__token = data.get('token')
            self.userid = data.get('userId')

            # update header with the generated token
            self.__headers['Authorization'] = self.__token
415768
def _authenticate(self):
        
        for authenticator in self.authenticators:
            try:
                user_auth_tuple = authenticator.authenticate(self)
            except exceptions.APIException:
                self._not_authenticated()
                raise

            if user_auth_tuple is not None:
                self._authenticator = authenticator
                self.user, self.auth = user_auth_tuple
                return

        self._not_authenticated()
1187881
def authenticate_identify(self, api_token, override=True):
        
        if (self.context.has_auth_params('Gem-Identify') and not override):
            raise OverrideError('Gem-Identify')

        if (not api_token or
            not self.context.authorize('Gem-Identify', api_token=api_token)):
            raise AuthUsageError(self.context, 'Gem-Identify')

        return True
355138
def authenticated(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        self = args[0]
        if self.refresh_token is not None and \
           self.token_expiration_time <= dt.datetime.utcnow():
            self.re_authenticate()
        return func(*args, **kwargs)
    return wrapper
1315183
def authenticate(self):
        """"""
        if self.apiKey:
            return
        loginResponse = self._curl_bitmex(
            api="user/login",
            postdict={'email': self.login, 'password': self.password, 'token': self.otpToken})
        self.token = loginResponse['id']
        self.session.headers.update({'access-token': self.token})
406434
async function authenticate(database) {
    database[AUTH_RETRIES] = database[AUTH_RETRIES] || 0;

    try {
      await database.authenticate();
    } catch (e) {
      if (e.name !== 'SequelizeConnectionRefusedError') throw e;
      if (app.model[AUTH_RETRIES] >= 3) throw e;

      // sleep 2s to retry, max 3 times
      database[AUTH_RETRIES] += 1;
      app.logger.warn(`Sequelize Error: ${e.message}, sleep 2 seconds to retry...`);
      await sleep(2000);
      await authenticate(database);
    }
  }