nodejs-set permissions

nodejs-set permissions

Preface

log in Register

registered

  1. Check if the user exists
check The user has a prompt registration failure, User does not exist to perform registration Copy code
  1. Add new user

log in

  1. Check if the user exists

  2. Verify username and password

  3. Return logo

The cookie exists on the client side, and the security is not high The session exists on the server, which has high security. Once the service is hung up, the data will be lost The token exists in the server, and it stores a set of algorithms, which can be cross-domain jsonwebtoken Copy code

User registration

router.post( '/register' , async (req, res) => { try { //1. Check if the user has already registered const sql = 'select * from user2 where username = ?' const {results} = await db. query(sql, req.body.username) //2. Register a new user if (results.length === 0 ) { const sql = 'insert into user2 set ?' const {results} = await db.query(sql, req.body) if (results.affectedRows !== 1 ) return res.send({ status :0 , message : 'Registration failed' }) res.send({ status : 0 , message : 'success' }) } else { res.send({ status : 1 , message : 'user already exists' }) } } catch (error) { res.send({ message : error }) } }) Copy code

log in

router.post( '/login' , async (req, res) => { const sql = 'select * from user2 where username = ?' const {results} = await db.query(sql, req.body.username) if (results.length === 0 ) { return res.send({ status : 0 , message : 'User does not exist' }) } //2. Determine whether the username and password are correct if (results[ 0 ].username === req.body.username && results[ 0 ].password === req.body.password) { //3. Generate token and return Give the client const token = jwt.sign(results[ 0 ].id) console .log(token) res.send({ status : 0 , token }) } }) Copy code

1. Entry file

const express = require ( 'express' ) const path = require ( 'path' ) const app = express() //set cross-domain app.use( require ( 'cors' )()) app.use(express.static(path.join(__dirname, './apidoc' ))) app.use(express.urlencoded({ extended : false })) app.use(express.json()) require ( './routes/index.js' )(app, express) app.listen( 3000 , [ '10.41.153.32' , '127.0.0.1' ], () => { console .log( 'local service http://127.0.0.1:3000' ) console .log( 'remote service http://10.41.153.32:3000' ) }) Copy code

2. ./routes/index.js

const db = require ( '../db' ) const jwt = require ( '../utils/jwt' ) //Generate token const auth = require ( '../middleware/auth' ) //Set permissions module . exports = ( app, express ) => { const ctrl = require ( '../controller' ) const router = express.Router() //Request resource router.get( '/users' , auth, ctrl.getUsers) //Request resource based on id router.get( '/users/:id' , auth, ctrl.getUserById) //Add resource router.post( '/users' , auth, ctrl.addUser) //Update resource according to id router.put( '/users/:id' , auth, ctrl.updateUser) //Delete resource according to id router.delete( '/users/:id' , auth, ctrl.deleteUser) //Register a new user router.post( '/register' , async (req, res) => { try { //1. Check if the user is already registered const sql = 'select * from user2 where username = ?' const {results } = await db.query(sql, req.body.username) //2. Register a new user if (results.length === 0 ) { const sql = 'insert into user2 set ?' const {results} = await db .query(sql, req.body) if (results.affectedRows !== 1 ) return res.send({status : })0 , message : 'Registration failed' res.send({ status : 0 , message : 'success' }) } else { res.send({ status : 1 , message : 'user already exists' }) } } catch (error) { res.send({ message : error }) } }) //Login router.post( '/login' , async (req, res) => { const sql = 'select * from user2 where username = ?' const {results} = await db.query(sql, req.body. username) if (results.length === 0 ) { return res.send({ status : 0 , message : 'User does not exist' }) } //2. Determine whether the username and password are correct if (results[ 0 ].username === req.body.username && results[ 0 ].password === req.body.password) { //3. Generate token and return Give the client const token = jwt.sign(results[ 0 ].id) console .log(token) res.send({ status : 0 , token }) } }) app.use(router) } Copy code

3. Encryption and decryption (../utils/jwt)

const SECRET = 'GAJLGHJALR' const jwt = require ( 'jsonwebtoken' ) module .exports = { //encrypted sign ( id ) { return jwt.sign( { id }, SECRET, { expiresIn : 1000 * 60 * 60 * 24 * 7 } ) }, //Decrypt async verify ( token ) { const {id} = await jwt.verify(token, SECRET) return id } } Copy code

4. set permissions (../middleware/auth)

const jwt = require ( '../utils/jwt' ) const db = require ( '../db' ) module .exports = async (req, res, next) => { const token = req.query.token || req.headers.token || req.body.token || String (req.headers.authorization || '' ).split( '' ).pop() if (!token) { res.send({ status : 1 , message : 'Please log in to check if a valid token is passed' }) } const id = await jwt.verify(token) console .log(id) if (!id) { res.send({ status : 1 , message : 'User does not exist' }) } const sql = 'select * from user2 where id = ?' const {results} = await db.query(sql, id) req.user = results next() } Copy code

5. the control layer (./controller/index.js)

const DB = the require ( '../db' ) const Moment = the require ( 'Moment' ) Module1 .exports = { the async the getUsers ( REQ, RES ) { the try { const SQL = 'SELECT * WHERE from User isdel = 0' const {results} = await db.query(sql) res.send({ status : 0 , message : results }) } catch (error) { res.send({ message : error }) } }, async getUserById ( req, res ) { try { const sql = 'select * from user where isdel = 0 and id = ?' const {results} = await db.query(sql, req.params.id) if (results.length === 0 ) return res.send({ status : 1 , message : 'The hero does not exist' }) res.send({ status : 0 , message : results }) } catch (error) { res.send({ message : error }) } }, async addUser ( req, res ) { try { const sql = 'insert into user set ?' const body = req.body body.add_time = moment().format( 'YYYY-MM-DD HH:mm:ss' ) const {results} = await db.query(sql, body) if (results.affectedRows !== 1 ) return res. send({ status : 1 , message : 'adding failed' }) res.send({ status : 0 , message : 'success' }) } catch (error) { res.send({ message : error }) } }, async updateUser ( req, res ) { try { const sql = 'update user set? where id = ?' const body = req.body body.add_time = moment().format( 'YYYY-MM-DD HH:mm:ss' ) const {results} = await db.query(sql, [body, req.params.id]) if (results.affectedRows !== 1 ) return res.send({ status : 1 , message : 'Update failed' }) res.send({ status : 0 , message : 'success' }) } catch (error) { res.send({ message : error }) } }, async deleteUser ( req, res ) { try { const sql = 'update user set isdel = 1 where id = ?' const {results} = await db.query(sql, req.params.id) if (results.affectedRows != = 1 ) return res.send({ status : 1 , message : 'Deletion failed' }) res.send({ status : 0 , message : 'success' }) } catch (error) { res.send({ message : error }) } } } Copy code

6. Connection layer (./db/index.js)

module .exports = { query ( sql, params = [] ) { return new Promise ( ( resolve, reject ) => { //1. Import mysql const mysql = require ( 'mysql' ) const dbConfig = require ( './db.config' ) //2. Create a connection object const connection = mysql.createConnection(dbConfig) //3. Open the connection connection.connect( err => { if (err) return reject(err.message + '----Database connection failed' ) console .log( 'Database connection succeeded' ) }) //4. Execute the query statement connection.query(sql, params, ( err, results, filds ) => { if (err) return reject(err.message) resolve({ results, filds }) }) //5. Close the connection connection.end( err => { if (err) return reject(err.message) console .log( 'Close the database connection' ) }) }) } } Copy code

./db/db.config.js

module .exports = { host : '127.0.0.1' , user : 'root' , password : 'root' , database : '2101_3' } Copy code

Page rendering

1. Home page (index.html) (add and delete pages)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Hero Management</h1> <a href="./add.html" class="btn btn-success pull-right">Add</a> <table class="table table-striped table-hover"> <thead> <tr> <th>Serial number</th> <th>Name</th> <th>Age</th> <th>Gender</th> <th>Time</th> <th>Operation</th> </tr> </thead> <tbody id="tbody"> </tbody> </table> </div> <script src="./js/jquery.min.js"></script> <script> function getUsers() { //Get local token const token = localStorage.token console.log(token) $(function () { $.ajax({ url:'http://10.41.153.32:3000/users', //Send a network request with token headers: { Authorization:'Bearer '+ token }, success(res) { let html ='' res.message.forEach(item => { html += ` <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.age}</td> <td>${item.sex}</td> <td>${item.add_time}</td> <td> <a href="./edit.html?id=${item.id}" class="btn btn-primary">Edit</a> <button type="button" class="btn btn-danger" data-id="${item.id}" id="deleteUsers">Delete</button> </td> </tr> ` }) $('#tbody').html(html) } }) }) } getUsers() $('#tbody').on('click','#deleteUsers', function () { //console.log($(this).data('id')) $.ajax({ type:'delete', url:'http://10.41.153.32:3000/users/' + $(this).data('id'), success(res) { console.log(res) //location.reload() getUsers() } }) }) </script> </body> </html> Copy code

2. Add (add.html)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Add hero</h1> <form> <div class="form-group"> <label for="">Name</label> <input type="text" class="form-control" id="name" placeholder="Input field"> </div> <div class="form-group"> <label for="">Age</label> <input type="text" class="form-control" id="age" placeholder="Input field"> </div> <div class="form-group"> <label for="">Gender</label> <input type="text" class="form-control" id="sex" placeholder="Input field"> </div> <button type="button" class="btn btn-primary" id="addForm">Submit</button> </form> </div> <script src="./js/jquery.min.js"></script> <script> $(function () { //1. Get the parameters to be passed $('#addForm').click(function () { var data = { name: $('#name').val(), age: $('#age').val(), sex: $('#sex').val() } //2. Send an ajax request $.ajax({ type:'post', url:'http://10.41.153.32:3000/users', data, success(res) { console.log(res) //3. Manually jump to the homepage location.href ='/' } }) }) }) </script> </body> </html> Copy code

3. Edit (edit.html)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Edit hero</h1> <form id="editForm"> </form> </div> <script src="./js/jquery.min.js"></script> <script> $(function () { //const id = location.search.split('=')[1] const params = new URLSearchParams(location.search) const id = params.get('id') $.ajax({ url:'http://10.41.153.32:3000/users/' + id, success(res) { let html = ` <div class="form-group"> <label for="">Name</label> <input type="text" class="form-control" id="name" value="${res.message[0].name}"> </div> <div class="form-group"> <label for="">Age</label> <input type="text" class="form-control" id="age" value="${res.message[0].age}"> </div> <div class="form-group"> <label for="">Gender</label> <input type="text" class="form-control" id="sex" value="${res.message[0].sex}"> </div> <button type="button" class="btn btn-primary" id="editUsers">Submit</button> ` $('#editForm').html(html) } }) //1. Get the parameters to be passed $('#editForm').on('click','#editUsers', function () { console.log(1) var data = { name: $('#name').val(), age: $('#age').val(), sex: $('#sex').val() } //2. Send an ajax request $.ajax({ type:'put', url:'http://10.41.153.32:3000/users/' + id, data, success(res) { //3. Manually jump to the homepage location.href ='/' } }) }) }) </script> </body> </html> Copy code

4. Login (login.html)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Please log in to your account</h1> <form> <div class="form-group"> <label for="">Username</label> <input type="text" class="form-control" id="username" value="admin"> </div> <div class="form-group"> <label for="">Password</label> <input type="password" class="form-control" id="password" value="admin"> </div> <button type="button" class="btn btn-primary" id="loginForm">Login</button> </form> </div> <script src="./js/jquery.min.js"></script> <script> $(function () { //1. Get the parameters to be passed $('#loginForm').click(function () { var data = { username: $('#username').val(), password: $('#password').val(), } console.log(data) //2. Send an ajax request $.ajax({ type:'post', url:'http://10.41.153.32:3000/login', data, success(res) { //console.log('success') //Save the token to local storage localStorage.token = res.token location.href ='./index.html' } }) }) }) </script> </body> </html> Copy code