当前位置:网站首页>NodeJs实现token登录注册(KOA2)
NodeJs实现token登录注册(KOA2)
2022-07-23 13:15:00 【佚名的热心网友】
源码
https://github.com/NaCl-131/node-study.git
把该安装的安装好
npm install koa
npm i nodemon -D # 保存自动更新
npm i koa-router # 路由
npm i koa-body #解析post的传参
npm i mysql2 sequelize #mysql和一个ORM工具
npm i jsonwebtoken #JWT
npm i dotenv #.env文件
入口
main.js引入:
const koa = require('koa');
const app = new koa();
const koaBody = require("koa-body");
app.use(koaBody())
const router = require("../src/router/user.route")
app.listen(8080, () => {
})
app.use(router.routes())
路由引入:
const Router = require('koa-router')
const {
register,
login
} = require('../sequelize/controller/user.controller')
const {
userDelete
} = require("../sequelize/controller/other.controller");
const router = new Router();
// const router = new Router({ prefix: '/users' })
// 注册接口
router.post('/register', register)
// 登录接口
router.post('/login', login)
module.exports = router
操作
创建三个文件:controller,model,service。
分别作用是进行主要操作,数据库管理,进行数据库操作。
控制层:
const {
createUser,
UserExistJudge,
UserPasswordJudge
} = require('../service/user.service')
class UserController {
async register(ctx, next) {
// 1. 获取数据
// console.log(ctx.request.body)
const {
user_name,
password
} = JSON.parse(ctx.request.body)
// 2. 操作数据库
const isUserExist = await UserExistJudge(user_name)
if (isUserExist) {
ctx.body = {
code: 0,
message: '用户名已存在',
result: {
},
}
} else {
const res = await createUser(user_name, password);
ctx.body = {
code: 0,
message: '用户注册成功',
result: {
id: res.id,
user_name: res.user_name,
},
}
}
}
async login(ctx, next) {
const {
user_name,
password
} = JSON.parse(ctx.request.body)
const isUserExist = await UserExistJudge(user_name);
if (isUserExist) {
//登录成功
let UserInfo = await UserPasswordJudge(user_name, password);
if (UserInfo.UserPasswordTrue) {
ctx.body = {
code: 0,
message: '登录成功!',
result: {
id: UserInfo.id,
user_name: UserInfo.user_name,
token: UserInfo.token
},
}
} else {
ctx.body = {
code: 0,
message: '密码错误!',
result: {
},
}
}
} else {
ctx.body = {
code: 0,
message: '用户名不存在!',
result: {
},
}
}
}
}
module.exports = new UserController()
服务层:
const User = require('../model/user');
const jwt = require('jsonwebtoken');
const {
TOKEN_SECRET
} = require('../../config/config.default')
class UserService {
// 插入用户数据
async createUser(user_name, password) {
// 插入数据
const res = await User.create({
// 表的字段
user_name: user_name,
password: password
})
console.log(res)
return res.dataValues
}
// 判断用户是否存在
async UserExistJudge(user_name) {
const res = await User.findAll({
where: {
user_name: user_name
}
})
if (res.length !== 0) {
return true;
} //用户名存在
else return false; //不存在
}
// 判断用户密码
async UserPasswordJudge(user_name, password) {
const user = await User.findAll({
where: {
user_name
}
})
const token = await getToken({
user_name,
// password,密码不要放进token
is_admin: user[0].is_admin
})
return {
UserPasswordTrue: user[0].password === password,
user_name: user[0].user_name,
id: user[0].id,
token: token
}
}
//验证用户token
async tokenVerify(token) {
return jwt.verify(token, TOKEN_SECRET);
}
}
let getToken = async (body) => {
const token = jwt.sign(body, TOKEN_SECRET);
return token;
}
module.exports = new UserService()
数据库:
const {
DataTypes
} = require('sequelize')
const seq = require('../line')
// 创建模型(Model zd_user -> 表 zd_users)
const User = seq.define('zd_user', {
// id 会被sequelize自动创建, 管理
user_name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
comment: '用户名, 唯一',
},
password: {
type: DataTypes.CHAR(64),
allowNull: false,
comment: '密码',
},
is_admin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: 0,
comment: '是否为管理员, 0: 不是管理员(默认); 1: 是管理员',
},
})
// 强制同步数据库(创建数据表)
// User.sync({ force: true })
module.exports = User
效果:
注册:
登录:
边栏推荐
- pytest接口自动化测试框架 | 控制测试用例执行
- 三方支付公司有哪些?
- Sealing agent glycerol sealing neutral resin sealing dosage form
- 【C语言】结构体、枚举和联合体
- Backup and restore of database
- Fastadmin, non super administrator, has been granted batch update permission, but it still shows no permission
- Custom JSTL tag of JSP
- TOPSIS法(MATLAB)
- The new business form of smart civil aviation has emerged, and Tupo digital twin has entered the civil aviation flight network of the Bureau
- 15001.系统设计方案
猜你喜欢

O3DF执行董事Royal O’Brien:开源没有边界,所有共享的声音都会变成实际方向

Microcomputer principle and technical interface practice in class

动态规划背包问题之多重背包详解

ESP8266-NodeMCU——从苏宁API获取实时天气

Tan Zhangxi, director of risc-v Foundation: risc-v has gradually expanded from the edge to the center

TOPSIS法(MATLAB)

【TensorFlow】检测TensorFlow GPU是否可用

锁相环工作原理,比如我们8MHZ晶振如何让MCU工作在48MHZ或者72MHZ呢

距离IoU损失:包围盒回归更快更好的学习(Distance-IoU Loss: Faster and Better Learning for Bounding Box Regression)

SurFace家族选购参照
随机推荐
Microcomputer principle and technical interface practice in class
《STM32MP1 M4裸机CubeIDE开发指南》第六章 STM32Cube固件包
CNCF基金会总经理Priyanka Sharma:一文读懂CNCF运作机制
MySQL multi table query_ Inner connection_ Show internal connections
系统内存介绍和内存管理
The first stage of basic knowledge of numpy data analysis (numpy Foundation)
fio性能测试工具
Distance IOU loss: faster and better learning for bounding box regression
(resolved) idea compilation gradle project prompt error no symbol found
leetcode-67.二进制求和
TS encapsulates the localstorage class to store information
低佣金账户怎么开?安全吗?
Tensorflow2.x actual combat series softmax function
阿里平头哥CPU技术生态负责人陈炜:平头哥的发展之路
动态规划背包问题之完全背包详解
RISC-V基金会董事谭章熹:RISC-V,从边缘逐渐向中央扩展
FreeRTOS个人笔记-挂起/解挂任务
UiPath Studio Enterprise 22.4 Crack
pytest接口自动化测试框架 | pytest生成简单测试报告
移动端H5 - 手撸一个生命线 timeline