1
1
mirror of https://github.com/ZeroCatDev/ClassworksKV.git synced 2025-12-07 13:03:09 +00:00
ClassworksKV/middleware/kvTokenAuth.js
SunWuyuan bb61e6e6f5
feat: Add AutoAuth functionality and enhance Apps API
- Introduced AutoAuth model to manage automatic authorization configurations for devices.
- Added new endpoint to obtain token via namespace and password for automatic authorization.
- Implemented functionality to set student names for student-type tokens.
- Enhanced AppInstall model to include deviceType and isReadOnly fields.
- Updated device creation to allow custom namespaces and ensure uniqueness.
- Added routes for managing AutoAuth configurations, including CRUD operations.
- Implemented checks for read-only tokens in KV operations.
- Created detailed API documentation for AutoAuth and new Apps API endpoints.
- Added migration scripts to accommodate new database schema changes.
2025-11-01 19:31:46 +08:00

71 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* KV接口专用Token认证中间件
*
* 仅验证app token设置设备和应用信息到res.locals
* 适用于所有KV相关的接口
*/
import { PrismaClient } from "@prisma/client";
import errors from "../utils/errors.js";
const prisma = new PrismaClient();
/**
* KV Token认证中间件
* 从请求中提取token支持多种方式验证后将设备和应用信息注入到res.locals
*/
export const kvTokenAuth = async (req, res, next) => {
try {
// 从多种途径获取token
const token = extractToken(req);
if (!token) {
return next(errors.createError(401, "需要提供有效的token"));
}
// 查找token对应的应用安装信息
const appInstall = await prisma.appInstall.findUnique({
where: { token },
include: {
device: true,
},
});
if (!appInstall) {
return next(errors.createError(401, "无效的token"));
}
// 将信息存储到res.locals供后续使用
res.locals.device = appInstall.device;
res.locals.appInstall = appInstall;
res.locals.deviceId = appInstall.device.id;
res.locals.token = token;
next();
} catch (error) {
next(error);
}
};
/**
* 从请求中提取token
* 支持的方式:
* 1. Header: x-app-token
* 2. Query: token 或 apptoken
* 3. Body: token 或 apptoken
*/
function extractToken(req) {
// 优先从 Authorization header 提取 Bearer token支持大小写
const authHeader = req.headers && (req.headers.authorization || req.headers.Authorization);
if (authHeader) {
const m = authHeader.match(/^Bearer\s+(.+)$/i);
if (m) return m[1];
}
return (
req.headers["x-app-token"] ||
req.query.token ||
req.query.apptoken ||
(req.body && req.body.token) ||
(req.body && req.body.apptoken)
);
}