Authenticate against yubico server
170359
def auth(username, password):
    '''
    
    '''
    _cred = __get_yubico_users(username)

    client = Yubico(_cred['id'], _cred['key'])

    try:
        return client.verify(password)
    except yubico_exceptions.StatusCodeError as e:
        log.info('Unable to verify YubiKey `%s`', e)
        return False
111993
public function authenticate() {
    	
    	$userClass = new core_kernel_classes_Class(GenerisRdf::CLASS_GENERIS_USER);
    	$filters = array(GenerisRdf::PROPERTY_USER_LOGIN => $this->username);
    	$options = array('like' => false, 'recursive' => true);
    	$users = $userClass->searchInstances($filters, $options);
    	
    	
    	if (count($users) > 1){
    		// Multiple users matching
    		throw new common_exception_InconsistentData("Multiple Users found with the same login '".$this->username."'.");
    	}
        if (empty($users)){
            // fake code execution to prevent timing attacks
            $label = new core_kernel_classes_Property(OntologyRdfs::RDFS_LABEL);
            $hash = $label->getUniquePropertyValue($label);
            if (!core_kernel_users_Service::getPasswordHash()->verify($this->password, $hash)) {
                throw new core_kernel_users_InvalidLoginException();
            }
            // should never happen, added for integrity
    		throw new core_kernel_users_InvalidLoginException();
    	}
    	
	    $userResource = current($users);
	    $hash = $userResource->getUniquePropertyValue(new core_kernel_classes_Property(GenerisRdf::PROPERTY_USER_PASSWORD));
	    if (!core_kernel_users_Service::getPasswordHash()->verify($this->password, $hash)) {
	        throw new core_kernel_users_InvalidLoginException();
	    }
    	
    	return new core_kernel_users_GenerisUser($userResource);
    }
1259392
def authenticate(self):
        """"""
        valid = self._session_check()
        if self._is_authenticated and valid:
            self._log.debug("[!] User has already authenticated")
            return
        init = self._session.get(url=self.LOGIN_URL, headers=self.HEADERS)
        soup = BeautifulSoup(init.content, "html.parser")
        soup_login = soup.find('form').find_all('input')
        post_data = dict()
        for u in soup_login:
            if u.has_attr('name') and u.has_attr('value'):
                post_data[u['name']] = u['value']
        post_data['Email'] = self._email
        post_data['Passwd'] = self._password
        response = self._session.post(url=self.AUTH_URL, data=post_data,
                                      headers=self.HEADERS)
        if self.CAPTCHA_KEY in str(response.content):
            raise AccountCaptcha('Google is forcing a CAPTCHA. To get around this issue, run the google-alerts with the seed option to open an interactive authentication session. Once authenticated, this module will cache your session and load that in the future')
        cookies = [x.name for x in response.cookies]
        if 'SIDCC' not in cookies:
            raise InvalidCredentials("Email or password was incorrect.")
        with open(SESSION_FILE, 'wb') as f:
            cookies = requests.utils.dict_from_cookiejar(self._session.cookies)
            pickle.dump(cookies, f, protocol=2)
            self._log.debug("Saved session to disk for future reference")
        self._log.debug("User successfully authenticated")
        self._is_authenticated = True
        self._process_state()
        return
591052
def authenticate(self, driver):
        """"""
        #                      0                      1                    2                    3
        events = [driver.username_re, driver.password_re, self.device.prompt_re, driver.rommon_re,
                  #       4             5                   6                       7                8
                  driver.unable_to_connect_re, driver.authentication_error_re, pexpect.TIMEOUT, pexpect.EOF]

        transitions = [
            (driver.username_re, [0], 1, partial(a_send_username, self.username), 10),
            (driver.username_re, [1], 1, None, 10),
            (driver.password_re, [0, 1], 2, partial(a_send_password, self._acquire_password()),
             _C['first_prompt_timeout']),
            (driver.username_re, [2], -1, a_authentication_error, 0),
            (driver.password_re, [2], -1, a_authentication_error, 0),
            (driver.authentication_error_re, [1, 2], -1, a_authentication_error, 0),
            (self.device.prompt_re, [0, 1, 2], -1, None, 0),
            (driver.rommon_re, [0], -1, partial(a_send, "\r\n"), 0),
            (pexpect.TIMEOUT, [0], 1, partial(a_send, "\r\n"), 10),
            (pexpect.TIMEOUT, [2], -1, None, 0),
            (pexpect.TIMEOUT, [3, 7], -1, ConnectionTimeoutError("Connection Timeout", self.hostname), 0),
            (driver.unable_to_connect_re, [0, 1, 2], -1, a_unable_to_connect, 0),
        ]
        self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re)))
        fsm = FSM("CONSOLE-SERVER-AUTH", self.device, events, transitions, timeout=_C['connect_timeout'],
                  init_pattern=self.last_pattern)
        return fsm.run()
711031
def _authenticate_client(self, client, secret):
        
        client_s = str.join(':', [client, secret])
        credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
            'Authorization': 'Basic ' + credentials
            }
        params = {
            'client_id': client,
            'grant_type': 'client_credentials'
            }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate as %s" % (client))
            response.raise_for_status()
1341162
def authenticate_credentials(self, userid, password, request=None):
        """"""

        user = auth.authenticate(username=userid, password=password)

        if user is None or (user and not user.is_active):
            raise exceptions.AuthenticationFailed("Invalid username/password.")

        return (user, None)
14485
private function authenticate()
    {
        self::assertValidAuthType();

        $this->client
            ->getEmitter()
            ->attach(new $this->authenticators[$this->authType]($this));
    }
568997
def authenticate(self, username="", password="", **kwargs):
        """"""
        try:
            user = get_user_model().objects.filter(email__iexact=username)[0]
            if check_password(password, user.password):
                return user
            else:
                return None
        except IndexError:
            # No user was found, return None - triggers default login failed
            return None
1255189
public static function authenticate() {
    // If a client does't support cookies, they can use the X-TILMELDAUTH header
    // to provide the auth token.
    if (!empty($_SERVER['HTTP_X_TILMELDAUTH']) && empty($_COOKIE['TILMELDAUTH'])) {
      $fromAuthHeader = true;
      $authToken = $_SERVER['HTTP_X_TILMELDAUTH'];
    } elseif (!empty($_COOKIE['TILMELDAUTH'])) {
      $fromAuthHeader = false;
      $authToken = $_COOKIE['TILMELDAUTH'];
    } else {
      return false;
    }
    $setupUrlParts = parse_url(self::$config['setup_url']);
    $setupHost = $setupUrlParts['host'].
      (array_key_exists('port', $setupUrlParts) ? ':'.$setupUrlParts['port'] : '');
    if ($_SERVER['HTTP_HOST'] === $setupHost
        && $_SERVER['REQUEST_URI'] === $setupUrlParts['path']
      ) {
      // The request is for the setup app, so don't check for the XSRF token.
      $extract = self::$config['jwt_extract']($authToken);
    } else {
      // The request is for something else, so check for a valid XSRF token.
      if (empty($_SERVER['HTTP_X_XSRF_TOKEN'])) {
        return false;
      }

      $extract = self::$config['jwt_extract'](
          $authToken,
          $_SERVER['HTTP_X_XSRF_TOKEN']
      );
    }

    if (!$extract) {
      self::logout();
      return false;
    }
    $guid = $extract['guid'];
    $expire = $extract['expire'];

    $user = Nymph::getEntity(
        ['class' => '\Tilmeld\Entities\User'],
        ['&',
          'guid' => $guid
        ]
    );
    if (!$user || !$user->guid || !$user->enabled) {
      self::logout();
      return false;
    }

    if ($expire < time() + self::$config['jwt_renew']) {
      // If the user is less than renew time from needing a new token, give them
      // a new one.
      self::login($user, $fromAuthHeader);
    } else {
      self::fillSession($user);
    }
    return true;
  }
1253446
def authenticate(self):
        
        if request.headers.get('Authorization') or request.args.get('access_token'):
            realm = 'Bearer realm="%s", error="invalid_token"' % __package__
        else:
            realm = 'Bearer realm="%s"' % __package__
        resp = Response(None, 401, {'WWW-Authenticate': realm})
        abort(401, description='Please provide proper credentials', response=resp)
698677
def _authenticate(self):
        
        url = "{base_url}/api/authenticate".format(base_url=self._base_url())
        data = json.dumps({'username': self.username, "password": self.password})
        # Bypass authentication check in make_request by using _send_request
        logger.debug("Authenticating against NetMRI")
        self._send_request(url, method="post", data=data)
        self._is_authenticated = True
506848
def _authenticate_client(self, client):
        """"""
        if self.login and not self.restart_required:
            try:
                db = client[self.auth_source]
                if self.x509_extra_user:
                    db.authenticate(
                        DEFAULT_SUBJECT,
                        mechanism='MONGODB-X509'
                    )
                else:
                    db.authenticate(
                        self.login, self.password)
            except Exception:
                logger.exception(
                    "Could not authenticate to %r as %s/%s"
                    % (client, self.login, self.password))
                raise
528242
def _challenge_response(self, challenge, mode, slot, variable, may_block):
        
         # Check length and pad challenge if appropriate
        if mode == 'HMAC':
            if len(challenge) > yubikey_defs.SHA1_MAX_BLOCK_SIZE:
                raise yubico_exception.InputError('Mode HMAC challenge too big (%i/%i)' \
                                                      % (yubikey_defs.SHA1_MAX_BLOCK_SIZE, len(challenge)))
            if len(challenge) < yubikey_defs.SHA1_MAX_BLOCK_SIZE:
                pad_with = b'\0'
                if variable and challenge[-1:] == pad_with:
                    pad_with = b'\xff'
                challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, pad_with)
            response_len = yubikey_defs.SHA1_DIGEST_SIZE
        elif mode == 'OTP':
            if len(challenge) != yubikey_defs.UID_SIZE:
                raise yubico_exception.InputError('Mode OTP challenge must be %i bytes (got %i)' \
                                                      % (yubikey_defs.UID_SIZE, len(challenge)))
            challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, b'\0')
            response_len = 16
        else:
            raise yubico_exception.InputError('Invalid mode supplied (%s, valid values are HMAC and OTP)' \
                                                  % (mode))

        try:
            command = _CMD_CHALLENGE[mode][slot]
        except:
            raise yubico_exception.InputError('Invalid slot specified (%s)' % (slot))

        frame = yubikey_frame.YubiKeyFrame(command=command, payload=challenge)
        self._device._write(frame)
        response = self._device._read_response(may_block=may_block)
        if not yubico_util.validate_crc16(response[:response_len + 2]):
            raise YubiKeyUSBHIDError("Read from device failed CRC check")
        return response[:response_len]
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})
540599
def input_validate_yubikey_secret(data, name='data'):
    
    if isinstance(data, pyhsm.aead_cmd.YHSM_YubiKeySecret):
        data = data.pack()
    return input_validate_str(data, name)
606611
public function authenticate()
    {
        // go to google.com to get some cookies
        $request = $this->guzzleClient->createRequest('GET', 'http://www.google.com/ncr', ['cookies' => $this->cookieJar]);
        $response = $this->guzzleClient->send($request);

        // get google auth page html and fetch GALX
        $request = $this->guzzleClient->createRequest('GET', self::AUTH_URL, ['cookies' => $this->cookieJar]);
        $response = $this->guzzleClient->send($request);

        $content = $response->getBody()->getContents();

        $document = new \DOMDocument();
        @$document->loadHTML($content);

        $inputElements = $document->getElementsByTagName("input");

        $params = [];

        foreach ($inputElements as $input) {
            $params[$input->getAttribute("name")] = $input->getAttribute("value");
        }

        $params['Email'] = $this->email;
        $params['Passwd'] = $this->password;

        $params['pstMsg'] = '1';
        $params['continue'] = 'http://www.google.com/trends';

        // authenticate
        $request = $this->guzzleClient->createRequest('POST', self::AUTH_URL, ['cookies' => $this->cookieJar]);
        $query = $request->getQuery();


        foreach ($params as $key => $param) {
            $query->set($key, $param);
        }

        $response = $this->guzzleClient->send($request);

        // verify sign in if needed
        if (strpos($response->getEffectiveUrl(), 'LoginVerification') !== false) {
            $content = $response->getBody()->getContents();

            $document = new \DOMDocument();
            @$document->loadHTML($content);

            $inputElements = $document->getElementsByTagName("input");

            $params = [];

            foreach ($inputElements as $input) {
                $params[$input->getAttribute("name")] = $input->getAttribute("value");
            }

            $params['challengetype'] = 'RecoveryEmailChallenge';
            $params['emailAnswer'] = $this->recoveryEmail;

            $url = substr($response->getEffectiveUrl(), 0, strpos($response->getEffectiveUrl(), '?'));

            $request = $this->guzzleClient->createRequest('POST', $url, ['cookies' => $this->cookieJar]);
            $query = $request->getQuery();


            foreach ($params as $key => $param) {
                $query->set($key, $param);
            }

            $response = $this->guzzleClient->send($request);
        }

        // update cookies
        $response = $this->guzzleClient->get('https://www.google.com/accounts/CheckCookie?chtml=LoginDoneHtml',
            ['cookies' => $this->cookieJar],
            ['headers' =>
                ['Referrer' => 'https://www.google.com/accounts/ServiceLoginBoxAuth'],
            ]
        );

        // set language for trends
        $I4SUserLocale = new setCookie([
            'Name'     => 'I4SUserLocale',
            'Value'    => $this->language,
            'Domain'   => 'www.google.com',
            'Path'     => '/trends',
            'Secure'   => true,
            'HttpOnly' => true
        ]);

        $this->cookieJar->setCookie($I4SUserLocale);

        return $this;
    }
1358576
def authenticate(self):
        

        config_data = {}

        # Step 1: try getting username/password from environment
        config_data = self.read_config_environment(config_data)

        # Step 2: if credentials were not in env read in configuration file
        if self.CONFIG_NAME_USER not in config_data \
                or self.CONFIG_NAME_KEY not in config_data:
            if os.path.exists(self.config):
                config_data = self.read_config_file(config_data)
            else:
                raise IOError('Could not find {}. Make sure it\'s located in'
                              ' {}. Or use the environment method.'.format(
                                  self.config_file, self.config_dir))

        # Step 3: load into configuration!
        self._load_config(config_data)