当前位置:网站首页>Nodejs implements token login registration (koa2)
Nodejs implements token login registration (koa2)
2022-07-23 16:56:00 【Anonymous enthusiastic netizens】
Source code
https://github.com/NaCl-131/node-study.git
Install what should be installed
npm install koa
npm i nodemon -D # Save automatic updates
npm i koa-router # route
npm i koa-body # analysis post It's a kind of reference
npm i mysql2 sequelize #mysql And a ORM Tools
npm i jsonwebtoken #JWT
npm i dotenv #.env file
entrance
main.js introduce :
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())
Routing in :
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' })
// Registered interface
router.post('/register', register)
// Login interface
router.post('/login', login)
module.exports = router
operation
Create three files :controller,model,service.
The function of each is to carry out the main operation , Database management , Perform database operations .
Control layer :
const {
createUser,
UserExistJudge,
UserPasswordJudge
} = require('../service/user.service')
class UserController {
async register(ctx, next) {
// 1. get data
// console.log(ctx.request.body)
const {
user_name,
password
} = JSON.parse(ctx.request.body)
// 2. Operating the database
const isUserExist = await UserExistJudge(user_name)
if (isUserExist) {
ctx.body = {
code: 0,
message: ' User name already exists ',
result: {
},
}
} else {
const res = await createUser(user_name, password);
ctx.body = {
code: 0,
message: ' User registration successful ',
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) {
// Login successful
let UserInfo = await UserPasswordJudge(user_name, password);
if (UserInfo.UserPasswordTrue) {
ctx.body = {
code: 0,
message: ' Login successful !',
result: {
id: UserInfo.id,
user_name: UserInfo.user_name,
token: UserInfo.token
},
}
} else {
ctx.body = {
code: 0,
message: ' Wrong password !',
result: {
},
}
}
} else {
ctx.body = {
code: 0,
message: ' The username does not exist !',
result: {
},
}
}
}
}
module.exports = new UserController()
Service layer :
const User = require('../model/user');
const jwt = require('jsonwebtoken');
const {
TOKEN_SECRET
} = require('../../config/config.default')
class UserService {
// Insert user data
async createUser(user_name, password) {
// insert data
const res = await User.create({
// Table fields
user_name: user_name,
password: password
})
console.log(res)
return res.dataValues
}
// Judge whether the user exists
async UserExistJudge(user_name) {
const res = await User.findAll({
where: {
user_name: user_name
}
})
if (res.length !== 0) {
return true;
} // User name exists
else return false; // non-existent
}
// Judge the user password
async UserPasswordJudge(user_name, password) {
const user = await User.findAll({
where: {
user_name
}
})
const token = await getToken({
user_name,
// password, Don't put the password in 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
}
}
// Validate users 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()
database :
const {
DataTypes
} = require('sequelize')
const seq = require('../line')
// Creating models (Model zd_user -> surface zd_users)
const User = seq.define('zd_user', {
// id Will be sequelize Automatically create , management
user_name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
comment: ' user name , only ',
},
password: {
type: DataTypes.CHAR(64),
allowNull: false,
comment: ' password ',
},
is_admin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: 0,
comment: ' Is it an administrator , 0: Not an administrator ( Default ); 1: It's the administrator ',
},
})
// Force database synchronization ( Create data table )
// User.sync({ force: true })
module.exports = User
effect :
register :
Sign in :
边栏推荐
- docker 安装redis
- Pinia (pineapple)
- Liupeng, vice president of copu: China's open source has approached or reached the world's advanced level in some areas
- 学习MySQL这一篇就够了
- JS之闭包
- 基于APISIX的basic-auth插件对Minio文件上传功能进行授权
- Detector: detect objects with recursive feature pyramid and switchable atolos convolution
- Navicat15下载安装
- pairwise的使用
- Leetcode-168.excel table column name
猜你喜欢

General paging function

The working principle of PLL. For example, how can our 8MHz crystal oscillator make MCU work at 48mhz or 72mhz

通用分页功能

USB基础

CNCF基金会总经理Priyanka Sharma:一文读懂CNCF运作机制

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

微信小程序wx.hideLoading()会关闭toast提示框

Tensorflow2.x actual combat series softmax function

智慧物联网源码 带组态物联网源码 工业物联网源码:支持传感器解析服务,数据实时采集和远程控制

Chen Wei, head of CPU technology ecology of Alibaba pingtouge: the development road of pingtouge
随机推荐
USB基础
Closure of JS
Network protocol and attack simulation: Wireshark use, ARP Protocol
Frequently asked questions about MySQL
Acquisition of positional reliability in accurate target detection
实时疫情数据可视化分析
微机原理与技术接口笔记
SurFace家族选购参照
TOPSIS法(MATLAB)
使用BoundsChecker「建议收藏」
FreeRTOS个人笔记-挂起/解挂任务
怎么购买收益在6%以上的理财产品?
opencv之打开摄像头、边缘检测
docker 安装redis
YOLOV7
YOLOv4: Optimal Speed and Accuracy of Object Detection
[C language] structure, enumeration and union
ts封装localstorage类,存储信息
目前有哪些年利率6%左右的保本理财产品?
百度编辑器上传图片设置自定义目录