Eggjs Learning Notes Day 33: eggjs creates a base class base.js controller, configures session, and creates a tool.js service (svg-captcha verification code)

1. Create base classes.

The role of base classes: for example, login success and failure, administrator new edit success and failure, role new edit success and failure, there are success callbacks and failure callbacks, such as showing a successful information failure, these things are common.So encapsulated with base classes, other classes can reuse code by inheriting this base class.

Controller>admin New base.js

Write a simple base class:

"use strict";

const Controller = require("egg").Controller;

class BaseController extends Controller {
  async success() {
    this.ctx.body = "Success";
  }
}

module.exports = BaseController;

Other controllers are introduced and inherited from baseController.

"use strict";

const BaseController = require("../admin/base");

class LoginController extends BaseController {
  async index() {
    console.log("admin");
    await this.ctx.render("admin/login.html");
  }
}

module.exports = LoginController;

Introduce success.html and error.html in view>admin>public

Type:

<%- include ../public/page_header.html %>

    <meta http-equiv="refresh" content="3;url=<%=redirectUrl%>">

    <div class="container-fluid">
        <div class="row">
            <%- include ../public/page_sidebar.html %>

                <div class="col-sm-10">

                    <div class="alert alert-success">

                        <h2>Operation Successful!</h2>

                        <br/>

                        <p>If you do not make a choice, you will jump to the first link address in 3 seconds.</p>

                    </div>

                </div>
            </div>
        </div>
    </div>
</body>
</html>
<%- include ../public/page_header.html %>

    <meta http-equiv="refresh" content="3;url=<%=redirectUrl%>">

    <div class="container-fluid">
        <div class="row">
            <%- include ../public/page_sidebar.html %>
                <div class="col-sm-10">

                    <div class="alert alert-danger">

                        <h2>operation failed!</h2>

                        <br/>

                        <p>If you do not make a choice, you will jump to the first link address in 3 seconds.</p>

                    </div>

                </div>
            </div>
        </div>
    </div>
</body>
</html>

Configure a routing rule for doLogin:

  router.get("/admin/doLogin", controller.admin.login.doLogin);

Write in controller: call base class succ method, pass in redirected url.

async doLogin() {
    await this.success("/admin/login");
  }

This meta tag code jumps redirectUrl after accessing 3s, which is / admin/login above

    <meta http-equiv="refresh" content="3;url=<%=redirectUrl%>">

Jump to the login page after 3s.

 

2. Configuring session s

Cong>config.default.js Type

config.session = {
    key: "SESSION_ID",
    maxAge: 864000,
    httpOnly: true,
    encrypt: true,
    renew: true // Extend session validity
  };

 

3. Create tool.js service

The implementation of Authentication Code (to prevent malicious attacks, malicious irrigation) is mainly used in the svg-captcha plug-in

cnpm install --save svg-captcha

Write code methods in base classes, using the Authentication Code plug-in

"use strict";

const Controller = require("egg").Controller;
var svgCaptcha = require("svg-captcha");

class BaseController extends Controller {
  async success(redirectUrl) {
    console.log("redirectUrl");
    console.log(redirectUrl);
    await this.ctx.render("admin/public/success", {
      redirectUrl: redirectUrl
    });
  }
  async error(redirectUrl) {
    await this.ctx.render("admin/public/error", {
      redirectUrl: redirectUrl
    });
  }
  async code() {
    var captcha = svgCaptcha.create();
    this.ctx.session.code = captcha.text; //Verification Code Information Above
    this.ctx.response.type = "image/svg+xml"; // Specify the type of return
    this.ctx.body = captcha.data; // Return a picture to the page
  }
}

module.exports = BaseController;

Configure Routing:

router.get("/admin/code", controller.admin.base.code);

Access/admin/code, available: Authentication Code Picture

 

Modify the Authentication Code logic in login.html: the src of img is given to/admin/code, which can be rendered normally, and onclick src binds random numbers to ensure that you can switch the Authentication Code by clicking on the picture.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>User Login</title>

    <link rel="stylesheet" href="/public/admin/css/login.css">
  </head>
  <body>
    <div class="container">
      <div id="login">
        <form action="/yuqing/admin.php?m=Public&amp;a=login" method="post" id="myform">
          <input type="hidden" name="ajaxlogin" id="ajaxlogin">
          <input type="hidden" name="ajaxcode" id="ajaxcode">
          <div class="l_title">Background Management System of Millet Shop-IT camp</div>
          <dl>
            <dd>Administrator name:<input class="text" type="text" name="username" id="username"></dd>
            <dd>Administrator password:<input class="text" type="password" name="password" id="password"></dd>
            <dd>Testing card Code:<input id="verify" type="text" name="verify">
              <img id="verify_img" src="/admin/code" title="Invisibility?Click Refresh" onclick="javascript:this.src='/admin/code?mt='+Math.random()">
            </dd>
            <dd><input type="submit" class="submit" name="dosubmit" value=""></dd>
          </dl>
        </form>
      </div>
    </div>

  </body>
</html>

 

Other configurations for the Authentication Code plug-in: width, height, size, background color, etc.

async code() {
    var captcha = svgCaptcha.create({
      size: 6,
      fontSize: 50,
      width: 100,
      height: 40,
      background: "#cc9966"
    });
    this.ctx.session.code = captcha.text; //Verification Code Information Above
    this.ctx.response.type = "image/svg+xml"; // Specify the type of return
    this.ctx.body = captcha.data; // Return a picture to the page
  }

Verification codes are used for both front-end and back-end functions, so they are encapsulated into public services for the following modifications;
Create a new tools.js encapsulation generation verification code method under app>service.

"use strict";

const Service = require("egg").Service;
var svgCaptcha = require("svg-captcha");
class ToolsService extends Service {
  // Methods for generating verification codes
  async captcha() {
    var captcha = svgCaptcha.create({
      size: 6,
      fontSize: 50,
      width: 100,
      height: 40,
      background: "#cc9966"
    });
    console.log(this.ctx.session.code);
    this.ctx.session.code = captcha.text; //Verification Code Information Above
    return captcha;
  }
}

module.exports = ToolsService;

Called under the controller as follows:

async code() {
    var captcha = await this.service.tools.captcha(); // Method that invokes a service generates a validation code
    this.ctx.session.code = captcha.text; //Verification Code Information Above
    this.ctx.response.type = "image/svg+xml"; // Specify the type of return
    this.ctx.body = captcha.data; // Return a picture to the page
  }

Function is still the same, bag, sleep!

Tags: Front-end Session xml PHP Javascript

Posted on Mon, 18 May 2020 09:53:22 -0700 by wkerplunk