Blog system forget password implementation

Posted by danielle on Tue, 18 Jan 2022 20:43:00 +0100

Blog system forgot password operation:

About How does php install the phpemail plug-in I mentioned it in the previous article. I won't repeat it here. I mainly talk about how to implement this function. The steps I implement here are as follows: 1. Click the page displaying forgotten password, and the user needs to enter his user name and email, and then click the send verification code button. At this time, an ajax request will be sent. I encapsulate a class for sending email in the background, Class has a method to send e-mail. Here, I will first verify the user name and mailbox. If there is no problem with the verification, I will generate a verification code and call the method to send e-mail. If the transmission is successful, the currently generated verification code will be stored in a cookie and set to expire in 60 seconds. Then the user fills in the verification code in the mailbox, and when clicking verification, another ajax request will be sent. The background will verify whether there is a problem with changing the verification code. If there is no problem, modify the user password, change the user password to the first six digits of the verification mailbox, and jump to the login interface. The following is the detailed implementation of the code:

1,forget.ctp view code

When I change the code again, I spend more time on the implementation of the background page. It takes more time to click the countdown, disable the button and add a new style to the button. The implementation of the back-end code is relatively simple.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Login</title>

    <link rel="stylesheet" href="/css/layui/css/layui.css">
    <script src="/css/layui/layui.js"></script>
    <!--<script src="/css/layui/modules/layer.js"></script>-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>

</head>
<body style="background-color:#5FB878">
<div>
    <h1 style="color: #fafafa; text-align: center; Line height: 80px "> wyq blog system background login</h1>
</div>
<div style="width: 30%;height: 40%;position: absolute;left:35%;top:30%;background-color:#FAFAFA">
    <div style="width: 100%;height: 20%;background-color: #009688;">
        <h1 style="color: #fafafa; text-align: center; Line height: 80px "> password retrieval</h1>
    </div>
    <div style="padding: 40px;">
        <form class="layui-form" >

            <div class="layui-form-item">
                <label class="layui-form-label">user name</label>
                <div class="layui-input-block">
                    <input type="text" id="username" name="username"  placeholder="Please enter a registered user name"  class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">e-mail address</label>
                <div class="layui-input-inline">
                    <input type="text" id="email" name="username"  placeholder="Please enter a registered mailbox"  class="layui-input">
                </div>
                <!--Click the button to send the verification code-->
                <button id="fun" type="button"  class="layui-btn" >Send verification code</button>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label">Email verification code</label>
                <div class="layui-input-block">
                    <input type="text" name="code" id="code" placeholder="Please enter the verification code" style="width: 200px;"  class="layui-input">
                </div>
            </div>

            <button id="submit" type="button" class="layui-btn" style="margin-left: 80px;margin-top: 20px">verification</button>
            <a type="button"  href="/login/regist" style="margin-left: 250px;margin-top: 20px"  class="layui-btn">To register</a>
        </form>
    </div>
</div>
</body>
</html>

    <script>
        //Click the button to send the request. If successful, count down and disable the button
        $('#fun').click(function () {
             //ajax calls the send mailbox method
             var data = {
                'email':$('#email').val(),
                'username':$('#username').val(),
             }
             //Send post request
            $.ajax({
                'url':'/login/findPsw',
                'data':data,
                'type':'post',
                'dataType':'Json',
                'success':function (res) {
                    if (res == 200){
                        //Email sent successfully
                        layui.use('layer',function () {
                            var layer = layui.layer;
                            layer.msg("Sending succeeded!");
                        });
                        //Add button style, and disable the button style of layui
                        $('#fun').addClass('layui-btn-disabled');
                        //Disable the button, and the request cannot be sent again after sending successfully
                        $('#fun').attr('disabled',true);
                        //Set the 59 second countdown
                        var t = parseInt(59);
                        //Set the timer and execute it every second
                        var time =  setInterval(function () {
                            //Example of setting button value: 45s
                            $('#fun').html(t+'s');
                            //The value of t per execution is - 1
                            t--;
                            //When 60 seconds later
                            if (t == 0){
                                //Reset button
                                $('#fun').removeClass('layui-btn-disabled');
                                $('#fun').attr('disabled',false);
                                $('#fun').html('Send verification code ');
                                //Clear counter
                                clearInterval(time);
                            }
                        },1000)
                    } else if (res == 400) {
                        layui.use('layer',function () {
                            var layer = layui.layer;
                            layer.msg("Mailbox sending failed!");
                        });
                    }else{
                        layui.use('layer',function () {
                            var layer = layui.layer;
                            layer.msg("User name or mailbox error!");
                        });
                    }
                }
            })
         })
        layui.use('layer',function () {
            //Submit email verification code
            $('#submit').click(function () {
                var data = {
                    'username' : $('#username').val(),
                    'email': $('#email').val(),
                    'code':$('#code').val(),
                }
			
                $.ajax({
                    'url':'/login/submitPsw',
                    'data':data,
                    'dataType':'json',
                    'type':'post',
                    'success':function (res) {
                        if (res == 200){
                            layer.msg("The password has been reset to the top six digits of the authentication mailbox!");
                            setTimeout(function () {
                                window.location.href = "/login/login";
                            },800)
                        } else {
                            layer.msg("Verification failed!");
                        }
                    }
                })
            })
        })
    </script>

Page display

2. Login controller code

To realize the controller code, it should be noted that when the verification code is successfully sent, the verification code should be stored in the cookie and the 60s time limit should be set, so that there will be no problem with the logic. Otherwise, after the operation time has passed, the user can also modify the password through the previous verification code, so there is no need for the verification code. The following is the detailed code for implementation.

    /*
     * Show forgot password page
     */
    public function forget(){
        $this->layout = false;
    }

    /*
     * Click forget password to generate verification code
     */
    public function findPsw(){
        //get data
        $email = $_POST['email'];
        $username = $_POST['username'];
        //Get user details.
        $login = ClassRegistry::init('Login');
        $data = $login->find_admin($username);
        //Verify that the user mailbox user name matches
        if ($data && $data['Login']['email'] == $email){
            //Generate random number if successful
            $code = rand(1000,9999);
          	//Generate cookie name, which is unique here
            $name = 'emailCode'.$username;
            //Stored cookie s expire after 60 seconds.
            setcookie($name,$code,time()+60);
            //Here is the content of the email
            $content ="<h1>Your verification code is:".$code."</h1>";
            //Call the encapsulated sendmail method
            $res = $this->email->sendmail($email,$content);
            if ($res == 1){
                exit(json_encode(200));
            }else{
                exit(json_encode(400));
            }
        }
        exit(json_encode(401));
    }


    /*
     * Verification code and mailbox
     */
    public function submitPsw(){
        //receive data 
        $post = $_POST;
        //Splice cookie name
        $name = 'emailCode'.$post['username'];
        //Get the verification code stored in the cookie
        $code = $_COOKIE[$name];
        //Get user information
        $login = ClassRegistry::init('Login');
        $data = $login->find_admin($post['username']);
        //Verify again whether the mailbox matches the user and whether the verification code is entered successfully.
        if ($data['Login']['email'] == $post['email'] && $data['Login']['username'] == $post['username'] && $code = $post['code']){
            //Intercept the top six of the mailbox
            $password = substr($post['email'],'0','6');
            //Encryption operation
            $password = $this->publicFunction->encrypt($password);
            //Password for modification
            $data['Login']['password'] = $password;
            $admin = ClassRegistry::init('Admin');
            $data = $admin->dellAdmin($data['Login']);
            exit(json_encode(200));
        }else{
            exit(json_encode(400));
        }
    }
3. Encapsulated PHPemail code

The email sending code encapsulated here is placed in the cakephp component, and all controllers can access it. For the definition and use of cakephp component, please see another article. I have already explained the smtp password and e-mail here. For the specific implementation, please refer to my previous article article.

<?php
/**
 * Created by PhpStorm.
 * User: 
 * Date: 2021/7/14
 * Time: 16:23
 */


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../../vendors/phpmailer/phpmailer/src/Exception.php';
require '../../vendors/phpmailer/phpmailer/src/PHPMailer.php';
require '../../vendors/phpmailer/phpmailer/src/SMTP.php';

App::uses('Component', 'Controller');

class EmailComponent extends Component
{
    /*
     * Transfer parameters
     * $params $email Receiving email address
     * $params $content Mailbox content
     */
    function sendmail($email,$content){
//Initialization parameters
     $mail = new PHPMailer(true);
     try{
         //Server configuration
         $mail->CharSet ="UTF-8";                     //Set mail code
         $mail->SMTPDebug = 0;                        // Debug mode output
         $mail->isSMTP();                             // Using SMTP
         $mail->Host = 'smtp.qq.com';                // SMTP server
         $mail->SMTPAuth = true;                      // Allow SMTP authentication
         $mail->Username = '';                // SMTP user name is the user name of the mailbox
         $mail->Password = '';             // SMTP password part of mailbox is authorization code
         $mail->SMTPSecure = 'ssl';                    // Allow TLS or ssl protocols
         $mail->Port = 465;                            // Server port 25 or 465 depends on the mailbox server support

         $mail->setFrom('', 'wyqgg');  //Sender
         $mail->addAddress($email, 'wyq');  // addressee
         //$mail->addAddress(' ellen@example.com ');  //  Multiple recipients can be added
         $mail->addReplyTo('', 'info'); //Which email should I reply to when replying? The suggestion is consistent with the sender
         //Content
         $mail->isHTML(true);                                  // Whether to send in HTML document format. After sending, the client can directly display the corresponding HTML content
         //title
         $mail->Subject = 'Login prompt' . time();
         //Main part
         $mail->Body    = $content . date('Y-m-d H:i:s');
         $mail->AltBody = 'If the mail client does not support HTML This content is displayed';

         $mail->send();
         return 1;
     }catch (Exception $e){
         return 0;
     }
 }
}
Summary:

For me, the implementation of background page code is more complex, and the implementation of background controller and model code is still relatively basic.

Topics: PHP JQuery