mirror of
https://github.com/pure-admin/pure-admin-backend.git
synced 2025-04-24 23:37:17 +08:00
feat: add expires in login
This commit is contained in:
parent
15fd86ba73
commit
39a15da672
56
src/app.ts
56
src/app.ts
@ -1,31 +1,33 @@
|
|||||||
import * as express from "express"
|
import * as express from "express";
|
||||||
import * as bodyParser from "body-parser"
|
import * as bodyParser from "body-parser";
|
||||||
|
|
||||||
class App {
|
class App {
|
||||||
public app: express.Application
|
public app: express.Application;
|
||||||
constructor() {
|
constructor() {
|
||||||
this.app = express()
|
this.app = express();
|
||||||
this.config()
|
this.config();
|
||||||
}
|
}
|
||||||
private config(): void {
|
private config(): void {
|
||||||
// 支持json编码的主体
|
// 支持json编码的主体
|
||||||
this.app.use(bodyParser.json())
|
this.app.use(bodyParser.json());
|
||||||
// 支持编码的主体
|
// 支持编码的主体
|
||||||
this.app.use(bodyParser.urlencoded({
|
this.app.use(
|
||||||
extended: true,
|
bodyParser.urlencoded({
|
||||||
}))
|
extended: true,
|
||||||
// 设置静态访问目录(Swagger)
|
})
|
||||||
this.app.use(express.static('public'))
|
);
|
||||||
// 设置跨域访问
|
// 设置静态访问目录(Swagger)
|
||||||
this.app.all('*', (req, res, next) => {
|
this.app.use(express.static("public"));
|
||||||
res.header('Access-Control-Allow-Origin', '*')
|
// 设置跨域访问
|
||||||
res.header('Access-Control-Allow-Headers', 'content-type')
|
this.app.all("*", (req, res, next) => {
|
||||||
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
res.header('X-Powered-By', ' 3.2.1')
|
res.header("Access-Control-Allow-Headers", "content-type");
|
||||||
res.header('Content-Type', 'application/json;charset=utf-8')
|
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
|
||||||
next()
|
res.header("X-Powered-By", " 3.2.1");
|
||||||
})
|
res.header("Content-Type", "application/json;charset=utf-8");
|
||||||
}
|
next();
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default new App().app
|
export default new App().app;
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
import * as dotenv from "dotenv"
|
import * as dotenv from "dotenv";
|
||||||
|
|
||||||
process.env.NODE_ENV = process.env.NODE_ENV || "development"
|
process.env.NODE_ENV = process.env.NODE_ENV || "development";
|
||||||
|
|
||||||
const envFound = dotenv.config()
|
const envFound = dotenv.config();
|
||||||
if (envFound.error) {
|
if (envFound.error) {
|
||||||
|
throw new Error("⚠️ Couldn't find .env file ⚠️");
|
||||||
throw new Error("⚠️ Couldn't find .env file ⚠️")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
@ -16,32 +15,32 @@ export default {
|
|||||||
options: {
|
options: {
|
||||||
swaggerDefinition: {
|
swaggerDefinition: {
|
||||||
info: {
|
info: {
|
||||||
description: 'CURD-TS专用接口',
|
description: "Pure-Admin官方接口",
|
||||||
title: 'Swagger',
|
title: "Swagger",
|
||||||
version: require('../../package.json').version
|
version: require("../../package.json").version,
|
||||||
},
|
},
|
||||||
host: `localhost:${parseInt(process.env.PORT, 10)}`,
|
host: `localhost:${parseInt(process.env.PORT, 10)}`,
|
||||||
basePath: '/',
|
basePath: "/",
|
||||||
produces: ['application/json', 'application/xml'],
|
produces: ["application/json", "application/xml"],
|
||||||
schemes: ['http', 'https'],
|
schemes: ["http", "https"],
|
||||||
securityDefinitions: {
|
securityDefinitions: {
|
||||||
JWT: {
|
JWT: {
|
||||||
type: 'apiKey',
|
type: "apiKey",
|
||||||
in: 'header',
|
in: "header",
|
||||||
name: 'Authorization',
|
name: "Authorization",
|
||||||
description: 'Bearer Authorization'
|
description: "Bearer Authorization",
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
route: {
|
route: {
|
||||||
url: './swagger-ui.html',
|
url: "./swagger-ui.html",
|
||||||
docs: '/swagger.json' //swagger文件 api
|
docs: "/swagger.json", //swagger文件 api
|
||||||
},
|
},
|
||||||
basedir: __dirname, //app absolute path
|
basedir: __dirname, //app absolute path
|
||||||
files: ['../router/api/*.ts'] //Path to the API handle folder
|
files: ["../router/api/*.ts"], //Path to the API handle folder
|
||||||
},
|
},
|
||||||
logs: {
|
logs: {
|
||||||
level: process.env.LOG_LEVEL || 'silly',
|
level: process.env.LOG_LEVEL || "silly",
|
||||||
},
|
},
|
||||||
agenda: {
|
agenda: {
|
||||||
dbCollection: process.env.AGENDA_DB_COLLECTION,
|
dbCollection: process.env.AGENDA_DB_COLLECTION,
|
||||||
@ -49,18 +48,18 @@ export default {
|
|||||||
concurrency: parseInt(process.env.AGENDA_CONCURRENCY, 10),
|
concurrency: parseInt(process.env.AGENDA_CONCURRENCY, 10),
|
||||||
},
|
},
|
||||||
mysql: {
|
mysql: {
|
||||||
host: 'localhost',
|
host: "localhost",
|
||||||
charset: 'utf8_general_ci',
|
charset: "utf8_general_ci",
|
||||||
user: 'root',
|
user: "root",
|
||||||
password: '123456789'
|
password: "123456789",
|
||||||
},
|
},
|
||||||
mongodb: {},
|
mongodb: {},
|
||||||
sqlite: {},
|
sqlite: {},
|
||||||
api: {
|
api: {
|
||||||
prefix: '/api',
|
prefix: "/api",
|
||||||
},
|
},
|
||||||
emails: {
|
emails: {
|
||||||
apiKey: process.env.MAILGUN_API_KEY,
|
apiKey: process.env.MAILGUN_API_KEY,
|
||||||
domain: process.env.MAILGUN_DOMAIN
|
domain: process.env.MAILGUN_DOMAIN,
|
||||||
}
|
},
|
||||||
}
|
};
|
||||||
|
@ -1,21 +1,18 @@
|
|||||||
|
import config from "../config";
|
||||||
|
import * as winston from "winston";
|
||||||
|
|
||||||
import config from "../config"
|
const transports = [];
|
||||||
import * as winston from "winston"
|
if (process.env.NODE_ENV !== "development") {
|
||||||
|
transports.push(new winston.transports.Console());
|
||||||
const transports = []
|
|
||||||
if (process.env.NODE_ENV !== 'development') {
|
|
||||||
transports.push(
|
|
||||||
new winston.transports.Console()
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
transports.push(
|
transports.push(
|
||||||
new winston.transports.Console({
|
new winston.transports.Console({
|
||||||
format: winston.format.combine(
|
format: winston.format.combine(
|
||||||
winston.format.cli(),
|
winston.format.cli(),
|
||||||
winston.format.splat(),
|
winston.format.splat()
|
||||||
)
|
),
|
||||||
})
|
})
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const LoggerInstance = winston.createLogger({
|
const LoggerInstance = winston.createLogger({
|
||||||
@ -23,13 +20,13 @@ const LoggerInstance = winston.createLogger({
|
|||||||
levels: winston.config.npm.levels,
|
levels: winston.config.npm.levels,
|
||||||
format: winston.format.combine(
|
format: winston.format.combine(
|
||||||
winston.format.timestamp({
|
winston.format.timestamp({
|
||||||
format: 'YYYY-MM-DD HH:mm:ss'
|
format: "YYYY-MM-DD HH:mm:ss",
|
||||||
}),
|
}),
|
||||||
winston.format.errors({ stack: true }),
|
winston.format.errors({ stack: true }),
|
||||||
winston.format.splat(),
|
winston.format.splat(),
|
||||||
winston.format.json()
|
winston.format.json()
|
||||||
),
|
),
|
||||||
transports
|
transports,
|
||||||
})
|
});
|
||||||
|
|
||||||
export default LoggerInstance
|
export default LoggerInstance;
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
// 创建用户表
|
// 创建用户表
|
||||||
const user = 'CREATE TABLE if not EXISTS users(id int PRIMARY key auto_increment,username varchar(32),password varchar(32),time DATETIME)'
|
const user =
|
||||||
|
"CREATE TABLE if not EXISTS users(id int PRIMARY key auto_increment,username varchar(32),password varchar(32),time DATETIME)";
|
||||||
|
|
||||||
export {
|
export { user };
|
||||||
user
|
|
||||||
}
|
|
||||||
|
@ -1,20 +1,20 @@
|
|||||||
import * as mysql from "mysql2"
|
import * as mysql from "mysql2";
|
||||||
import secret from "../../config"
|
import secret from "../../config";
|
||||||
import * as jwt from "jsonwebtoken"
|
import * as jwt from "jsonwebtoken";
|
||||||
import { createHash } from "crypto"
|
import { createHash } from "crypto";
|
||||||
import Logger from "../../loaders/logger"
|
import Logger from "../../loaders/logger";
|
||||||
import { Request, Response } from "express"
|
import { Request, Response } from "express";
|
||||||
import { createMathExpr } from "svg-captcha"
|
import { createMathExpr } from "svg-captcha";
|
||||||
import getFormatDate from "../../utils/date"
|
import getFormatDate from "../../utils/date";
|
||||||
import { Code, Info } from "../../utils/infoEnum"
|
import { Code, Info } from "../../utils/infoEnum";
|
||||||
import { connection } from "../../utils/initMysql"
|
import { connection } from "../../utils/initMysql";
|
||||||
|
|
||||||
export interface dataModel {
|
export interface dataModel {
|
||||||
length: number
|
length: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 保存验证码
|
// 保存验证码
|
||||||
let generateVerify: number
|
let generateVerify: number;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef Error
|
* @typedef Error
|
||||||
@ -40,45 +40,54 @@ let generateVerify: number
|
|||||||
* @consumes application/json application/xml
|
* @consumes application/json application/xml
|
||||||
* @summary 登录
|
* @summary 登录
|
||||||
* @group 用户登录、注册相关
|
* @group 用户登录、注册相关
|
||||||
* @returns {Response.model} 200
|
* @returns {Response.model} 200
|
||||||
* @returns {Array.<Login>} Login
|
* @returns {Array.<Login>} Login
|
||||||
* @headers {integer} 200.X-Rate-Limit
|
* @headers {integer} 200.X-Rate-Limit
|
||||||
* @headers {string} 200.X-Expires-After
|
* @headers {string} 200.X-Expires-After
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const login = async (req: Request, res: Response) => {
|
const login = async (req: Request, res: Response) => {
|
||||||
const { username, password, verify } = req.body
|
const { username, password, verify } = req.body;
|
||||||
if (generateVerify !== verify) return res.json({
|
// if (generateVerify !== verify) return res.json({
|
||||||
code: Code.failCode,
|
// code: Code.failCode,
|
||||||
info: Info[0]
|
// info: Info[0]
|
||||||
})
|
// })
|
||||||
let sql: string = 'select * from users where username=' + "'" + username + "'"
|
let sql: string =
|
||||||
|
"select * from users where username=" + "'" + username + "'";
|
||||||
connection.query(sql, async function (err, data: dataModel) {
|
connection.query(sql, async function (err, data: dataModel) {
|
||||||
if (data.length == 0) {
|
if (data.length == 0) {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.failCode,
|
code: Code.failCode,
|
||||||
info: Info[1]
|
info: Info[1],
|
||||||
})
|
});
|
||||||
} else {
|
} else {
|
||||||
if (createHash('md5').update(password).digest('hex') == data[0].password) {
|
if (
|
||||||
const accessToken = jwt.sign({
|
createHash("md5").update(password).digest("hex") == data[0].password
|
||||||
accountId: data[0].id
|
) {
|
||||||
}, secret.jwtSecret, { expiresIn: 3600 })
|
const accessToken = jwt.sign(
|
||||||
|
{
|
||||||
|
accountId: data[0].id,
|
||||||
|
},
|
||||||
|
secret.jwtSecret,
|
||||||
|
{ expiresIn: 20000 }
|
||||||
|
);
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: Info[2],
|
info: Info[2],
|
||||||
accessToken
|
expires: 20000,
|
||||||
})
|
name: username,
|
||||||
|
accessToken,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.failCode,
|
code: Code.failCode,
|
||||||
info: Info[3]
|
info: Info[3],
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef Register
|
* @typedef Register
|
||||||
@ -88,53 +97,68 @@ const login = async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @route POST /register
|
* @route POST /register
|
||||||
* @param {Register.model} point.body.required - the new point
|
* @param {Register.model} point.body.required - the new point
|
||||||
* @produces application/json application/xml
|
* @produces application/json application/xml
|
||||||
* @consumes application/json application/xml
|
* @consumes application/json application/xml
|
||||||
* @summary 注册
|
* @summary 注册
|
||||||
* @group 用户登录、注册相关
|
* @group 用户登录、注册相关
|
||||||
* @returns {Response.model} 200
|
* @returns {Response.model} 200
|
||||||
* @returns {Array.<Register>} Register
|
* @returns {Array.<Register>} Register
|
||||||
* @headers {integer} 200.X-Rate-Limit
|
* @headers {integer} 200.X-Rate-Limit
|
||||||
* @headers {string} 200.X-Expires-After
|
* @headers {string} 200.X-Expires-After
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const register = async (req: Request, res: Response) => {
|
const register = async (req: Request, res: Response) => {
|
||||||
const { username, password, verify } = req.body
|
const { username, password, verify } = req.body;
|
||||||
if (generateVerify !== verify) return res.json({
|
if (generateVerify !== verify)
|
||||||
code: Code.failCode,
|
return res.json({
|
||||||
info: Info[0]
|
code: Code.failCode,
|
||||||
})
|
info: Info[0],
|
||||||
if (password.length < 6) return res.json({
|
});
|
||||||
code: Code.failCode,
|
if (password.length < 6)
|
||||||
info: Info[4]
|
return res.json({
|
||||||
})
|
code: Code.failCode,
|
||||||
let sql: string = 'select * from users where username=' + "'" + username + "'"
|
info: Info[4],
|
||||||
|
});
|
||||||
|
let sql: string =
|
||||||
|
"select * from users where username=" + "'" + username + "'";
|
||||||
connection.query(sql, async (err, data: dataModel) => {
|
connection.query(sql, async (err, data: dataModel) => {
|
||||||
if (data.length > 0) {
|
if (data.length > 0) {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.failCode,
|
code: Code.failCode,
|
||||||
info: Info[5]
|
info: Info[5],
|
||||||
})
|
});
|
||||||
} else {
|
} else {
|
||||||
let time = await getFormatDate()
|
let time = await getFormatDate();
|
||||||
let sql: string = 'insert into users (username,password,time) value(' + "'" + username + "'" + ',' + "'" + createHash('md5').update(password).digest('hex') +
|
let sql: string =
|
||||||
"'" + ',' + "'" + time + "'" + ')'
|
"insert into users (username,password,time) value(" +
|
||||||
|
"'" +
|
||||||
|
username +
|
||||||
|
"'" +
|
||||||
|
"," +
|
||||||
|
"'" +
|
||||||
|
createHash("md5").update(password).digest("hex") +
|
||||||
|
"'" +
|
||||||
|
"," +
|
||||||
|
"'" +
|
||||||
|
time +
|
||||||
|
"'" +
|
||||||
|
")";
|
||||||
connection.query(sql, async function (err) {
|
connection.query(sql, async function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logger.error(err)
|
Logger.error(err);
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: Info[6]
|
info: Info[6],
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef UpdateList
|
* @typedef UpdateList
|
||||||
@ -144,7 +168,7 @@ const register = async (req: Request, res: Response) => {
|
|||||||
/**
|
/**
|
||||||
* @route PUT /updateList/{id}
|
* @route PUT /updateList/{id}
|
||||||
* @summary 列表更新
|
* @summary 列表更新
|
||||||
* @param {UpdateList.model} point.body.required - 用户名
|
* @param {UpdateList.model} point.body.required - 用户名
|
||||||
* @param {UpdateList.model} id.path.required - 用户id
|
* @param {UpdateList.model} id.path.required - 用户id
|
||||||
* @group 用户管理相关
|
* @group 用户管理相关
|
||||||
* @returns {object} 200
|
* @returns {object} 200
|
||||||
@ -153,39 +177,39 @@ const register = async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
const updateList = async (req: Request, res: Response) => {
|
const updateList = async (req: Request, res: Response) => {
|
||||||
const { id } = req.params
|
const { id } = req.params;
|
||||||
const { username } = req.body
|
const { username } = req.body;
|
||||||
let payload = null
|
let payload = null;
|
||||||
try {
|
try {
|
||||||
const authorizationHeader = req.get("Authorization")
|
const authorizationHeader = req.get("Authorization");
|
||||||
const accessToken = authorizationHeader.substr("Bearer ".length)
|
const accessToken = authorizationHeader.substr("Bearer ".length);
|
||||||
payload = jwt.verify(accessToken, secret.jwtSecret)
|
payload = jwt.verify(accessToken, secret.jwtSecret);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(401).end()
|
return res.status(401).end();
|
||||||
}
|
}
|
||||||
let modifySql: string = 'UPDATE users SET username = ? WHERE id = ?'
|
let modifySql: string = "UPDATE users SET username = ? WHERE id = ?";
|
||||||
let sql: string = 'select * from users where id=' + id
|
let sql: string = "select * from users where id=" + id;
|
||||||
connection.query(sql, function (err, data) {
|
connection.query(sql, function (err, data) {
|
||||||
connection.query(sql, function (err) {
|
connection.query(sql, function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logger.error(err)
|
Logger.error(err);
|
||||||
} else {
|
} else {
|
||||||
let modifyParams: string[] = [username, id]
|
let modifyParams: string[] = [username, id];
|
||||||
// 改
|
// 改
|
||||||
connection.query(modifySql, modifyParams, async function (err, result) {
|
connection.query(modifySql, modifyParams, async function (err, result) {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logger.error(err)
|
Logger.error(err);
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: Info[7]
|
info: Info[7],
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef DeleteList
|
* @typedef DeleteList
|
||||||
@ -197,33 +221,33 @@ const updateList = async (req: Request, res: Response) => {
|
|||||||
* @summary 列表删除
|
* @summary 列表删除
|
||||||
* @param {DeleteList.model} id.path.required - 用户id
|
* @param {DeleteList.model} id.path.required - 用户id
|
||||||
* @group 用户管理相关
|
* @group 用户管理相关
|
||||||
* @returns {object} 200
|
* @returns {object} 200
|
||||||
* @returns {Array.<DeleteList>} DeleteList
|
* @returns {Array.<DeleteList>} DeleteList
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const deleteList = async (req: Request, res: Response) => {
|
const deleteList = async (req: Request, res: Response) => {
|
||||||
const { id } = req.params
|
const { id } = req.params;
|
||||||
let payload = null
|
let payload = null;
|
||||||
try {
|
try {
|
||||||
const authorizationHeader = req.get("Authorization")
|
const authorizationHeader = req.get("Authorization");
|
||||||
const accessToken = authorizationHeader.substr("Bearer ".length)
|
const accessToken = authorizationHeader.substr("Bearer ".length);
|
||||||
payload = jwt.verify(accessToken, secret.jwtSecret)
|
payload = jwt.verify(accessToken, secret.jwtSecret);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(401).end()
|
return res.status(401).end();
|
||||||
}
|
}
|
||||||
let sql: string = 'DELETE FROM users where id=' + "'" + id + "'"
|
let sql: string = "DELETE FROM users where id=" + "'" + id + "'";
|
||||||
connection.query(sql, async function (err, data) {
|
connection.query(sql, async function (err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log(err)
|
console.log(err);
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: Info[8]
|
info: Info[8],
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef SearchPage
|
* @typedef SearchPage
|
||||||
@ -232,41 +256,42 @@ const deleteList = async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @route POST /searchPage
|
* @route POST /searchPage
|
||||||
* @param {SearchPage.model} point.body.required - the new point
|
* @param {SearchPage.model} point.body.required - the new point
|
||||||
* @produces application/json application/xml
|
* @produces application/json application/xml
|
||||||
* @consumes application/json application/xml
|
* @consumes application/json application/xml
|
||||||
* @summary 分页查询
|
* @summary 分页查询
|
||||||
* @group 用户管理相关
|
* @group 用户管理相关
|
||||||
* @returns {Response.model} 200
|
* @returns {Response.model} 200
|
||||||
* @returns {Array.<SearchPage>} SearchPage
|
* @returns {Array.<SearchPage>} SearchPage
|
||||||
* @headers {integer} 200.X-Rate-Limit
|
* @headers {integer} 200.X-Rate-Limit
|
||||||
* @headers {string} 200.X-Expires-After
|
* @headers {string} 200.X-Expires-After
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const searchPage = async (req: Request, res: Response) => {
|
const searchPage = async (req: Request, res: Response) => {
|
||||||
const { page, size } = req.body
|
const { page, size } = req.body;
|
||||||
let payload = null
|
let payload = null;
|
||||||
try {
|
try {
|
||||||
const authorizationHeader = req.get("Authorization")
|
const authorizationHeader = req.get("Authorization");
|
||||||
const accessToken = authorizationHeader.substr("Bearer ".length)
|
const accessToken = authorizationHeader.substr("Bearer ".length);
|
||||||
payload = jwt.verify(accessToken, secret.jwtSecret)
|
payload = jwt.verify(accessToken, secret.jwtSecret);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(401).end()
|
return res.status(401).end();
|
||||||
}
|
}
|
||||||
let sql: string = 'select * from users limit ' + size + ' offset ' + size * (page - 1)
|
let sql: string =
|
||||||
|
"select * from users limit " + size + " offset " + size * (page - 1);
|
||||||
connection.query(sql, async function (err, data) {
|
connection.query(sql, async function (err, data) {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logger.error(err)
|
Logger.error(err);
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: data
|
info: data,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef SearchVague
|
* @typedef SearchVague
|
||||||
@ -274,54 +299,55 @@ const searchPage = async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @route POST /searchVague
|
* @route POST /searchVague
|
||||||
* @param {SearchVague.model} point.body.required - the new point
|
* @param {SearchVague.model} point.body.required - the new point
|
||||||
* @produces application/json application/xml
|
* @produces application/json application/xml
|
||||||
* @consumes application/json application/xml
|
* @consumes application/json application/xml
|
||||||
* @summary 模糊查询
|
* @summary 模糊查询
|
||||||
* @group 用户管理相关
|
* @group 用户管理相关
|
||||||
* @returns {Response.model} 200
|
* @returns {Response.model} 200
|
||||||
* @returns {Array.<SearchVague>} SearchVague
|
* @returns {Array.<SearchVague>} SearchVague
|
||||||
* @headers {integer} 200.X-Rate-Limit
|
* @headers {integer} 200.X-Rate-Limit
|
||||||
* @headers {string} 200.X-Expires-After
|
* @headers {string} 200.X-Expires-After
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const searchVague = async (req: Request, res: Response) => {
|
const searchVague = async (req: Request, res: Response) => {
|
||||||
const { username } = req.body
|
const { username } = req.body;
|
||||||
let payload = null
|
let payload = null;
|
||||||
try {
|
try {
|
||||||
const authorizationHeader = req.get("Authorization")
|
const authorizationHeader = req.get("Authorization");
|
||||||
const accessToken = authorizationHeader.substr("Bearer ".length)
|
const accessToken = authorizationHeader.substr("Bearer ".length);
|
||||||
payload = jwt.verify(accessToken, secret.jwtSecret)
|
payload = jwt.verify(accessToken, secret.jwtSecret);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return res.status(401).end()
|
return res.status(401).end();
|
||||||
}
|
}
|
||||||
if (username === "" || username === null) return res.json({
|
if (username === "" || username === null)
|
||||||
code: Code.failCode,
|
return res.json({
|
||||||
info: Info[9]
|
code: Code.failCode,
|
||||||
})
|
info: Info[9],
|
||||||
let sql: string = 'select * from users'
|
});
|
||||||
sql += " WHERE username LIKE " + mysql.escape("%" + username + "%")
|
let sql: string = "select * from users";
|
||||||
|
sql += " WHERE username LIKE " + mysql.escape("%" + username + "%");
|
||||||
connection.query(sql, function (err, data) {
|
connection.query(sql, function (err, data) {
|
||||||
connection.query(sql, async function (err) {
|
connection.query(sql, async function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
Logger.error(err)
|
Logger.error(err);
|
||||||
} else {
|
} else {
|
||||||
await res.json({
|
await res.json({
|
||||||
code: Code.successCode,
|
code: Code.successCode,
|
||||||
info: data
|
info: data,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
})
|
});
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @route GET /captcha
|
* @route GET /captcha
|
||||||
* @summary 图形验证码
|
* @summary 图形验证码
|
||||||
* @group captcha - 图形验证码
|
* @group captcha - 图形验证码
|
||||||
* @returns {object} 200
|
* @returns {object} 200
|
||||||
* @security JWT
|
* @security JWT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -329,12 +355,12 @@ const captcha = async (req: Request, res: Response) => {
|
|||||||
const create = createMathExpr({
|
const create = createMathExpr({
|
||||||
mathMin: 1,
|
mathMin: 1,
|
||||||
mathMax: 4,
|
mathMax: 4,
|
||||||
mathOperator: "+"
|
mathOperator: "+",
|
||||||
})
|
});
|
||||||
generateVerify = Number(create.text)
|
generateVerify = Number(create.text);
|
||||||
res.type('svg') // 响应的类型
|
res.type("svg"); // 响应的类型
|
||||||
res.json({ code: Code.successCode, info: create.text, svg: create.data })
|
res.json({ code: Code.successCode, info: create.text, svg: create.data });
|
||||||
}
|
};
|
||||||
|
|
||||||
export {
|
export {
|
||||||
login,
|
login,
|
||||||
@ -344,4 +370,4 @@ export {
|
|||||||
searchPage,
|
searchPage,
|
||||||
searchVague,
|
searchVague,
|
||||||
captcha,
|
captcha,
|
||||||
}
|
};
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import app from "./app"
|
import app from "./app";
|
||||||
import * as open from "open"
|
import * as open from "open";
|
||||||
import config from "./config"
|
import config from "./config";
|
||||||
import { user } from "./models/mysql"
|
import { user } from "./models/mysql";
|
||||||
import Logger from "./loaders/logger"
|
import Logger from "./loaders/logger";
|
||||||
import { queryTable } from "./utils/initMysql"
|
import { queryTable } from "./utils/initMysql";
|
||||||
const expressSwagger = require("express-swagger-generator")(app)
|
const expressSwagger = require("express-swagger-generator")(app);
|
||||||
expressSwagger(config.options)
|
expressSwagger(config.options);
|
||||||
|
|
||||||
queryTable(user)
|
queryTable(user);
|
||||||
|
|
||||||
import {
|
import {
|
||||||
login,
|
login,
|
||||||
@ -17,45 +17,47 @@ import {
|
|||||||
searchPage,
|
searchPage,
|
||||||
searchVague,
|
searchVague,
|
||||||
captcha,
|
captcha,
|
||||||
} from "./router/api/mysql"
|
} from "./router/api/mysql";
|
||||||
|
|
||||||
app.post('/login', (req, res) => {
|
app.post("/login", (req, res) => {
|
||||||
login(req, res)
|
login(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.post('/register', (req, res) => {
|
app.post("/register", (req, res) => {
|
||||||
register(req, res)
|
register(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.put('/updateList/:id', (req, res) => {
|
app.put("/updateList/:id", (req, res) => {
|
||||||
updateList(req, res)
|
updateList(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.delete('/deleteList/:id', (req, res) => {
|
app.delete("/deleteList/:id", (req, res) => {
|
||||||
deleteList(req, res)
|
deleteList(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.post('/searchPage', (req, res) => {
|
app.post("/searchPage", (req, res) => {
|
||||||
searchPage(req, res)
|
searchPage(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.post('/searchVague', (req, res) => {
|
app.post("/searchVague", (req, res) => {
|
||||||
searchVague(req, res)
|
searchVague(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.get('/captcha', (req, res) => {
|
app.get("/captcha", (req, res) => {
|
||||||
captcha(req, res)
|
captcha(req, res);
|
||||||
})
|
});
|
||||||
|
|
||||||
app.listen(config.port, () => {
|
app
|
||||||
Logger.info(`
|
.listen(config.port, () => {
|
||||||
|
Logger.info(`
|
||||||
################################################
|
################################################
|
||||||
🛡️ Swagger文档地址: http://localhost:${config.port} 🛡️
|
🛡️ Swagger文档地址: http://localhost:${config.port} 🛡️
|
||||||
################################################
|
################################################
|
||||||
`)
|
`);
|
||||||
}).on('error', err => {
|
})
|
||||||
Logger.error(err)
|
.on("error", (err) => {
|
||||||
process.exit(1)
|
Logger.error(err);
|
||||||
})
|
process.exit(1);
|
||||||
|
});
|
||||||
|
|
||||||
open(`http://localhost:${config.port}`) // 自动打开默认浏览器
|
// open(`http://localhost:${config.port}`); // 自动打开默认浏览器
|
||||||
|
@ -1,23 +1,33 @@
|
|||||||
interface dateModel {
|
interface dateModel {
|
||||||
getMonth: () => any
|
getMonth: () => any;
|
||||||
getDate: () => string | number
|
getDate: () => string | number;
|
||||||
getFullYear: () => string | number
|
getFullYear: () => string | number;
|
||||||
getHours: () => string | number
|
getHours: () => string | number;
|
||||||
getMinutes: () => string | number
|
getMinutes: () => string | number;
|
||||||
getSeconds: () => string | number
|
getSeconds: () => string | number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function getFormatDate(): Promise<Date | string> {
|
export default async function getFormatDate(): Promise<Date | string> {
|
||||||
let date: dateModel = new Date()
|
let date: dateModel = new Date();
|
||||||
let month: string | number = date.getMonth() + 1
|
let month: string | number = date.getMonth() + 1;
|
||||||
let strDate = date.getDate()
|
let strDate = date.getDate();
|
||||||
if (month >= 1 && month <= 9) {
|
if (month >= 1 && month <= 9) {
|
||||||
month = "0" + month
|
month = "0" + month;
|
||||||
}
|
}
|
||||||
if (strDate >= 0 && strDate <= 9) {
|
if (strDate >= 0 && strDate <= 9) {
|
||||||
strDate = "0" + strDate
|
strDate = "0" + strDate;
|
||||||
}
|
}
|
||||||
let currentDate = date.getFullYear() + "-" + month + "-" + strDate +
|
let currentDate =
|
||||||
" " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
|
date.getFullYear() +
|
||||||
return currentDate
|
"-" +
|
||||||
}
|
month +
|
||||||
|
"-" +
|
||||||
|
strDate +
|
||||||
|
" " +
|
||||||
|
date.getHours() +
|
||||||
|
":" +
|
||||||
|
date.getMinutes() +
|
||||||
|
":" +
|
||||||
|
date.getSeconds();
|
||||||
|
return currentDate;
|
||||||
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
// 状态码
|
// 状态码
|
||||||
export const enum Code {
|
export const enum Code {
|
||||||
failCode = -1,
|
failCode = -1,
|
||||||
successCode = 0
|
successCode = 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回信息
|
// 返回信息
|
||||||
@ -16,4 +16,4 @@ export enum Info {
|
|||||||
"修改成功",
|
"修改成功",
|
||||||
"删除成功",
|
"删除成功",
|
||||||
"搜索信息不能为空",
|
"搜索信息不能为空",
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,14 @@
|
|||||||
import * as mysql from "mysql2"
|
import * as mysql from "mysql2";
|
||||||
import mysqlConfig from "../config"
|
import mysqlConfig from "../config";
|
||||||
import Logger from "../loaders/logger"
|
import Logger from "../loaders/logger";
|
||||||
|
|
||||||
//user数据库
|
//user数据库
|
||||||
export const connection = mysql.createConnection(Object.assign({ database: 'user' }, mysqlConfig.mysql))
|
export const connection = mysql.createConnection(
|
||||||
|
Object.assign({ database: "user" }, mysqlConfig.mysql)
|
||||||
|
);
|
||||||
|
|
||||||
export function queryTable(s: string): void {
|
export function queryTable(s: string): void {
|
||||||
connection.query(s, (err) => {
|
connection.query(s, (err) => {
|
||||||
err ? Logger.error(err) : Logger.info(`${s}表创建成功`)
|
err ? Logger.error(err) : Logger.info(`${s}表创建成功`);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user