前一篇實現了基本的生成token和驗證token的功能,這其實並沒什么用。這一篇主要實現對數據庫里的人員進行驗證。
需求
- 登錄:查詢數據庫的user表驗證該人員是否存在
- user表中存在該nickname,生成token返回
- user表中不存在該nickname,返回{code:'404',msg:'不存在該人員'}
- 查詢
- 查詢所有user,無需傳token
- 通過id查詢指定user,需要傳token
- 狀態碼
- 201:成功
- 404:不存在
- 400:業務邏輯錯誤
實現
- 數據庫表沒有變,依舊只有一張user表
- 數據庫名稱(database):test,用戶名(user):root,密碼(password):123456

- 在egg實現登錄鑒權(一)的基礎之上繼續安裝依賴包
- npm install --save egg-cors egg-jwt
- 目錄
- 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), }, { timestamps: false, }); return User; };
- 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 isValid = await ctx.service.user.isValidUser('nickname', data.nickname); if (isValid) { const token = app.jwt.sign({ nickname: data.nickname, }, app.config.jwt.secret); ctx.body = token; } else { ctx.body = { code: 404, 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); } } module.exports = UserController;
- app/service/user.js
'use strict'; const Service = require('egg').Service; function toInt(str) { if (typeof str === 'number') return str; if (!str) return str; return parseInt(str, 10) || 0; } class UserService extends Service { // 查詢test數據庫user表,驗證是否存在該用戶 async isValidUser(key, value) { const data = await this.getUser(); for (const item of data) { if (item[key] === value) 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); } } module.exports = UserService;
- 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); };
- 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" }
自測
- 登錄

- 查詢所有

- 查詢指定id的人員

