Authenticate

@throws SFException           if any error occurs
@throws SnowflakeSQLException if any error occurs
540844
void authenticate() throws SFException, SnowflakeSQLException
  {
    ServerSocket ssocket = this.getServerSocket();
    try
    {
      // main procedure
      int port = this.getLocalPort(ssocket);
      logger.debug("Listening localhost:{}", port);
      String ssoUrl = getSSOUrl(port);
      this.handlers.output(
          "Initiating login request with your identity provider. A " +
          "browser window should have opened for you to complete the " +
          "login. If you can't see it, check existing browser windows, " +
          "or your OS settings. Press CTRL+C to abort and try again...");
      this.handlers.openBrowser(ssoUrl);

      while (true)
      {
        Socket socket = ssocket.accept(); // start accepting the request
        try
        {
          BufferedReader in = new BufferedReader(
              new InputStreamReader(socket.getInputStream(), UTF8_CHARSET));
          char[] buf = new char[16384];
          int strLen = in.read(buf);
          String[] rets = new String(buf, 0, strLen).split("\r\n");
          if (!processOptions(rets, socket))
          {
            processSamlToken(rets, socket);
            break;
          }
        }
        finally
        {
          socket.close();
        }
      }
    }
    catch (IOException ex)
    {
      throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
    }
    finally
    {
      try
      {
        ssocket.close();
      }
      catch (IOException ex)
      {
        throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
      }
    }
  }
158602
@Override
    public synchronized void authenticate() throws PortalSecurityException {
        int i;
        Enumeration e = mySubContexts.elements();

        while (e.hasMoreElements()) {
            ISecurityContext sctx = ((Entry) e.nextElement()).getCtx();
            // The principal and credential are now set for all subcontexts in Authentication
            try {
                if (sctx instanceof IParentAwareSecurityContext) {
                    ((IParentAwareSecurityContext) sctx).authenticate(this);
                } else {
                    sctx.authenticate();
                }
            } catch (Exception ex) {
                log.error("Exception authenticating subcontext " + sctx, ex);
            }
            // Stop attempting to authenticate if authenticated and if the property flag is set
            if (stopWhenAuthenticated && sctx.isAuthenticated()) {
                break;
            }
        }

        // Zero out the actual credentials if it isn't already null
        if (this.myOpaqueCredentials.credentialstring != null) {
            for (i = 0; i < this.myOpaqueCredentials.credentialstring.length; i++)
                this.myOpaqueCredentials.credentialstring[i] = 0;
            myOpaqueCredentials.credentialstring = null;
        }

        return;
    }
1178996
@Override
    public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
        return authenticate(credentials);
    }
1203862
protected function smtp_authenticate()
	{
		// Encode login data
		$username = base64_encode($this->config['smtp']['username']);
		$password = base64_encode($this->config['smtp']['password']);

		try
		{
			// Prepare login
			$this->smtp_send('AUTH LOGIN', 334);

			// Send username
			$this->smtp_send($username, 334);

			// Send password
			$this->smtp_send($password, 235);

		}
		catch(\SmtpCommandFailureException $e)
		{
			throw new \SmtpAuthenticationFailedException('Failed authentication.');
		}

	}
752856
public function authenticate()
    {
     Logger::get()->debug('Authenticating OpenID user...');
        if (!$this->isAuthenticated) {
            if (!static::getConsumer()->validate()) {
             Logger::get()->debug('  Failed!');
                throw new NotAuthenticatedException('OpenID authentication failed.');
            } else {
                $this->isAuthenticated = true;
            }
        }

     Logger::get()->debug('  OK!');
    }
919238
protected function authenticateSetup()
    {
        $exception = null;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($this->tableName)) {
            $exception = 'A table must be supplied for the DbTable authentication adapter.';
        } /** @noinspection IsEmptyFunctionUsageInspection */ elseif (empty($this->identityColumn)) {
            $exception = 'An identity column must be supplied for the DbTable authentication adapter.';
        } /** @noinspection IsEmptyFunctionUsageInspection */ elseif (empty($this->credentialColumn)) {
            $exception = 'A credential column must be supplied for the DbTable authentication adapter.';
        }

        if (null !== $exception) {
            throw new Exception\RuntimeException($exception);
        }

        $this->setup();

        return true;
    }
356376
def _authenticate(self):
        """"""
        data = {'username': self.username,
                'password': self.password}
        url = '{base}/client/login'.format(base=self.base_url)
        response = self._session.get(url, params=data)
        print(response.text)
        data = response.json()
        if not data.get('success'):
            raise InvalidCredentials(data.get('reason', None))
        self._populate_info(data)
647846
public void authenticate(AuthenticationProtocol authentication,
			String servicename) throws SshException, AuthenticationResult {

		try {
			if (getUsername() == null || getPassword() == null) {
				throw new SshException("Username or password not set!",
						SshException.BAD_API_USAGE);
			}

			if (passwordChangeRequired && newpassword == null) {
				throw new SshException("You must set a new password!",
						SshException.BAD_API_USAGE);
			}

			ByteArrayWriter msg = new ByteArrayWriter();

			try {
				msg.writeBoolean(passwordChangeRequired);
				msg.writeString(getPassword());
				if (passwordChangeRequired) {
					msg.writeString(newpassword);

				}
				authentication.sendRequest(getUsername(), servicename,
						"password", msg.toByteArray());
			} finally {
				try {
					msg.close();
				} catch (IOException e) {
				}
			}
			// We need to read the response since we may have password change.
			byte[] response = authentication.readMessage();

			if (response[0] != SSH_MSG_USERAUTH_PASSWD_CHANGEREQ) {
				authentication.transport.disconnect(
						TransportProtocol.PROTOCOL_ERROR,
						"Unexpected message received");
				throw new SshException(
						"Unexpected response from Authentication Protocol",
						SshException.PROTOCOL_VIOLATION);
			}

			passwordChangeRequired = true;
			throw new AuthenticationResult(SshAuthentication.FAILED);
		} catch (IOException ex) {
			throw new SshException(ex, SshException.INTERNAL_ERROR);
		}
	}
854207
@Override
    @FFDCIgnore({ com.ibm.ws.security.authentication.AuthenticationException.class })
    public AuthenticationResult authenticate(HttpServletRequest request,
                                             HttpServletResponse response,
                                             HashMap<String, Object> props) throws Exception {
        WebRequest webRequest = new WebRequestImpl(request, response, ((WebAppConfig) props.get("webAppConfig")).getApplicationName(), null, (SecurityMetadata) props.get("securityMetadata"), null, (WebAppSecurityConfig) props.get("webAppSecurityConfig"));
        JaspiRequest jaspiRequest = new JaspiRequest(webRequest, (WebAppConfig) props.get("webAppConfig"));
        AuthenticationResult result = null;
        AuthConfigProvider provider = getAuthConfigProvider(jaspiRequest.getAppContext());
        if (provider != null) {
            try {
                if (jaspiRequest.getWebSecurityContext() != null) {
                    JaspiAuthContext jaspiContext = getJaspiAuthContext(jaspiRequest, provider);
                    webRequest.getWebSecurityContext().setJaspiAuthContext(jaspiContext);
                }
                result = authenticate(new Subject(),
                                      getJaspiAuthType(jaspiRequest),
                                      jaspiRequest,
                                      provider);

            } catch (AuthenticationException e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Internal error during JASPI authentication", e);
                result = new AuthenticationResult(AuthResult.FAILURE, e.getMessage());

            }
        } else {
            result = new AuthenticationResult(AuthResult.CONTINUE, "No JASPI provider found for request: " + request.getRequestURI());

        }
        return result;
    }
128460
def _authenticate(self, database, username, password, use_x509, server_name, service_check_tags):
        
        authenticated = False
        try:
            # X.509
            if use_x509:
                self.log.debug(u"Authenticate `%s`  to `%s` using `MONGODB-X509` mechanism", username, database)
                authenticated = database.authenticate(username, mechanism='MONGODB-X509')

            # Username & password
            else:
                authenticated = database.authenticate(username, password)

        except pymongo.errors.PyMongoError as e:
            self.log.error(u"Authentication failed due to invalid credentials or configuration issues. %s", e)

        if not authenticated:
            message = "Mongo: cannot connect with config %s" % server_name
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=message)
            raise Exception(message)

        return authenticated
704404
public function authenticate() {
    	
        throw new common_exception_NotImplemented();
        
        $digest = tao_helpers_Http::getDigest();
        $data = tao_helpers_Http::parseDigest($digest);
        //store the hash A1 as a property to be updated on register/changepassword
        $trialLogin = 'admin'; $trialPassword = 'admin';
        $A1 = md5($trialLogin . ':' . $this::realm . ':' . $trialPassword);
        $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
        $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
    }
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})
612445
@Override
    public boolean authenticate() {
        UndertowLogger.SECURITY_LOGGER.debugf("Attempting to authenticate %s, authentication required: %s", exchange.getRequestPath(), isAuthenticationRequired());
        if(authenticationState == AuthenticationState.ATTEMPTED || (authenticationState == AuthenticationState.CHALLENGE_SENT && !exchange.isResponseStarted())) {
            //we are re-attempted, so we just reset the state
            //see UNDERTOW-263
            authenticationState = AuthenticationState.NOT_ATTEMPTED;
        }
        return !authTransition();
    }
1143087
def authenticate
      begin
        @backend.transaction(true){
          raise NotInitializedError.new(@backend.path.path) unless @backend[:user] && @backend[:system] && @backend[:system][:created]
          check_salt!
        }
      rescue OpenSSL::Cipher::CipherError
        raise WrongMasterPasswordError
      end
    end
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);
    }
470815
@Override
    public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException {
        User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password);
        if(u != null) {
            Authentication auth;
            try {
                UserDetails userDetails = u.getUserDetailsForImpersonation();
                auth = u.impersonate(userDetails);

                SecurityListener.fireAuthenticated(userDetails);
            } catch (UsernameNotFoundException x) {
                // The token was valid, but the impersonation failed. This token is clearly not his real password,
                // so there's no point in continuing the request processing. Report this error and abort.
                LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x);
                throw new ServletException(x);
            } catch (DataAccessException x) {
                throw new ServletException(x);
            }

            req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true);
            return auth;
        }
        return null;
    }
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);
    }