Authenticates to the Tor server.

Autodetect authentication method if not set in options

@throws \Exception

@return \TorControl\TorControl
11981
public function authenticate()
    {
        if (static::AUTH_METHOD_NOT_SET === $this->options['authmethod']) {
            $this->detectAuthMethod();
        }

        switch ($this->options['authmethod']) {
            case static::AUTH_METHOD_NULL:
                $this->executeCommand('AUTHENTICATE');
                break;

            case static::AUTH_METHOD_HASHEDPASSWORD:
                $password = $this->getOption('password');
                if (false === $password) {
                    throw new \Exception('You must set a password option');
                }

                $this->executeCommand('AUTHENTICATE '.static::quote($password));
                break;

            case static::AUTH_METHOD_COOKIE:
                $cookieFile = $this->getOption('cookiefile');
                if (false === $cookieFile) {
                    throw new \Exception('You must set a cookiefile option');
                }
                $cookie = file_get_contents($cookieFile);

                $this->executeCommand('AUTHENTICATE '.bin2hex($cookie));
                break;
        }

        return $this;
    }
371605
protected function identity()
    {
        // Get authentication service
        if (null === $this->identity) {
            $authenticationService = $this->getServiceLocator()
                    ->get('Zend\Authentication\AuthenticationService');
            if (!$authenticationService->hasIdentity()) {
                throw new \Exception('No identity loaded');
            }
            $this->identity = $authenticationService->getIdentity();
        }

        return $this->identity;
    }
37200
protected function authenticate()
    {
        if (!$this->isAuthenticated) {
            list($url, $this->cdnUrl, $this->authToken) = $this->auth->authenticate();
            if ($this->useServicenet) {
                $url = str_replace('https://', 'https://snet-%s', $url);
            }

            $this->connectionUrlInfo = Utils::parseUrl($url);
            $this->httpConnect();

            if ($this->cdnUrl) {
                $this->cdnConnect();
            }

            $this->isAuthenticated = true;
        }
    }
508626
public function authenticate()
    {
        $request = $this->getRequest();
        $adapter = $this->getAuthenticationAdapter();
        $result  = $adapter->setRequest($request);

        if ($result instanceof ResponseInterface) {
            return $result;
        }

        $result = $this->getAuthenticationService()->authenticate($adapter);
        $messages = $result->getMessages();
        if (!$messages) {
            return $result;
        }

        $controller = $this->getController();
        /* @var $flash \Zend\Mvc\Controller\Plugin\FlashMessenger */
        $flash = $controller->flashMessenger();

        switch ($result->getCode()) {
            case Result::SUCCESS:
                foreach ($messages as $message) {
                    $flash->addSuccessMessage($controller->translate($message));
                }
                break;
            case Result::FAILURE_UNCATEGORIZED:
                foreach ($messages as $message) {
                    $flash->addErrorMessage($controller->translate($message));
                }
                break;
            case Result::FAILURE_IDENTITY_NOT_FOUND:
                $identityKey = $adapter->getEvent()->getIdentityKey();
                foreach ($messages as $message) {
                    $errors[$identityKey][] = $controller->translate($message);
                }
                $flash->addErrorMessage($errors);
                break;
            case Result::FAILURE_CREDENTIAL_INVALID:
                $credentialKey = $adapter->getEvent()->getCredentialKey();
                foreach ($messages as $message) {
                    $errors[$credentialKey][] = $controller->translate($message);
                }
                $flash->addErrorMessage($errors);
        }

        if (!$result->isValid()) {
            $adapter->resetAdapters();
        }

        return $result;
    }
390011
private function authenticate() {
        if (!is_resource($this->connection))
            throw new RuntimeException('Cannot authenticate: Not connected');

        // init authentication
        $this->writeData('AUTH LOGIN');
        $response = $this->readResponse();

        $this->parseResponse($response);
        if ($this->responseStatus == 503)
            return;                                     // already authenticated

        if ($this->responseStatus != 334)
            throw new RuntimeException('AUTH LOGIN command not supported: '.$this->responseStatus.' '.$this->response);

        // send username
        $this->writeData(base64_encode($this->options['auth_username']));
        $response = $this->readResponse();

        $this->parseResponse($response);
        if ($this->responseStatus != 334)
            throw new RuntimeException('Username '.$this->options['auth_username'].' not accepted'.$this->responseStatus.' '.$this->response);

        // send password
        $this->writeData(base64_encode($this->options['auth_password']));
        $response = $this->readResponse();

        $this->parseResponse($response);
        if ($this->responseStatus != 235)
            throw new RuntimeException('Login failed for username '.$this->options['auth_username'].': '.$this->responseStatus.' '.$this->response);
    }
754786
public function authenticate() {
		$this->sendMessage('AUTH LOGIN', 334, 'SMTP AUTH not accepted from server');
		$this->sendMessage($this->config->getUser(), 334, 'SMTP username not accepted from server', true);
		$this->sendMessage($this->config->getPassword(), 235, 'SMTP password not accepted from server', true);
	}
845331
public function authenticate()
    {
        if (empty($this->_username) ||
            empty($this->_password)) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('Username/password should be set');
        }

        if(!isset($this->_users[$this->_username])) {
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                null,
                array('Username not found')
                );
        }

        $user = $this->_users[$this->_username];
        if($user["password"] != $this->_password) {
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                null,
                array('Authentication failed')
                );
        }

        $id = new stdClass();
        $id->role = $user["role"];
        $id->name = $this->_username;
        return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $id);
    }
1231211
public static function auth()
    {
        return function (callable $handler) {
            return function (RequestInterface $request, array $options) use ($handler) {
                if (empty($options['http_errors'])) {
                    return $handler($request, $options);
                }
                return $handler($request, $options)->then(
                    function (ResponseInterface $response) use ($request, $handler) {
                        $code = $response->getStatusCode();
                        if ($code == 401 || $code == 403) {
//							do your oauth authorization and retry
                            throw UnauthorizedException::create($request, $response);
                        }

                        return $response;
                    }
                );
            };
        };
    }
562586
public function makeAuthenticationCall()
    {
        $authResponse = $this->call('POST', [
            'grant_type' => 'client_credentials',
            'client_id' => $this->client->getClientID(),
            'client_secret' => $this->client->getClientSecret()
        ], false, ['Content-Type' => 'application/x-www-form-urlencoded'], false, false);

        if (empty($authResponse->getRaw()->access_token)) {
            throw new Exceptions\AuthenticationException;
        }

        return $authResponse;
    }
248070
public function authenticate()
    {
        $hmac = $this->getRest()->getServer()->getHmac();
        $data = array_merge($this->getRequestHeaders(true), $this->getBodyData());
        $auth = $hmac->setData($data)
                     ->setRoute($this->getPlatform()->getPost('api_method'))
                     ->setMethod($_SERVER['REQUEST_METHOD'])
                     ->auth($this->settings['api_key'], $this->settings['api_secret']);
        
        if(!$auth) {
            return false;
        }
        
        return true;
    }
71921
private function instantiateAuthentication()
    {
        foreach ((array) $this->getConfig('auth.bindings', []) as $binding) {
            $this->auths[] = $this->make($binding);
        }
    }
22424
public function authenticate()
    {
        $optionsRequired = array('filename', 'realm', 'username', 'password');
        foreach ($optionsRequired as $optionRequired) {
            if (null === $this->{"_$optionRequired"}) {
                /**
                 * @see Zend_Auth_Adapter_Exception
                 */
                require_once 'Zend/Auth/Adapter/Exception.php';
                throw new Zend_Auth_Adapter_Exception("Option '$optionRequired' must be set before authentication");
            }
        }

        if (false === ($fileHandle = @fopen($this->_filename, 'r'))) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception("Cannot open '$this->_filename' for reading");
        }

        $id       = "$this->_username:$this->_realm";
        $idLength = strlen($id);

        $result = array(
            'code'  => Zend_Auth_Result::FAILURE,
            'identity' => array(
                'realm'    => $this->_realm,
                'username' => $this->_username,
                ),
            'messages' => array()
            );

        while ($line = trim(fgets($fileHandle))) {
            if (substr($line, 0, $idLength) === $id) {
                if ($this->_secureStringCompare(substr($line, -32), md5("$this->_username:$this->_realm:$this->_password"))) {
                    $result['code'] = Zend_Auth_Result::SUCCESS;
                } else {
                    $result['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
                    $result['messages'][] = 'Password incorrect';
                }
                return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
            }
        }

        $result['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
        $result['messages'][] = "Username '$this->_username' and realm '$this->_realm' combination not found";
        return new Zend_Auth_Result($result['code'], $result['identity'], $result['messages']);
    }
252859
protected function attemptAuthentication()
    {
        $extractor = $this->getExtractor();

        if (!$this->isValid()) {
            throw new Exception(
                'Invalid account, user cannot be logged in.');
        }

        $user_id = $this->getBoundUserID($extractor->getUniqueId());

        if ($user_id && $user_id > 0) {
            $user = User::loginByUserID($user_id);
            if ($user && !$user->isError()) {
                return $user;
            }
        }

        if ($extractor->supportsEmail() && $user = \UserInfo::getByEmail($extractor->getEmail())) {
            if ($user && !$user->isError()) {
                throw new Exception('A user account already exists for this email, please log in and attach from your account page.');
            }
        }

        if ($this->supportsRegistration()) {
            if ($extractor->getEmail() === null || empty($extractor->getEmail())) {

                /** @var FlashBagInterface $flashbag */
                $flashbag = $this->app->make('session')->getFlashBag();
                if ($this->supportsFullName()) {
                    $flashbag->set('fullName', $this->getFullName());
                } else {
                    $flashbag->set('firstName', $this->getFirstName());
                    $flashbag->set('lastName', $this->getLastName());
                }
                $flashbag->set('username', $this->getUsername());
                $flashbag->set('token', $this->getToken());


                $response = \Redirect::to('/login/callback/' . $this->getHandle() . '/handle_register/', id(new Token())->generate($this->getHandle() . '_register'));
                $response->send();
                exit;

            } else {
                $user = $this->createUser();

                return $user;
            }
        }

        return null;
    }
1314819
public function authorize(): bool
    {
        parent::authorize();

        $user = $this->user($this->route('guard'))
                ?? $this->attemptUser($this->route('guard'))
                   ?? app('cortex.auth.admin')->whereNotNull('phone')->where('phone', $this->get('phone'))->first();

        if (! $user) {
            // User instance required to detect active TwoFactor methods
            throw new GenericException(trans('cortex/foundation::messages.session_required'), route('adminarea.login'));
        }

        return true;
    }
1024603
public function authenticateAction()
    {
        $request = $this->getRequest();
        $translator = $this->serviceLocator->get('translator');
        $melisCoreAuth = $this->serviceLocator->get('MelisCoreAuth');
        $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig');
        $userTable = $this->getServiceLocator()->get('MelisCoreTableUser');
        $pathAppConfigForm = '/meliscore/forms/meliscore_login';

        // Creating the Zend Form to validate datas
        $appConfigForm = $melisMelisCoreConfig->getItem($pathAppConfigForm);
        $factory = new \Zend\Form\Factory();
        $loginForm = $factory->createForm($appConfigForm);

        if ($request->isPost()) {
            $postValues = get_object_vars($request->getPost());

            $loginForm->setData($postValues);

            // Validate datas
            if ($loginForm->isValid()) {
                // check if the user exists
                $userData = $userTable->getEntryByField('usr_login', $postValues['usr_login']);
                $userData = $userData->current();

                if (!empty($userData)) {

                    /**
                     * PASSWORD UPDATE - June 05, 2017
                     * description: the following code below checks if the user's password is currently still on MD5,
                     * if it's on MD5, it will still accept it, once correctly matched then it will update the user's password
                     * encryption.
                     */

                    // @var $requiresPasswordReset - Flag for password update when successfully logged-in
                    $requiresPasswordReset = false;
                    // @var $password - user provided password
                    $password = $postValues['usr_password'];
                    // @var $newPassword - variable holder for new password encryption
                    $newPassword = null;
                    // @var $md5Regex - regular expression for checking if the password in the user table is on MD5
                    $md5Regex = '/^[a-f0-9]{32}$/';
                    // @var $needReset - Flag if user need's to use the forgot password link
                    $needReset = false;

                    // if the user password in the user table is on MD5
                    if (preg_match($md5Regex, $userData->usr_password)) {
                        // set $requiresPasswordReset flag to "true" to update to new password encryption
                        $requiresPasswordReset = true;
                        // encrypt the password to new encryption
                        $newPassword = $melisCoreAuth->encryptPassword($password);
                        // set the MD5 value of the user provided password, to match its' value to the user table password field
                        $password = md5($postValues['usr_password']);
                    } else {
                        // check if the user password in user table is already in the new password encryption algorithm
                        if (strlen($userData->usr_password) != 60) {

                            // get the 'use_mcrypt' config
                            $useMcrypt = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['use_mcrypt'];
                            // encrypt the password to new encryption
                            $newPassword = $melisCoreAuth->encryptPassword($password);

                            /**
                             * if 'use_mcrypt' is set to "true", then we'll use the mcrypt API for password checking,
                             * however, this will still update the password to new password encryption.
                             *
                             * WARNING: mcrypt API is deprecated on PHP 7.1
                             */
                            if ($useMcrypt) {
                                // salt config
                                $salt = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['salt'];
                                // hash_method config
                                $hash = $melisMelisCoreConfig->getItem('/meliscore/datas/default/accounts')['hash_method'];

                                $enc = new \Zend\Crypt\BlockCipher(new \Zend\Crypt\Symmetric\Mcrypt([
                                    'algo' => 'aes',
                                    'mode' => 'cfb',
                                    'hash' => $hash,
                                ]));
                                $enc->setKey($salt);

                                // get the encrypted password value from the user table
                                $userEncPassword = $userData->usr_password;
                                // get the decrypted password value from the user table
                                $decryptedPassword = $enc->decrypt($userData->usr_password);

                                // try to login using AES SHA256 by matching the decrypted user password to the user provided password
                                if ($password == $decryptedPassword) {
                                    // set $requiresPasswordReset flag to "true" to update to new password encryption
                                    $requiresPasswordReset = true;
                                    // encrypt the password to new encryption
                                    $newPassword = $melisCoreAuth->encryptPassword($password);
                                    // set the MD5 value of the user provided password, to match its' value to the user table password field
                                    $password = $userEncPassword;
                                }
                            } else {
                                // asked the password to reset their password (by using "forgot password" link)
                                $needReset = true;
                            }
                        } else {
                            $userPassword = $userData->usr_password;
                            if ($melisCoreAuth->isPasswordCorrect($password, $userPassword)) {
                                // this will be used in setCredential method
                                $password = $userPassword;
                            }

                        }
                    }

                    // If user is active
                    if ($userData->usr_status != self::USER_INACTIVE) {
                        if (!$needReset) {
                            $melisCoreAuth->getAdapter()->setIdentity($postValues['usr_login'])
                                ->setCredential($password);

                            $result = $melisCoreAuth->authenticate();

                            if ($result->isValid()) {
                                $user = $melisCoreAuth->getAdapter()->getResultRowObject();

                                // Update the rights of the user if it's not a custom role
                                if ($user->usr_role_id != self::ROLE_ID_CUSTOM) {
                                    // Get rights from Role table
                                    $rightsXML = '';
                                    $tableUserRole = $this->serviceLocator->get('MelisCoreTableUserRole');
                                    $datasRole = $tableUserRole->getEntryById($user->usr_role_id);
                                    if ($datasRole) {
                                        $datasRole = $datasRole->current();
                                        if (!empty($datasRole)) {
                                            $user->usr_rights = $datasRole->urole_rights;
                                        }
                                    }
                                }

                                // Write session
                                $melisCoreAuth->getStorage()->write($user);

                                // Update Melis BO locale
                                $melisLangTable = $this->serviceLocator->get('MelisCore\Model\Tables\MelisLangTable');
                                $datasLang = $melisLangTable->getEntryById($user->usr_lang_id);

                                if (!empty($datasLang->current())) {
                                    $datasLang = $datasLang->current();
                                    $container = new Container('meliscore');
                                    $container['melis-lang-id'] = $user->usr_lang_id;
                                    $container['melis-lang-locale'] = $datasLang->lang_locale;
                                }

                                // update last login
                                $loggedInDate = date('Y-m-d H:i:s');
                                $this->getEventManager()->trigger('melis_core_auth_login_ok', $this, [
                                    'login_date' => $loggedInDate,
                                    'usr_id' => $user->usr_id,
                                ]);

                                // update user password if the password is on MD5
                                if ($requiresPasswordReset) {
                                    $userTable->save([
                                        'usr_password' => $newPassword,
                                    ], $userData->usr_id);
                                }

                                // Retrieving recent user logs on database
                                $this->getEventManager()->trigger('meliscore_get_recent_user_logs', $this, []);

                                // check if the user clicked remember me button
                                $rememberMe = (int) $request->getPost('remember');
                                if ($rememberMe == 1) {
                                    $this->rememberMe($postValues['usr_login'], $postValues['usr_password']);
                                } else {
                                    $this->forgetMe($postValues['usr_login'], $postValues['usr_password']);
                                }

                                $result = [
                                    'success' => true,
                                    'errors' => [],
                                ];
                            } else {
                                $result = [
                                    'success' => false,
                                    'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],
                                ];
                            }
                        } else {
                            $result = [
                                'success' => false,
                                'require_reset_password' => true,
                                'errors' => ['empty' => $translator->translate('tr_meliscore_login_password_enc_update')],
                            ];
                        }

                    } else {
                        $result = [
                            'success' => false,
                            'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],
                        ];
                    }
                } else {
                    $result = [
                        'success' => false,
                        'errors' => ['empty' => $translator->translate('tr_meliscore_login_auth_Failed authentication')],
                    ];
                }
            } else {
                $result = [
                    'success' => false,
                    'errors' => [$loginForm->getMessages()],
                ];
            }
        } else {
            $result = [
                'success' => false,
                'errors' => ['empty' => $translator->translate('tr_meliscore_login_errors_Empty datas')],
            ];
        }

        return new JsonModel($result);
    }
869586
public function connect()
    {
        if ( ! ($this->connection = ssh2_connect($this->host, $this->port))) {
            throw new \Exception('Cannot connect to server');
        }
        
        if ( ! ssh2_auth_pubkey_file($this->connection, $this->authUser, $this->authPub, $this->authPriv,
            $this->authPass)
        ) {
            throw new \Exception('Autentication rejected by server');
        }
    }
861312
public function authenticate()
	{
		// Already got some credentials stored?
		if ($this->token)
		{
			$response = $this->verifyCredentials();

			if ($response)
			{
				return $this->token;
			}
			else
			{
				$this->token = null;
			}
		}

		// Check for callback.
		if (strcmp($this->version, '1.0a') === 0)
		{
			$verifier = $this->input->get('oauth_verifier');
		}
		else
		{
			$verifier = $this->input->get('oauth_token');
		}

		if (empty($verifier))
		{
			// Generate a request token.
			$this->_generateRequestToken();

			// Authenticate the user and authorise the app.
			$this->_authorise();
		}

		// Callback
		else
		{
			$session = $this->application->getSession();

			// Get token form session.
			$this->token = array('key' => $session->get('key', null, 'oauth_token'), 'secret' => $session->get('secret', null, 'oauth_token'));

			// Verify the returned request token.
			if (strcmp($this->token['key'], $this->input->get('oauth_token')) !== 0)
			{
				throw new \DomainException('Bad session!');
			}

			// Set token verifier for 1.0a.
			if (strcmp($this->version, '1.0a') === 0)
			{
				$this->token['verifier'] = $this->input->get('oauth_verifier');
			}

			// Generate access token.
			$this->_generateAccessToken();

			// Return the access token.
			return $this->token;
		}
	}