Формы регистрации и входа в AMP - PullRequest
0 голосов
/ 25 ноября 2018

Я работаю над проектом, в котором у меня довольно много форм.

Мне удалось заставить некоторые из них работать либо с помощью метода POST с action-xhr, который включал перекодирование немного phpскрипт, который обрабатывает отправленные данные, или изменяя их на метод GET, а иногда просто немного корректируя скрипт php обработки (скажем, где был вызван метод post для получения данных).

Проблема, с которой я столкнулсясталкивается с тем, как перекодировать регистрацию и формы входа в систему, используя метод POST, и это должно остаться таким, в формате AMP.

В настоящее время у меня есть эта форма входа (login.php):

<?php
if(!empty($_POST)){

    $account_username = $_POST['account_username'];
    $account_password = $_POST['account_password'];
    $remember = $_POST['remember'];

    $domain_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
    header("Content-type: application/json");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: ". str_replace('.', '-','https://amp.domain.com') .".cdn.ampproject.org");
    header("AMP-Access-Control-Allow-Source-Origin: " . $domain_url);
    header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
    echo json_encode(array('account_username' => $account_username, 'account_password' => $account_password, 'remember' => $remember));
    exit;
}
include('login-content.php');

Затем внутри файла "login-content.php" у меня есть эта другая кодировка:

<form method="post" action-xhr="/account/login/" custom-validation-reporting="show-all-on-submit">

<p><a href="/account/registration/" title="Register for an account.">Register for an account</a></p>

<p><label for="account_username">*Email Address:</label>
<input type="text" name="account_username" id="account_username" autofocus required value="<?php if(isset($Html->account_username)){ echo $Html->account_username; } ?>" />
<span visible-when-invalid="valueMissing" validation-for="account_username"></span></p>

<p><label for="account_password">*Password:</label>
<input type="password" name="account_password" id="account_password" required value="<?php if(isset($Html->account_password)){ echo $Html->account_password; } ?>" />
<span visible-when-invalid="valueMissing" validation-for="account_password"></span><p>

        <?php
        if(Account::USE_PERSIST_LOGIN)
        {
            ?>

<p><input type="checkbox" name="remember" id="remember" value="1" <?php if(isset($Html->remember) && $Html->remember=='1'){ echo " checked "; } ?> />
<label for="remember" >Remember me?</label></p>

            <?php
        }
        ?>

<p><input class="Input Green" type="submit" name="action" value="Login" /></p>

<p><a href="/account/forgot.php" title="Forgot your password?" >Forgot your password?</a></p>

<p><span class="req">* Denotes a required field.</span></p>

<div submit-success>
    <template type="amp-mustache">
        <?php $php_username = '{{account_username}}'; $php_password = '{{account_password}}'; ?><?php echo 'PHP username: "'.$php_username.'" and PHP password: "'.$php_password.'"'; ?><br />
<br />
<br />
        The username submitted was '{{account_username}}' and the password submitted was '{{account_password}}'.
    </template>
</div>
<div submit-error><?php print_r($_POST); ?>
    <template type="amp-mustache">
        Logging in failed!
    </template>
</div>

</form>

Хорошая новость в том, что я могу получить данные JSONвнутри формы, внутри '' и ''.

Я мог получить его, используя '{{account_username}}', или я мог установить переменную PHP, которая вызывала бы '{{account_username}}', а затем яможет отображать переменную PHP.

На данный момент моя проблема в том, как я могу адаптировать свою кодировку из сценария «login.php», а не из «login-content.php», чтобы я мог получить данные, отправленные через форму, и сохранить ихв переменных PHP.

Мне нужно сравнить эти переменные PHP с различными функциями php, которые сравнивают имя пользователя и пароль с различными критериями, проверяет, подтвержден ли пользователь, хороши ли учетные данные, в конечном итоге подтверждает учетную запись, пишетв базу данных с помощью команды SQL и т. д.

По сути, мне нужно иметь возможность добавить в сценарий AMP "login.php" набор кодов из сценария DESKTOP "login.php", но AMPнужно уметь извлекать данные, отправленные через форму AMP (JSON).

Код, который мне нужно добавить в форму login.php:

<?php
/**
* Allows member to log into their account
* Uses a global form for simplicity - see include
* @version      3.0
* @package      Public
* @subpackage   Account
*/
################################################################################
# SETUP
################################################################################
if(!isset($root)){$root="";for($i=0;$i<substr_count(trim(str_replace($_SERVER['DOCUMENT_ROOT'],"",__FILE__),"/"),"/");$i++){$root.="../";}}
require_once("{$root}inc/config/main.php");
Account::validatePageAccess(USER_ACCESS_GUEST);

################################################################################
# REQUIRE
################################################################################
################################################################################
# OBJECTS
################################################################################
################################################################################
# REQUEST
################################################################################
if(Account::EMAIL_CONFIRMATION && isset($Clean->action) && "Confirm"==$Clean->action)
{
    $Clean->filter("str","q","request", true, "Invalid.");
    if(!Notifier::hasIssues())
    {
        if(isset($Clean->q))
        {
            $account_email=Encryption::decryptBasic($MySql->q);
            if(is_object($oExisting=Account::getAccountByEmail($account_email)))
            {
                if($oExisting->account_confirmed=="0")  // not confirmed
                {
                    if(Account::confirmAccountEmail($account_email))
                    {
                        messenger("notice","","Thank you.");
                        messenger("notice","","Your email address has now been confirmed.");
                        messenger("notice","","You may now log into your account.");
                    }
                }
                else    // already confirmed
                {
                    messenger("warning","","It appears that you have already confirmed this email address.");
                    messenger("notice","","You may now log into your account.");
                }
            }
            else
            {
                messenger("warning","","Sorry, but it appears that you have not registered yet.");
                //Forward::run("account/registration.php");
                //die();
            }
        }
    }
}
elseif(isset($Clean->action) && "Logout"==$Clean->action)
{
    if(is_object($myAccount))   // if user is logged in, log them out
    {
        Account::logout();
        messenger("notice","","You have been logged out.");
        messenger("notice","","Please come again soon.");
    }
}
elseif(isset($Clean->action) && "Login"==$Clean->action)
{
    $Clean->filter("str","account_username","request", true, "Please enter your user name or email address.");
    $Clean->filter("str","account_password","request", true, "Please enter your password.");
    $Clean->filter("cb","remember","request");
    if(!Notifier::hasIssues())
    {
        /**
        * Require Is class to test email
        */
        require_once("manip/Is.php");

        // If the submitted username is an email address
        if(Is::isEmail($Clean->account_username))
        {
            // Attempt to grab the account using an email address
            $oExisting=Account::getAccountByEmail($Clean->account_username);
        }
        else
        {
            // Attempt to grab the account using the username
            $oExisting=Account::getAccountByUsername($Clean->account_username);
        }


//$debug[] = Account::oscEncryptPassword($Clean->account_password);

        // If the account was found
        if(isset($oExisting) && is_object($oExisting))
        {

            // User exists, but appears to be a pseudo account...
            if(Account::ALLOW_PSEUDO_ACCOUNTS && $oExisting->account_is_pseudo)
            {
                $warning['account_email']="Sorry, but this email address has already been registered.";
                $warning[] = "<a href='/account/forgot.php' title='Forgot password?'>Forgot password?</a>";
                //Forward::run("account/registration.php");
                //die();
            }
            else
            {
                // user exists, prepare password
                $encrypted_pass=Encryption::encryptBasic($Clean->account_password);
                // If this account does not have a password
                if(empty($oExisting->account_password) and !empty($oExisting->account_password_osc))
                {
                    // if the submitted password validates through osc check
                    if(Account::oscValidatePassword($Clean->account_password,$oExisting->account_password_osc))
                    {
                        // Update oExisting password with encrypted submitted password
                        $qUpdate = "
                            UPDATE account_users
                            SET
                                account_password='{$encrypted_pass}'
                            WHERE
                                account_id='{$oExisting->account_id}'
                        ";
                        if(DBHelper::update($qUpdate))
                        {
                            $oExisting->account_password = $encrypted_pass; // Update the oExisting password to force login success
                            $debug[] = "Account password has been updated based on osc password validation success";
                        }
                    }
                }
                // Invalid credentials
                if($oExisting->account_password == '' or $encrypted_pass!=$oExisting->account_password)
                {
                    // update login attempts
                    $attempts=$oExisting->account_login_attempts + 1;
                    if(Account::updateLoginAttempts($oExisting->account_id, $attempts))
                    {
                        pre("Attempts have been updated: {$attempts}");
                    }
                    $warning['account_username']="Sorry, but the login credentials you provided are incorrect.";
                    $warning['account_password']="Please double check your credentials and remember that they are case sensitive.";
                }

                // Check if account has been suspended
                elseif($oExisting->account_suspended!='0')
                {
                    $warning['account_username']="Sorry, but it appears that this account was suspended.";
                    messenger("warning","","<a href='{$root}contact.php' title='Contact an Administrator'>Contact an Administrator</a>");
                }

                // Check if account has been cancelled
                elseif($oExisting->account_cancelled!='0')
                {
                    $warning['account_username']="Sorry, but it appears that this account was cancelled.";
                    //messenger("warning","","<a href='{$root}contact.php' title='Contact a Administrator'>Contact a Administrator</a>");   // want this to be permanent.
                }

                // Verify that this login has access to the member area
                elseif(!is_object($oExisting) || !Account::validateAccountAccess($oExisting, PAGE_ACCESS_MEMBER))
                {
                    messenger("warning","","Please check your login information and try again.");
                }

                // check if account has been confirmed
                elseif(Account::EMAIL_CONFIRMATION && $oExisting->account_confirmed=='0')
                {
                    $warning['account_username']="Sorry, but it appears that this email address has yet to be verified.";
                    /**
                    * Require the Mailer Class
                    */
                    require_once("utility/Mailer.php");
                    if(Mailer::sendConfirmEmailNotification($oExisting->account_id))
                    {
                        messenger("notice","",Account::EMAIL_VERIFICATION_MESSAGE);
                        ?>
                        <script>alert('<?php echo Account::EMAIL_VERIFICATION_MESSAGE; ?>');</script>
                        <?php
                    }
                }
                // valid account - continue to actual login process
                else
                {
                    // If the login attempts are greater than zero - display attempts
                    if($oExisting->account_login_attempts > 0)
                    {
                        pre("There have been {$oExisting->account_login_attempts} failed attempts to log into your account.");
                    }

                    // update accessed date and reset attempted logins
                    if(Account::resetLoginAttempts($oExisting->account_id))
                    {
                        pre("Attempts have been reset");
                    }

                    Account::login($oExisting, $Clean->remember);

                    messenger("notice","","Welcome {$oExisting->account_first}.");
                    // if there is no prepared forward
                    if(!Forward::run())
                    {
                        // forward to default
                        Forward::run("account/index.php");
                    }
                }
            }
        }
        else
        {
            $warning['account_username']="Sorry, but this account does not exist.";
        }
    }
}

На этоммне кажется, что я могу получить отправленные данные только внутри файла "login-content.php" и только внутри этого блока:

            <div submit-success>
                <template type="amp-mustache">

...

                </template>
            </div>

Мне нужно установить переменные PHPФайл «login.php» перед вызовом файла «login-content.php», где у меня есть логика AMP Mustache.

...