项目结构
项目源码
koa_system: 商城项目koa + react + antd (正在开发>>>)https://gitee.com/ah-ah-bao/koa_system.git
app->index.js
const Koa = require('koa');
const path = require('path');
const { koaBody } = require('koa-body');
const KoaStatic = require('koa-static');
const parameter = require('koa-parameter');
const router = require('../router/index');
const app = new Koa();
app.use(koaBody({
multipart: true,
formidable: {
// 这个配置选项中,不能直接使用相对路径,
// option里面的相对路径不是相对的,是相对于process.cwd()的,不是相对于当前文件
uploadDir: path.join(__dirname, '../upload'),
keepExtensions: true,
}
}));
app.use(KoaStatic(path.join(__dirname, '../upload')));
app.use(parameter(app));
app.use(router.routes()).use(router.allowedMethods())
module.exports = app
config->index.js
// dotenv 主要的作用读取根目录中的.env文件
const dotenv = require('dotenv');
dotenv.config()
module.exports = process.env
controller->user.controller.js
const { createUser, getUser, updateUserPassword } = require('../service/user.service')
const jsonwebtoken = require('jsonwebtoken');
const { JWT_SECRET } = require('../config/config.development')
const bcrypt = require('bcryptjs');
class UserController {
// 注册
async register(ctx, next) {
try {
const { username, password } = ctx.request.body;
// 如果用户存在
const userSelect = await getUser(username);
if (userSelect) {
ctx.status = 500;
ctx.body = { code: 500, message: '用户已存在' };
return;
}
// 调用 createUser 函数创建用户
const res = await createUser(username, password);
ctx.body = {
code: 200,
message: '用户注册成功',
data: {
id: res.id,
username: res.username
}
}; // 假设 createUser 返回了用户数据
} catch (error) {
ctx.status = 500; // 或其他适当的 HTTP 状态码
ctx.body = {code:500, message: '用户注册失败', error: error.message };
}
}
// 登录
async login(ctx, next) {
const { username, password } = ctx.request.body;
const user = await getUser(username, password);
const bcryptjsPassqord = user.password
// 解密 第一个参数是传过来的id,第二个参数是数据库查询的加密的密码
if (bcrypt.compareSync(password, bcryptjsPassqord)) {
ctx.body = {
code: 200,
message: '登录成功',
data: {
id: user.id,
username: user.username,
token: jsonwebtoken.sign({ id: user.id, username: user.username, is_admin: user.is_admin }, JWT_SECRET, { expiresIn: '10h' })
}
}
} else {
ctx.status = 500;
ctx.body = { code: 500, message: '用户名或密码错误' };
}
}
// 修改密码
async updatePassword(ctx, next) {
const id = ctx.state.user.id;
const password = ctx.request.body.password;
const res = await updateUserPassword(id, password, ctx.state.user.is_admin);
if (res) {
ctx.body = {
code: 200,
message: '密码修改成功!',
data:''
}
} else {
ctx.status = 500;
ctx.body = {
code: 500,
message: '密码修改失败!',
data:''
};
}
}
}
module.exports = new UserController()
db->seq.js
const { Sequelize } = require('sequelize');
const { MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB, MYSQL_TYPE } = require('../config/config.development')
const sequelize = new Sequelize(MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD, {
host: MYSQL_HOST,
dialect: MYSQL_TYPE
})
// 测试数据库连接是否成功
// sequelize.authenticate().then(() => console.log('Connection has been established successfully.'));
module.exports = sequelize;
middleware->user.middleware.js
const bcrypt = require('bcryptjs')
const userCheck = async (ctx, next) => {
// TODO: write the code
const { username, password } = ctx.request.body
// 如果用户名或者密码为空
if (!username || !password) {
ctx.status = 500;
ctx.body = { code: 500, message: '用户名或密码不能为空' };
return;
}
await next()
}
const passwordBcryptjs = async (ctx, next) => {
try {
var { password } = ctx.request.body
const salt = bcrypt.genSaltSync(10);
const passwordHash = bcrypt.hashSync(password, salt);
ctx.request.body.password = passwordHash
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: err.message };
return
}
await next()
}
module.exports = {
userCheck,
passwordBcryptjs
}
model->user.model.js
const { DataTypes } = require('sequelize');
const sequelize = require('../db/seq')
// Modal
const User = sequelize.define('node_user',{
username:{
type:DataTypes.STRING,
allowNull:false,
comment:'用户名,唯一',
unique:true
},
password:{
type:DataTypes.STRING,
allowNull:false,
comment:'密码'
},
is_admin:{
type:DataTypes.BOOLEAN,
allowNull:false,
defaultValue:0,
comment:'是否是管理员,0不是管理员,1是管理员'
}
})
// 强制同步数据库(创建数据库表)
// force:ture 如果表存在就强行删除表,然后创建一个新的表
// User.sync({force:'ture'})
module.exports = User
router->user.route.js
/**
* @author: zxb
* @date: 2024-07-25
* @des : 用户路由
* @router: /user/login
**/
const Router = require('koa-router');
const { register, login, updatePassword } = require('../controller/user.controller');
const { userCheck, passwordBcryptjs } = require('../middleware/user.middleware')
const { auth } = require('../middleware/auth.middleware');
const router = new Router({ prefix: '/user' });
router.post('/register', userCheck, passwordBcryptjs, register); // 注册
router.post('/login', userCheck, login); // 登录
router.post('/updatePassword', auth, passwordBcryptjs, updatePassword); // 修改密码
module.exports = router;
service->user.service.js
const User = require('../model/user.model')
class UserService {
async createUser(username,password) {
//TODO: implement
const res = await User.create({username,password})
return res.dataValues
}
async getUser(username) {
//TODO: implement
const res = await User.findOne({where:{username}})
return res
}
async updateUserPassword(id,password,is_admin) {
//TODO: implement
const res = await User.update({password,is_admin},{where:{id}})
return res[0] > 0 ? true : false
}
}
module.exports = new UserService();
index.js
const app = require('./app/index')
const { APP_PORT } = require('./config/config.development');
app.listen(APP_PORT, () => console.log(`server is running at http://localhost:${APP_PORT}`));
.env
APP_PORT=8000
MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=admin123
MYSQL_DB=node
MYSQL_TYPE=mysql
JWT_SECRET=koa_system_node
JWT_EXPIRES_IN=1h
SYS_LOCATION=127.0.0.1
结束语
正在开发中.......后续带来更多功能,点个赞,源码点个star!