This is the third day of my participation in the First Challenge 2022
preface
Recently, I summarized the login page that we often make to complete the login and registration functions. Today, XIAobian will take Express + Mongoose as an example to achieve the corresponding functions. Let’s follow me and have a look.
steps
1. Build a server (app.js) with Express, download the corresponding package, and configure the corresponding configuration.
The template engine I use is EJS, with an HTML suffix, and the corresponding configuration is:
// App.engine ('.html', ejs.renderfile) app.set('view engine', 'ejs')Copy the code
The middle of the third party is body-parser, and the corresponding configuration is:
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Copy the code
Of course, login and registration must use session, which can be used to store the content of the verification code and limit the route to decide whether to allow. The package I use is express-Session, configured and commented accordingly as follows:
App. use(session({secret: 'this is session', // server generates session name: "redspider", // change the name of the cookie corresponding to the session resave: SaveUninitialized: true, // Force the unsaved session cookie to be saved: {maxAge: 1000 * 60 * 60 * 24, secure: False //true indicates that only HTTPS can access cookie}, rolling: true // forcibly set cookie on each request, which resets cookie expiration time}))Copy the code
The app.js configuration is as follows:
const express = require('express'); const app = express(); Const bodyParser = require('body-parser') const ejs = require('ejs') const session = require('express-session') // Import routing modules Const admin = require('./routes/admin') // configure app.engine('.html', ejs.renderfile) app.set('view engine', 'ejs') // Configure static web directory app.use(express.static("static")) // Third-party middleware to get post submitted data app.use(bodyParser.urlencoded({extended: False}) app.use(bodyParser.json()) app.use(session({secret: 'this is session', // server generates session name: "Redspider ", // change the name of the cookie corresponding to the session resave: false, // force the session to be saved even if it is not changed saveUninitialized: True, // Force unsaved session cookie: {maxAge: 1000 * 60 * 60 * 24, secure: false //true means only HTTPS can access cookie}, rolling: True // Forcibly set cookies on each request, Use ('/admin', admin) // Listen to port app.listen(3000, () => {console.log('server is running'); })Copy the code
2. Configure the routing module
Use (‘/admin’, admin) : import the admin route, app.use(‘/admin’, admin)
Note: if you are simply creating a login page and don’t need to have so many layers nested, I have other features here.
Admin.js is configured as follows:
Router() const url = require("url") // introduce module const manager = Router. use('/manager', require('./admin/manager') const login = require('./admin/login') manager) router.use('/login', login) module.exports = routerCopy the code
The login.js configuration is as follows:
const express = require('express'); const router = express.Router(); const svgCaptcha = require('svg-captcha'); const ManagerModel = require('.. /.. /model/mangerModel') const md5 = require('md5'); / / login module router. Get ('/', (the req, res) = > {res. Send (" login ")}) / / logged on the router. The get ('/loginout '(the req, Res) => {res.send("loginout")}) Router. Post ('/register', async(req, async)) => {res.send("verify")}) Router.post ('/dologin', async(req, async)) => {res.send("register")}) res) => { res.send("dologin") }) module.exports = routerCopy the code
The routes on the login page correspond to login, logout, registration, and verification codes.
3. The route configured with login.js implements corresponding functions.
When the route is /admin/login, we render the login interface (login.html) through the EJS template engine. The login. HTML:
<body> <! -- login area start --><div class="login-register-area pt-100px pb-100px">
<div class="container">
<div class="row">
<div class="col-lg-7 col-md-12 ml-auto mr-auto">
<div class="login-register-wrapper">
<div class="login-register-tab-list nav">
<a class="active" data-bs-toggle="tab" href="#lg1">
<h4>login</h4>
</a>
<a data-bs-toggle="tab" href="#lg2">
<h4>register</h4>
</a>
</div>
<div class="tab-content">
<div id="lg1" class="tab-pane active">
<div class="login-form-container">
<div class="login-register-form">
<form action="/admin/login/dologin" method="post">
<input type="text" name="username" placeholder="Username" id="username" />
<input type="password" name="password" placeholder="Password" id="password" />
<div>
<input type="captcha" id="verify" name="verify" placeholder="captcha" width="100px" />
<img src="/admin/login/verify" title="I can't see it, hit Refresh." onclick="javascript:this.src='/admin/login/verify? mt='+Math.random()">
</div>
<div class="button-box">
<div class="login-toggle-btn">
<input type="checkbox" />
<a class="flote-none" href="javascript:void(0)">Remember me</a>
<a href="#">Forgot Password?</a>
</div>
<button type="submit"><span>Login</span></button>
</div>
</form>
</div>
</div>
</div>
<div id="lg2" class="tab-pane">
<div class="login-form-container">
<div class="login-register-form">
<form action="/admin/login/register" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input placeholder="Email" type="email" name="email" />
<div class="button-box">
<button type="submit"><span>Register</span></button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<! -- login area end -->
<script src="/login/js/vendor/vendor.min.js"></script>
<script src="/login/js/plugins/plugins.min.js"></script>
<! -- Main Js -->
<script src="/login/js/main.js"></script>
</body>
Copy the code
Let’s start with the login feature
Then submit the data through the form submit post method,action corresponding to the corresponding route,action =”/admin/login/dologin”, input field corresponding to name to get the value, In the corresponding route in login.js, the username and password are obtained through req.body.username and req.body.password.
Then comes the verification code. I use the package SVG-CAPtCHA to generate the corresponding verification code and save the verification code text in the session. The corresponding configuration is as follows:
const svgCaptcha = require('svg-captcha');
router.get('/verify'.async(req, res) => {
var captcha = svgCaptcha.create();
req.session.captcha = captcha.text;
res.type('svg');
res.status(200).send(captcha.data);
// console.log(req.session.captcha);
})
Copy the code
I also made a click refresh function, as follows:
<img SRC ="/admin/login/verify" title=" onclick="javascript:this. SRC ='/admin/login/verify? mt='+Math.random()">Copy the code
Finally, the user name and password are obtained to check whether there is a matching collection in the database. If there is a matching collection and the verification code is correct, the login succeeds. Of course, you can also do some foreground validation to limit their specifications before doing so, and store matching collections in cookies as well.
Another important point is that the route is allowed through session. If there is no corresponding cookie on the server, the route cannot be allowed. The corresponding configuration in admin.js is as follows
// restrict router. Use ((req, res, next) => {const myURL = new URL(req. URL, 'http://127.0.0.1:3000/'); let pathname = myURL.pathname; // console.log(pathname); if (req.session.userinfo && req.session.userinfo.username) { next() } else { if (pathname == "/login" || pathname == "/login/dologin" || pathname == "/login/register" || pathname == "/login/verify") { next() } else { res.redirect("/admin/login") } } })Copy the code
To log out of the session, jump to the login screen and clear the session data. As follows:
router.get('/loginout', (req, res) => {
req.session.userinfo = null;
res.redirect("/admin/login")
})
Copy the code
4. Mongoose operation database also mentioned above to match data and add data in the database, we of course need to package Mongoose: we set up a folder model to package Mongoose
(1) We set up a connection with the database:
const mongoose = require('mongoose'); const config = require('.. /config/config') mongoose.connect(config.dburl, { useNewUrlParser: true, useUnifiedTopology: true }, function(err) { if (err) { console.log(err); Return} console.log(' connection successful '); }) module.exports = mongoose;Copy the code
(2) Introduce core.js, use the schema specification data to operate the database, and configure managerModel.js:
const mongoose = require('./core')
let ManagerSchema = mongoose.Schema({
username: { type: String },
password: { type: String },
email: { type: String },
mobile: { type: String },
status: { type: Number },
login_time: { type: Number },
add_time: { type: String },
})
module.exports = mongoose.model('Manager', ManagerSchema, 'manager')
Copy the code
(3) Introduce ManagerModel. js in login.js and complete the corresponding functions in the corresponding route. The login and registration functions are as follows:
Post ('/dologin', async(req, res) => { let username = req.body.username let password = req.body.password let verify = req.body.verify // console.log(verify); // console.log(req.session.captcha.toLowerCase()); If (verify.tolowerCase ()! = req.session.captcha.toLowerCase()) { res.render("admin/pubic/error.html", { "redirectUrl": "/admin/login", "message": "Graphical verification code input error"}) return} //2. Let result = await managerModel. find({"username": username, "password": md5(password) }) // console.log(result); Req.session. userinfo = result[0]; if (result.length > 0) {req.session.userinfo = result[0]; Res. render("admin/pubic/success. HTML ", {"redirectUrl": "/admin/manager", "message": } else {res.render("admin/pubic/success.html", {"redirectUrl": "/admin/login", "message": // Register router.post('/register', async(req, res) => { let username = req.body.username let password = req.body.password let email = req.body.email let result = await ManagerModel.find({ "username": username, "password": Md5 (password)}) if (result.length > 0) {res.send(" user already exists ")} else {var newuser = new ManagerModel({"username": username, "password": md5(password), "email": email }) await newuser.save() res.redirect("/admin/login") } }) })Copy the code
The registration function is the same as the login function, but we save the data in the database.
Now I’ll talk about the complete rendering of login.js configuration:
const express = require('express'); const router = express.Router(); const svgCaptcha = require('svg-captcha'); const ManagerModel = require('.. /.. /model/mangerModel') const md5 = require('md5'); Router.get ('/', (req, Res) => {res.render("admin/login/login.html") // res.send(" login ")}) // Exit router. res) => { req.session.userinfo = null; Res.redirect ("/admin/login")}) // Verification code Router.get ('/verify', async(req, res) => {var captcha = svgcaptcha.create (); req.session.captcha = captcha.text; res.type('svg'); res.status(200).send(captcha.data); // console.log(req.session.captcha); }) // Register module router.post('/register', async(req, res) => { let username = req.body.username let password = req.body.password let email = req.body.email let result = await ManagerModel.find({ "username": username, "password": Md5 (password)}) if (result.length > 0) {res.send(" user already exists ")} else {var newuser = new ManagerModel({"username": username, "password": md5(password), "email": Redirect ("/admin/login")}}) router.post('/dologin', async(req, res) => { let username = req.body.username let password = req.body.password let verify = req.body.verify // console.log(verify); // console.log(req.session.captcha.toLowerCase()); If (verify.tolowerCase ()! = req.session.captcha.toLowerCase()) { res.render("admin/pubic/error.html", { "redirectUrl": "/admin/login", "message": "Graphical verification code input error"}) return} //2. Let result = await managerModel. find({"username": username, "password": md5(password) }) // console.log(result); Req.session. userinfo = result[0]; if (result.length > 0) {req.session.userinfo = result[0]; Res. render("admin/pubic/success. HTML ", {"redirectUrl": "/admin/manager", "message": } else {res.render("admin/pubic/success.html", {"redirectUrl": "/admin/login", "message": })}}) module.exports = routerCopy the code
To sum up: login and registration steps are relatively simple, but also relatively easy to start the novice content, think more logical thinking, more through, step by step, come on!