用戶登錄少不了密碼,上一篇只用nickname進行驗證。這一篇加上使用md5加密的password作為另一個條件進行登錄驗證。
需求
- 通過nickname和password(md5加密后)進行驗證登錄,查詢數據庫user表驗證nickname和password
- 存在nickname並且password解密后與數據數據對應成功則生成token返回
- 反之返回{code:400,msg:'登錄失敗'}
- 為了方便操作,加入了一個字符串md5加密的接口(user/getMd5/:data)
- 傳入字符串返回md5加密的密文字符串
環境
- 數據庫(mysql)
- 數據庫名稱(database):test,用戶名(user):root,密碼(password):123456
- 數據庫user表做了一些改變,新加一個password字段
- 依賴包(package.json)
- 確保安裝以下依賴包
實現
- config/config.default.js
/* eslint valid-jsdoc: "off" */ 'use strict'; /** * @param {Egg.EggAppInfo} appInfo app info */ module.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = exports = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1576461360545_5788'; // add your middleware config here config.middleware = []; config.jwt = { secret: '123456', }; // 安全配置 (https://eggjs.org/zh-cn/core/security.html) config.security = { csrf: { enable: false, ignoreJSON: true, }, // 允許訪問接口的白名單 domainWhiteList: [ 'http://localhost:8080' ], }; // 跨域配置 config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', }; config.sequelize = { dialect: 'mysql', host: '127.0.0.1', port: '3306', user: 'root', password: '123456', database: 'test', define: { underscored: true, freezeTableName: true, }, }; // add your user config here const userConfig = { // myAppName: 'egg', }; return { ...config, ...userConfig, }; };
- config/plugin.js
'use strict'; /** @type Egg.EggPlugin */ module.exports = { jwt: { enable: true, package: 'egg-jwt', }, cors: { enable: true, package: 'egg-cors', }, sequelize: { enable: true, package: 'egg-sequelize', }, };
- app/model/user.js
'use strict'; module.exports = app => { const { STRING, INTEGER } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, nickname: STRING(20), password: STRING(50), }, { timestamps: false, }); return User; };
- app/service/user.js
'use strict'; const Service = require('egg').Service; const crypto = require('crypto'); function toInt(str) { if (typeof str === 'number') return str; if (!str) return str; return parseInt(str, 10) || 0; } class UserService extends Service { // 查詢user表,驗證密碼和花名 async validUser(nickname, password) { const data = await this.getUser(); const pwd = crypto.createHash('md5').update(password).digest('hex'); for (const item of data) { if (item.nickname === nickname && item.password === pwd) return true; } return false; } // 獲取用戶,不傳id則查詢所有 async getUser(id) { const { ctx } = this; const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) }; if (id) { return await ctx.model.User.findByPk(toInt(id)); } return await ctx.model.User.findAll(query); } // 專門對數據進行md5加密的方法,輸入明文返回密文 getMd5Data(data) { return crypto.createHash('md5').update(data).digest('hex'); } } module.exports = UserService;
- app/controller/user.js
'use strict'; const Controller = require('egg').Controller; class UserController extends Controller { // 登錄 async login() { const { ctx, app } = this; const data = ctx.request.body; // 判斷該用戶是否存在並且密碼是否正確 const isValidUser = await ctx.service.user.validUser(data.nickname, data.password); if (isValidUser) { const token = app.jwt.sign({ nickname: data.nickname }, app.config.jwt.secret); ctx.body = { code: 200, msg: '登錄成功', token }; } else { ctx.body = { code: 400, msg: '登錄失敗' }; } } // 獲取所有用戶 async index() { const { ctx } = this; ctx.body = await ctx.service.user.getUser(); } // 通過id獲取用戶 async show() { const { ctx } = this; ctx.body = await ctx.service.user.getUser(ctx.params.id); } async getMd5Data() { const { ctx } = this; ctx.body = await ctx.service.user.getMd5Data(ctx.params.data); } } module.exports = UserController;
- app/router.js
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller, jwt } = app; router.get('/', controller.home.index); router.post('/user/login', controller.user.login); // 查詢 router.get('/user', controller.user.index); router.get('/user/:id', jwt, controller.user.show); // 生成經過md5加密后的密文 router.get('/user/getMd5/:data', controller.user.getMd5Data); };
- package.json
{
"name": "jwt", "version": "1.0.0", "description": "", "private": true, "egg": { "declarations": true }, "dependencies": { "egg": "^2.15.1", "egg-cors": "^2.2.3", "egg-jwt": "^3.1.7", "egg-scripts": "^2.11.0", "egg-sequelize": "^5.2.0", "mysql2": "^2.0.2" }, "devDependencies": { "autod": "^3.0.1", "autod-egg": "^1.1.0", "egg-bin": "^4.11.0", "egg-ci": "^1.11.0", "egg-mock": "^3.21.0", "eslint": "^5.13.0", "eslint-config-egg": "^7.1.0" }, "engines": { "node": ">=10.0.0" }, "scripts": { "start": "egg-scripts start --daemon --title=egg-server-jwt", "stop": "egg-scripts stop --title=egg-server-jwt", "dev": "egg-bin dev", "debug": "egg-bin debug", "test": "npm run lint -- --fix && npm run test-local", "test-local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", "ci": "npm run lint && npm run cov", "autod": "autod" }, "ci": { "version": "10" }, "repository": { "type": "git", "url": "" }, "author": "", "license": "MIT" }
自測
- 花名(nickname)和密碼(password)登錄
- 為了方便開發,臨時加入獲取md5數據加密的接口
- 通過id查詢user,需要傳token
- 查詢所有user,不用傳token