add: 用户鉴权和查询所有用户接口

This commit is contained in:
cancerai committed 2026-10-11 18:01:11 +08:00
commit 861a689759
10 files changed
+349

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import { sql, SQL } from "bun";
import { Hono } from "hono";
import { validator } from "hono/validator";
import { checkAdmin } from "./utils/admin";
import { checkUser } from "./utils/user";
const appTmp = new Hono()
const app = appTmp.basePath("/auth")
const db = new SQL({
"adapter": "mariadb",
"host": "localhost",
"user": "root",
"password": "root",
"database": "user_auth",
"allowPublicKeyRetrieval": true
})
// 鉴权
app.get(
"/",
validator("query", async (val, c) => {
const name = val.name ?? ""
const passwd = val.passwd ?? ""
// 判空
if (name == null ||
name == "" ||
passwd == null ||
passwd == ""
) {
c.status(401)
return c.json({
"msg": "需要提供用户信息字段: name, passwd"
})
}
// 验证是否是合法用户
const re = await checkUser(db, name.toString(), passwd.toString())
if (re) {
return val
} else {
c.status(401)
return c.json({
"msg": "用户验证失败"
})
}
}),
(c) => {
return c.json({
"code": 200,
"msg": "ok"
})
})
// 查询所有用户
app.get(
"/user",
validator("query", async (val, c) => {
const adminName = val.admin_name ?? ""
const adminPasswd = val.admin_passwd ?? ""
// 判空
if (adminName == null ||
adminName == "" ||
adminPasswd == null ||
adminPasswd == ""
) {
c.status(401)
return c.json({
"msg": "需要提供管理员信息字段: admin_name, admin_passwd"
})
}
// 验证是否是合法管理员
const re = await checkAdmin(db, adminName.toString(), adminPasswd.toString())
if (re) {
return val
} else {
c.status(401)
return c.json({
"msg": "管理员验证失败"
})
}
}),
async (c) => {
const rows = await db`select name, token, create_time, update_time from user`
interface userDTO {
name: String,
token: String,
create_time: Date,
update_time: Date,
}
let re: userDTO[] = []
rows.forEach((ele: { [x: string]: any; }) => {
re.push({
"name": ele["name"],
"token": ele["token"],
"create_time": ele["create_time"],
"update_time": ele["update_time"],
})
});
return c.json({
"msg": "ok",
"data": re
})
})
// 添加用户
// app.post("/user",
// validator("json", (val, c) => {
// if (val.auth_name == null || val.auth_passwd == null) {
// c.status(400)
// return c.json({
// "code": 400,
// "msg": "Parameter is invalid"
// })
// }
// }),
// async (c) => {
// const req = await c.req.json()
// const auth_name = req.auth_name
// const auth_passwd = req.auth_passwd
// await db``
// return c.json({})
// })
export default {
port: 8080,
fetch: app.fetch
}