提示:学习express,搭建管理系统
文章目录
- 前言
- 一、安装jsonwebtoken
- 二、新建config/jwt.js
- 三、修改models/user.js
- 四、修改routes下的user.js
- 五、修改index.js
- 六、Api新建user/queryUserList接口
- 七、token验证失败示例
- 总结
前言
需求:主要学习express,所以先写service部分
一、安装jsonwebtoken
npm install jsonwebtoken --save
二、新建config/jwt.js
jwt.js
const jsonwebtoken = require('jsonwebtoken');
const secretKey = 'longlongago';
const jwt = {
sign:(data,params,key)=>{
return jsonwebtoken.sign(data,key||secretKey,{expiresIn:60*60,...params});
},
verify:(authorization,key)=>{
let token = authorization.includes('Bearer')?authorization.replace('Bearer ',''):authorization;
return jsonwebtoken.verify(token,key||secretKey,(err,data)=>{
if(err)return {success:false,msg:'token验证失败'}
return {success:true,msg:'token验证成功'}
});
},
}
module.exports = jwt;
三、修改models/user.js
const query = require('../config/db');
const bcrypt = require('../config/bcrypt');
const md5 = require('md5');
const jwt = require('../config/jwt');
const secretKey = 'longlongago';
const errFun = (msg,code)=>{
return {
code:code||500,
success:false,
msg:msg||'操作失败'
}
}
const sucFun = (data,msg)=>{
return {
code:200,
success:true,
msg:msg||'操作成功',
data,
}
}
const userDao = {
//注册
register:async(data)=>{
//验证账号密码格式
const validateResult =userDao.validateUserNameAndPassword(data);
if(!validateResult.success)return errFun(validateResult.msg);
//查询用户名是否已存在
const userResult = await userDao.queryUserByUserName(data);
if(userResult.success)return errFun('用户名已存在');
//生成userId
const userId = md5(data.userName+secretKey);
//加密password
const password = bcrypt.hash(data.password+secretKey);
//根据userName查询user
const sql = `insert into user (userId,userName,password) values('${userId}','${data.userName}','${password}')`;
const result = await query(sql);
if(result&&result.affectedRows==1)return sucFun({},'添加用户成功');
return errFun('添加用户失败');
},
//登录
login:async(data)=>{
//验证账号密码格式
const validateResult =userDao.validateUserNameAndPassword(data);
if(!validateResult.success)return errFun(validateResult.msg);
//查询用户是否存在
const userResult = await userDao.queryUserByUserName(data);
if(!userResult.success)return errFun('用户名错误');
//验证密码是否正确
const comparePassword = bcrypt.compare(data.password+secretKey,userResult.data.password);
//生成token并返回
userResult.data.token = jwt.sign(data);
if(comparePassword)return sucFun(userResult.data,'登录成功');
return errFun('密码错误');
},
//通过用户名查询用户信息
queryUserByUserName:async(data)=>{
//根据userName查询user
const sql = `select * from user where userName='${data.userName}'`;
const result = await query(sql);
if(result&&result.length>0)return sucFun(result[0],'查询用户成功');
return errFun('查询用户失败');
},
//验证用户名密码
validateUserNameAndPassword:(data)=>{
//只包含大小写字母数字,包含1种即可
let nameReg = /[\da-zA-z]{6,16}$/;
let nameValidate = nameReg.test(data.userName);
if(!nameValidate)return errFun('用户名格式错误');
//大写字母,小写字母,特殊符号,包含2种以上
passwordReg = /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![~!@#$%^&*.]+$)[\da-zA-z~!@#$%^&*.]{6,16}$/;
let passwordValidate = passwordReg.test(data.password);
if(!passwordValidate)return errFun('密码格式错误');
return sucFun({},'用户名和密码格式正确');
},
//获取用户列表
queryUserList:async()=>{
//根据userName查询user
const sql = `select userId,userName from user`;
const result = await query(sql);
if(result&&result.length>0)return sucFun(result,'查询用户列表成功');
return errFun('查询用户列表失败');
},
}
module.exports = userDao;
四、修改routes下的user.js
const userDao = require('../models/user');
const userRoutes = (router)=>{
router.post('/user/register',async (req,res)=>{
const result = await userDao.register(req.body);
res.json(result);
});
router.post('/user/login',async (req,res)=>{
const result = await userDao.login(req.body);
res.json(result);
});
router.post('/user/queryUserList',async (req,res)=>{
const result = await userDao.queryUserList(req.body);
res.json(result);
});
}
module.exports = userRoutes;
五、修改index.js
const express = require('express');
const app = express();
const router = express.Router();
const jwt = require('./config/jwt');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const port = 1990;
//全局验证token
app.use('/*',(req,res,next)=>{
let notValidateData = ['/user/login','/user/register'];
if(notValidateData.indexOf(req.baseUrl)>-1)return next();
if((jwt.verify(req.headers.authorization||'')||{}).success)return next();
return res.json({success:false,code:500,msg:'token验证失败'});
})
//初始化路由
require('./routes/index')(router);
app.use('/', router);
app.listen(port,()=>{
console.log('http://localhost:'+port);
})
六、Api新建user/queryUserList接口
url:http://localhost:1990/user/login
name:/user/login
headers:{
“Authorization”:“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6Imxvbmdsb25nYWdvMSIsInBhc3N3b3JkIjoibG9uZzEyMzQ1NiIsImlhdCI6MTcwOTAzMzE2OCwiZXhwIjoxNzA5MDM2NzY4fQ.KMHlT7wi8APoQtidXMVbPlW_iFDJvFXz2f7HUclhAbA”,
}
七、token验证失败示例
添加用户
url:http://localhost:1990/user/register
name:/user/register
headers:{
“Authorization”:“123456789”
}
总结
踩坑路漫漫长@~@