检查验证码是否正确

验证成功后，删除缓存中保存的验证码

@param string $code 需要检查的验证码
@param string $namespace 命名空间，具体说明见ValidCode类
@param string $recipient 验证码接收者，具体说明见ValidCode类
@return bool true为正确  false为错误
546195
public function check($code, $namespace, $recipient)
    {
        $cacheKey = $this->getCacheKey($namespace, $recipient);
        /** @var ValidCode $validCode */
        $validCode = $this->cache->get($cacheKey);
        if (empty($validCode) || $validCode->isExpired() || $validCode->getCode() != $code) {
            return false;
        }
        //验证成功后删除缓存中保存的验证码
        $this->cache->delete($cacheKey);
        return true;
    }
628505
public function isCodeValid($code)
    {
        $now = $this->timezone->date()->format(\DateTime::ATOM);
        $expiryDateString = $this->helper->getWebsiteConfig(
            \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_API_TRIAL_TEMPORARY_PASSCODE_EXPIRY
        );

        if ($now >= $expiryDateString) {
            return false;
        }

        $codeFromConfig = $this->helper->getWebsiteConfig(
            \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_API_TRIAL_TEMPORARY_PASSCODE
        );

        return $codeFromConfig === $code;
    }
561533
public function send($code = null, array $headers = null, $compress = false)
    {
        if ($code !== null) {
            $this->withStatus($code);
        }
        if ($headers !== null) {
            $this->setHeaders($headers);
        }

        $body = $this->body;
        $this->headers['Content-Length'] = strlen($body);

        if ($compress === true) {
            $encoding = '';
            if (preg_match('/ *gzip *,?/', $this->headers['accept-encoding'])) {
                $encoding = 'gzip';
            } elseif (preg_match('/ *deflate *,?/', $this->headers['accept-encoding'])) {
                $encoding = 'deflate';
            }
            (isset($encoding)) ? $this->headers['Content-Encoding'] = $encoding : null;
            $body = static::encodeBody($body, $encoding);
        }
        $this->sendHeaders();
        echo $body;
    }
685661
public function postMessage($sender, $recipient, $message)
    {
        if ($this->maxMessages) {
            $statement = $this->connection->prepare(
                'SELECT COUNT(*) FROM "phergie-plugin-tell"
                    WHERE "recipient" = ?;'
            );
            $statement->execute([ $recipient ]);

            if ($statement->fetchColumn(0) >= $this->maxMessages) {
                return false;
            }
        }

        $this->connection->prepare(
            'INSERT INTO "phergie-plugin-tell"
                ("sender", "recipient", "message")
                VALUES (?, ?, ?);'
        )->execute([ $sender, $recipient, $message ]);

        return true;
    }
114434
private function getAccessToken($code)
    {
        $this->logger->debug('Get Access Token.');
        $this->initRequest();
        $token_url = $this->fcBaseUrl.'token';
        $post_data = [
            "grant_type"    => "authorization_code",
            "redirect_uri"  => $this->callbackUrl,
            "client_id"     => $this->clientId,
            "client_secret" => $this->clientSecret,
            "code"          => $code,
        ];
        $this->logger->debug('POST Data to FranceConnect.');
        $this->setPostFields($post_data);
        $response = \Unirest\Request::post($token_url);
        
        // check status code
        if ($response->code != Response::HTTP_OK) {
            $result_array = $response->body;
            $description = array_key_exists(
                "error_description",
                $result_array
            ) ? $result_array["error_description"] : '';
            $this->logger->error(
                $result_array["error"].$description
            );
            throw new Exception("FranceConnectError".$response->code." msg = ".$response->raw_body);
        }
        
        $result_array = $response->body;
        $id_token = $result_array['id_token'];
        $this->session->set(static::ID_TOKEN_HINT, $id_token);
        $all_part = explode(".", $id_token);
        $payload = json_decode(base64_decode($all_part[1]), true);
        
        // check nonce parameter
        if ($payload['nonce'] != $this->session->get(static::OPENID_SESSION_NONCE)) {
            $this->logger->error('The value of the parameter NONCE is not equal to the one which is expected');
            throw new SecurityException("The nonce parameter is invalid");
        }
        // verify the signature of jwt
        $this->logger->debug('Check JWT signature.');
        $jws = SimpleJWS::load($id_token);
        if (!$jws->verify($this->clientSecret)) {
            $this->logger->error('The signature of the JWT is not valid.');
            throw new SecurityException("JWS is invalid");
        }
        
        $this->session->remove(static::OPENID_SESSION_NONCE);
        
        return $result_array['access_token'];
    }
148578
public function isNamespaceConfiguredToAutoload(string $namespace): bool
    {
        $namespace = trim($namespace, '\\').'\\';
        $classLoader = $this->getClassLoader();

        foreach ($classLoader->getPrefixesPsr4() as $prefix => $paths) {
            if (0 === strpos($namespace, $prefix)) {
                return true;
            }
        }

        foreach ($classLoader->getPrefixes() as $prefix => $paths) {
            if (0 === strpos($namespace, $prefix)) {
                return true;
            }
        }

        return false;
    }
892254
public static function validateOldPersonCode(string $personCode): bool
    {
        $personCode = str_replace('-', '', $personCode);
        $check = '01060307091005080402';
        $checksum = 1;
        for ($i = 0; $i < 10; $i++) {
            $checksum -= (int)$personCode[$i] * (int)substr($check, $i * 2, 2);
        }

        return !((int)($checksum - floor($checksum / 11) * 11) !== (int)$personCode[10]);
    }
1131338
protected function isNamespaceValid($namespace)
    {
        if ($namespace === '\\') {
            return true;
        }

        if (strpos($namespace, '\\') === 0) {
            $namespace = substr($namespace, 1);
        }

        $parts = explode('\\', $namespace);
        foreach ($parts as $part) {
            $match = preg_match(self::PATTERN_VALIDATE_NAMESPACE_NAME, $part);
            if ($match === false || $match <= 0 || ReservedKeywords::isReservedKeyword($part) !== false) {
                return false;
            }
        }

        return true;
    }
1077097
public static function v3($namespace, $name)
    {
        if (!Validate::isValidUUID($namespace)) {
            return false;
        }

        // Get hexadecimal components of namespace
        $nhex = str_replace(array('-', '{', '}'), '', $namespace);

        // Binary Value
        $nstr = '';

        // Convert Namespace UUID to bits
        for ($i = 0; $i < strlen($nhex); $i += 2) {
            $nstr .= \chr(hexdec($nhex[$i] . $nhex[$i + 1]));
        }

        // Calculate hash value
        $hash = md5($nstr . $name);

        return sprintf('%08s-%04s-%04x-%04x-%12s',

            // 32 bits for "time_low"
            substr($hash, 0, 8),

            // 16 bits for "time_mid"
            substr($hash, 8, 4),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 3
            (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

            // 48 bits for "node"
            substr($hash, 20, 12)
        );
    }
407499
protected function isClient(string $namespace, string $name): bool
    {
        if (preg_match('/^Spryker[a-zA-Z]*\\\\Client\\\\[a-zA-Z]+$/', $namespace) && preg_match('/^(.*?)(Client|ClientInterface)$/', $name)) {
            return true;
        }

        return false;
    }
1047808
public function authenticateByCode($provider, string $code)
    {
        $provider_user = $provider->user();

        /** @var \Railken\Amethyst\Repositories\UserRepository */
        $repository = $this->manager->getRepository();

        $user = $repository->findOneByEmail($provider_user->getEmail());

        if (!$user) {
            $result = $this->manager->create([
                'name'     => $provider_user->getNickname() ? $provider_user->getNickname() : $provider_user->getName(),
                'role'     => 'user',
                'password' => str_random(32),
                'email'    => $provider_user->getEmail(),
            ]);

            if (!$result->ok()) {
                return $this->response(['errors' => $result->getSimpleErrors()], Response::HTTP_BAD_REQUEST);
            }

            $user = $result->getResource();
        }

        $token = Container::getInstance()->make(\Laravel\Passport\PersonalAccessTokenFactory::class)->make(
            $user->getKey(),
            'login',
            []
        );

        return $this->response([
            'token_type'   => 'Bearer',
            'expires_in'   => 0,
            'access_token' => $token->accessToken,
        ], Response::HTTP_OK);
    }
1096486
public static function validateNewPersonCode(string $personCode): bool
    {
        $personCode = str_replace('-', '', $personCode);
        // @formatter:off
        $calculations = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // @formatter:on
        $sum = 0;
        foreach ($calculations as $key => $calculation) {
            $sum += ($personCode[$key] * $calculation);
        }
        $remainder = $sum % 11;
        if (1 - $remainder < -1) {
            return (int)$personCode[10] === (1 - $remainder + 11);
        }

        return (int)$personCode[10] === (1 - $remainder);
    }
1233940
static function getSignature($token, $timestamp, $nonce)
    {
        //排序
        try {
            $array = array($token, $timestamp, $nonce);
            sort($array, SORT_STRING);
            $str = implode($array);
            return sha1($str);
        } catch (\Exception $e) {
            @error_log('getSignature Error: ' . $e->getMessage(), 0);
            return FALSE;
        }
    }
155489
public function getCode($code)
    {
        $result = $this->wechat->httpPost(self::WECHAT_DELETE_CARD_URL, [
            'code' => $code
        ], [
            'access_token' => $this->wechat->getAccessToken()
        ]);
        return isset($result['errmsg']) && $result['errmsg'] === 'ok' ? $result : false;
    }
1088889
public function validate($code)
    {
        $correctCode = $this->storage->pull();

        if (! empty($correctCode)) {
            return mb_strtolower($correctCode) === mb_strtolower($code);
        }

        return false;
    }
649855
static function generateMergeNamespaceCode( $php, $tpl, $namespace, $namespaceScope, $parameters = array(), $skipSimpleAssignment = false )
    {
        if ( $namespace != '' )
        {
            if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_GLOBAL )
            {
                $php->addVariable( 'namespace', $namespace, eZPHPCreator::VARIABLE_ASSIGNMENT, $parameters );
            }
            else if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_LOCAL )
            {
                $php->addCodePiece( "\$namespace = \$rootNamespace;
if ( \$namespace == '' )
    \$namespace = \"$namespace\";
else
    \$namespace .= ':$namespace';
", $parameters );
            }
            else if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_RELATIVE )
            {
                $php->addCodePiece( "\$namespace = \$currentNamespace;
if ( \$namespace == '' )
    \$namespace = \"$namespace\";
else
    \$namespace .= ':$namespace';
", $parameters );
            }
        }
        else
        {
            if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_GLOBAL )
            {
                if ( $skipSimpleAssignment )
                    return "''";
                $php->addVariable( 'namespace', '', eZPHPCreator::VARIABLE_ASSIGNMENT, $parameters );
            }
            else if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_LOCAL )
            {
                if ( $skipSimpleAssignment )
                    return "\$rootNamespace";
                $php->addCodePiece( "\$namespace = \$rootNamespace;\n", $parameters );
            }
            else if ( $namespaceScope == eZTemplate::NAMESPACE_SCOPE_RELATIVE )
            {
                if ( $skipSimpleAssignment )
                    return "\$currentNamespace";
                $php->addCodePiece( "\$namespace = \$currentNamespace;\n", $parameters );
            }
        }
        return true;
    }
328308
public function setHttpStatusCode($code)
    {
        $code = intval($code);
        if (!is_int($code)
            || $code < 100
            || $code > 599
        ) {
            trigger_error('Invalid HTTP status code, not taken into account.', E_USER_WARNING);
            return false;
        }
        $this->httpStatusCode = $code;
        return true;
    }