/* UserCredentialsInterface
761506
public function checkUserCredentials($username, $password)
    {
        if ($user = $this->getUser($username)) {
            return $this->checkPassword($user, $password);
        }

        return false;
    }
465065
private function _getRememberMeCredentials()
    {
        $credentials = array();
        $remember = get_hash('AN_LOGIN_REMEMBER');

        if (isset($_COOKIE[$remember]) && !empty($_COOKIE[$remember])) {
            $key = get_hash('AN_LOGIN_REMEMBER', 'md5');
            $crypt = $this->getService('anahita:encrypter', array('key' => $key, 'cipher' => 'AES-256-CBC'));
            $cookie = $crypt->decrypt($_COOKIE[$remember]);

            try {
                $credentials = (array) unserialize($cookie);
            } catch (RuntimeException $e) {
                error_log($e->getMessage());
            }
        }

        return $credentials;
    }
495201
public function listCredential()
    {
        $this->actionListCredential();
        $this->setTitleListCredential();
        $this->setBreadcrumbListCredential();
        $this->setFilterListCredential();
        $this->setPagerListCredential();

        $this->setData('credentials', $this->getListCredential());
        $this->setData('handlers', $this->credential->getHandlers());
        $this->outputListCredential();
    }
1232590
private function getCredentials()
    {
        $options = ['--config ui.interactive' => 'no', '--config auth.x.prefix' => 'http://'];

        $repository = $this->credentials->getCurrentRepository();
        if ($user = $repository->username) {
            $options['--config auth.x.username'] = $user;
        }
        if ($pass = $repository->password) {
            $options['--config auth.x.password'] = $pass;
        }

        return $options;
    }
819316
public static function authenticate(
        /** @noinspection PhpUnusedParameterInspection */
        array $routeParams,
        ContainerInterface $container,
        ServerRequestInterface $request
    ): ResponseInterface {
        $inputs = $request->getParsedBody();
        if (is_array($inputs) === false) {
            return new HtmlResponse(static::view($container, Views::SIGN_IN_PAGE, [
                'error_message'       => 'Invalid input data.',
                'password_min_length' => User::MIN_PASSWORD_LENGTH,
            ]), 422);
        }

        // validate inputs
        $formValidator = static::createFormValidator($container, SignIn::class);
        if ($formValidator->validate($inputs) === false) {
            /** @var Traversable $errorMessages */
            $errorMessages = $formValidator->getMessages();
            $errorMessages = iterator_to_array($errorMessages);

            return new HtmlResponse(static::view($container, Views::SIGN_IN_PAGE, [
                'errors'              => $errorMessages,
                'previous'            => $inputs,
                'password_min_length' => User::MIN_PASSWORD_LENGTH,
            ]), 422);
        }
        $captures = $formValidator->getCaptures();
        list (self::FORM_EMAIL => $email, self::FORM_PASSWORD => $password) = $captures;
        $isRemember = $captures[static::FORM_REMEMBER] ?? false;
        assert(is_bool($isRemember));

        // actual check for user email and password
        /** @var PassportServerIntegrationInterface $passport */
        $passport = $container->get(PassportServerIntegrationInterface::class);
        $userId   = $passport->validateUserId($email, $password);
        if ($userId === null) {
            return new HtmlResponse(static::view($container, Views::SIGN_IN_PAGE, [
                'error_message'       => 'Invalid email or password.',
                'previous'            => $inputs,
                'password_min_length' => User::MIN_PASSWORD_LENGTH,
            ]), 401);
        }

        // if we are here name and password are valid.
        // we have to create an auth token and return its value as a cookie.

        // default scope of default OAuth client
        $clientScope = $passport->getClientRepository()->readScopeIdentifiers($passport->getDefaultClientIdentifier());
        // limit the default scope to user's role allowed scopes
        // by default settings it invokes `\App\Authentication\OAuth::validateScope`
        $changedScopeOrNull = $passport->verifyAllowedUserScope($userId, $clientScope);
        // now save the token with the assigned scopes
        $unsavedToken = $passport
            ->createTokenInstance()
            ->setClientIdentifier($passport->getDefaultClientIdentifier())
            ->setUserIdentifier($userId);
        if ($changedScopeOrNull === null) {
            // here will be users with scopes identical to client's ones aka unlimited (e.g. admins)
            $unsavedToken->setScopeIdentifiers($clientScope)->setScopeUnmodified();
        } else {
            // here will be less privileged users with scope less than client's default
            $unsavedToken->setScopeIdentifiers($changedScopeOrNull)->setScopeModified();
        }
        list($tokenValue, $tokenType, $tokenExpiresIn, $refreshValue) = $passport->generateTokenValues($unsavedToken);
        $unsavedToken->setValue($tokenValue)->setType($tokenType)->setRefreshValue($refreshValue);
        $savedToken     = $passport->getTokenRepository()->createToken($unsavedToken);
        $valueForCookie = $savedToken->getValue();

        // now cookie ...
        /** @var CookieJarInterface $cookies */
        $cookies    = $container->get(CookieJarInterface::class);
        $authCookie = $cookies
            ->create(CookieAuth::COOKIE_NAME)
            ->setValue($valueForCookie)
            ->setAccessibleOnlyThroughHttp();

        $isRemember === true ? $authCookie->setExpiresInSeconds($tokenExpiresIn) : $authCookie->setExpiresAtUnixTime(0);

        $isOnlyHttpsCookie =
            static::getSettings($container, Authorization::class)[Authorization::KEY_AUTH_COOKIE_ONLY_OVER_HTTPS];
        if ($isOnlyHttpsCookie === true) {
            $authCookie->setSendOnlyOverSecureConnection();
        }

        $redirectUrl = null;
        if (array_key_exists(static::QUERY_SIGN_IN_REDIRECT_URI, $request->getQueryParams()) === true) {
            $mightBeRedirectUrl = $request->getQueryParams()[static::QUERY_SIGN_IN_REDIRECT_URI];
            if (is_string($mightBeRedirectUrl) === true && empty($mightBeRedirectUrl) === false) {
                $redirectUrl = static::safelyParseRedirectUrl($mightBeRedirectUrl);
            }
        }

        // ... and redirect to home page if no valid redirect URI given
        if ($redirectUrl === null) {
            $redirectUrl = static::createRouteUrl($container, HomeController::ROUTE_NAME_HOME);
        }

        return new RedirectResponse($redirectUrl);
    }
517447
public function getCredentials()
    {
        $secret = $this->getSecret();

        if (!isset($secret['username']) || !isset($secret['password'])) {
            throw new CredentialError('Unrecognized credential secret');
        }

        return parent::getCredentials();
    }
1263551
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp)
    {
        $oDb = Factory::service('Database');
        $oDb->where('user_id', $iUserId);
        $oDb->where('salt', $sSalt);
        $oDb->where('token', $sToken);

        $oToken  = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row();
        $bReturn = true;

        if (!$oToken) {

            $this->setError(lang('auth_twofactor_token_invalid'));
            return false;

        } elseif (strtotime($oToken->expires) <= time()) {

            $this->setError(lang('auth_twofactor_token_expired'));
            $bReturn = false;

        } elseif ($oToken->ip != $sIp) {

            $this->setError(lang('auth_twofactor_token_bad_ip'));
            $bReturn = false;
        }

        //  Delete the token
        $this->mfaTokenDelete($oToken->id);

        return $bReturn;
    }
349964
function setCredentials($xmlrpcEndPoint, $username, $password)
    {
        // prepend http protocol to the end point if needed
        $scheme = parse_url($xmlrpcEndPoint, PHP_URL_SCHEME);
        if (!$scheme) {
            $xmlrpcEndPoint = "http://{$xmlrpcEndPoint}";
        }

        // swith to https when working with wordpress.com blogs
        $host = parse_url($xmlrpcEndPoint, PHP_URL_HOST);
        if (substr($host, -14) == '.wordpress.com') {
            $xmlrpcEndPoint = preg_replace('|http://|', 'https://', $xmlrpcEndPoint, 1);
        }

        // save information
        $this->endPoint = $xmlrpcEndPoint;
        $this->username = $username;
        $this->password = $password;
    }
822142
public function getCredential($key)
    {
        return !isset($this->credentials[$key]) ? null : $this->credentials[$key];
    }
1198317
private OAuthHmacCredential new10aCredential(String userId) {
        ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();
        OAuthHmacCredential.Builder builder =
                new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(),
                        clientAuthentication.getClientSecret())
                        .setTransport(getTransport())
                        .setJsonFactory(getJsonFactory())
                        .setTokenServerEncodedUrl(getTokenServerEncodedUrl())
                        .setClientAuthentication(getClientAuthentication())
                        .setRequestInitializer(getRequestInitializer())
                        .setClock(getClock());
        if (getCredentialStore() != null) {
            builder.addRefreshListener(
                    new CredentialStoreRefreshListener(userId, getCredentialStore()));
        }

        builder.getRefreshListeners().addAll(getRefreshListeners());

        return builder.build();
    }
296420
public function verifyCredentials(AuthListener $listener, AreaContract $area, array $input)
    {
        $provider   = $this->service->getEnabledInArea($area);
        $userConfig = $this->userConfigService->getSettingsByArea($area);

        if (!$provider->getProviderGateway()->isVerified($userConfig, $input)) {
            return $listener->verifyFailed();
        }
        $this->userConfigService->setAsConfigured($userConfig);
        $this->service->getAuthStore()->verify();
        return $listener->authenticate($area);
    }
976691
def setUserKeyCredentials(self, username, public_key=None, private_key=None):
        """"""

        self.setCredentialValues(username=username, public_key=public_key, private_key=private_key)
1053552
public function createSecretCredentialsToken(CredentialsInterface $credentials, array $scopes = array())
    {
        /** @var Command $createSession */
        $createSession = $this->createCommand()
            ->setRequest($this->client->post('encrypted/session'))
            ->setBodyEntity($credentials->toPublicArray(), 'urlencoded')
            ->setResponseClass('Maba\OAuthCommerceClient\Entity\SignedCredentials\Session')
        ;

        $registry = $this->registry;

        $httpClient = $this->client;
        return $this->createCommand()
            ->setBeforeExecute(function(Command $command) use ($createSession, $credentials, $scopes, $httpClient, $registry) {
                /** @var Session $session */
                $session = $createSession->getResult();

                $keyExchange = $registry->getKeyExchange($session->getKeyExchange()->getType());
                $encrypting = $registry->getEncrypting($session->getCipher()->getType());
                $hasher = $registry->getHasher($session->getCertificate()->getHashType());

                $serverCertificate = $httpClient->get($session->getCertificate()->getUrl())
                    ->send()
                    ->getBody(true)
                ;

                $hash = $hasher->hash($serverCertificate);
                if ($session->getCertificate()->getHash() !== $hash) {
                    throw new InvalidHashException(sprintf(
                        'Provided hash (%s) does is not as calculated from downloaded certificate (%s)',
                        $session->getCertificate()->getHash(),
                        $hash
                    ));
                }

                $additionalParameters = new Collection();
                $commonKey = $keyExchange->generateCommonKey(
                    $session->getKeyExchange()->getParameters(),
                    $serverCertificate,
                    $additionalParameters,
                    $encrypting->getKeyLength()
                );
                $encoded = http_build_query($credentials->toPrivateArray(), null, '&');
                $encrypted = $encrypting->encrypt($encoded, base64_decode($session->getCipher()->getIv()), $commonKey);

                $command->setBodyEntity(array(
                    'grant_type' => 'urn:marius-balcytis:oauth:grant-type:encrypted-credentials',
                    'scope' => implode(' ', $scopes),
                    'session_id' => $session->getSessionId(),
                    'encrypted_credentials' => $encrypted,
                ) + $additionalParameters->getAll(), 'urlencoded');
            })
            ->setRequest($this->client->post('encrypted/token'))
            ->setResponseClass('Maba\OAuthCommerceClient\Entity\AccessToken')
        ;
    }
218363
@Override
  public final UserCredentials retrieveUserCredentials(
    final String pUserName) throws Exception {
    String query = "select USERTOMCAT.ITSUSER as ITSUSER, ITSPASSWORD, ITSROLE"
      + " from USERTOMCAT join USERROLETOMCAT on USERROLETOMCAT.ITSUSER ="
        + " USERTOMCAT.ITSUSER where USERTOMCAT.ITSUSER = '" + pUserName + "';";
    UserCredentials result = null;
    IRecordSet<RS> recordSet = null;
    try {
      this.srvDatabase.setIsAutocommit(false);
      this.srvDatabase.
        setTransactionIsolation(ISrvDatabase.TRANSACTION_READ_UNCOMMITTED);
      this.srvDatabase.beginTransaction();
      recordSet = getSrvDatabase().retrieveRecords(query);
      if (recordSet.moveToFirst()) {
        ArrayList<String> roles = new ArrayList<String>();
        do {
          if (result == null) {
            result = new UserCredentials();
            result.setUserName(recordSet.getString("ITSUSER"));
            result.setUserPassword(recordSet.getString("ITSPASSWORD"));
          }
          roles.add(recordSet.getString("ITSROLE"));
        } while (recordSet.moveToNext());
        result.setUserRoles(roles.toArray(new String[roles.size()]));
      }
      this.srvDatabase.commitTransaction();
    } catch (Exception ex) {
      this.srvDatabase.rollBackTransaction();
      throw ex;
    } finally {
      this.srvDatabase.releaseResources();
      if (recordSet != null) {
        recordSet.close();
      }
    }
    return result;
  }
398077
private static void validateCredentials() {
        try {
            Account.get().getAccountInfo();
        } catch (Exception e) {
            if (e instanceof AppPlatformException) {
                AppPlatformException appEx = (AppPlatformException) e;

                if (appEx.getStatus() == 401){
                    throw new InvalidCredentialsException();
                }
            } else {
                throw new RuntimeException(e);
            }
        }
    }
473010
public function validateCredentials(UserInterface $user, array $credentials)
	{
		try
		{
			$result = Kinvey::login($credentials);
			$user->_kmd = $result['_kmd'];
		}
		catch (KinveyResponseException $e)
		{
			if ($e->getResponse()->getStatusCode() === 401)
			{
				return false;
			}
			else
			{
				throw $e;
			}
		}

		return true;
	}
556141
public function requestClientCredentials($options = array()) {
        $options = array_merge(array(
            'scope' => '',
        ), $options);

        $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array(
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'grant_type' => 'client_credentials',
            'scope' => $options['scope'],
        ));
        $result = $res->getBody();

        $token = null;
        if ($result && $result = json_decode($result, true)) {
            if (!empty($result['error'])) {
                throw new Exception($result['error_description']);
            }

            if (!empty($result['access_token'])) {
                $this->accessToken = $token = $result['access_token'];
            }
        }

        if (empty($token)) {
            throw new InvalidTokenException('token not available.');
        }

        return $token;
    }