This commit is contained in:
2026-01-05 02:02:51 +08:00
parent c6715c2e35
commit 93879b532b
10 changed files with 184 additions and 143 deletions

View File

@@ -1,81 +0,0 @@
import { User } from '../models/user.ts';
import http from 'node:http';
import cookie from 'cookie';
export const error = (msg: string, code = 500) => {
return JSON.stringify({ code, message: msg });
};
type CheckAuthOptions = {
check401?: boolean; // 是否返回权限信息
};
/**
* 手动验证token如果token不存在则返回401
* @param req
* @param res
* @returns
*/
export const checkAuth = async (req: http.IncomingMessage, res: http.ServerResponse, opts?: CheckAuthOptions) => {
let token = (req.headers?.['authorization'] as string) || (req.headers?.['Authorization'] as string) || '';
const url = new URL(req.url || '', 'http://localhost');
const check401 = opts?.check401 ?? true; // 是否返回401错误
const resNoPermission = () => {
res.statusCode = 401;
res.end(error('Invalid authorization'));
return { tokenUser: null, token: null, hasToken: false };
};
if (!token) {
token = url.searchParams.get('token') || '';
}
if (!token) {
const parsedCookies = cookie.parse(req.headers.cookie || '');
token = parsedCookies.token || '';
}
if (!token && check401) {
return resNoPermission();
}
if (token) {
token = token.replace('Bearer ', '');
}
let tokenUser;
const hasToken = !!token; // 是否有token存在
try {
tokenUser = await User.verifyToken(token);
} catch (e) {
console.log('checkAuth error', e);
res.statusCode = 401;
res.end(error('Invalid token'));
return { tokenUser: null, token: null, hasToken: false };
}
return { tokenUser, token, hasToken };
};
/**
* 获取登录用户有则获取无则返回null
* @param req
* @returns
*/
export const getLoginUser = async (req: http.IncomingMessage) => {
let token = (req.headers?.['authorization'] as string) || (req.headers?.['Authorization'] as string) || '';
const url = new URL(req.url || '', 'http://localhost');
if (!token) {
token = url.searchParams.get('token') || '';
}
if (!token) {
const parsedCookies = cookie.parse(req.headers.cookie || '');
token = parsedCookies.token || '';
}
if (token) {
token = token.replace('Bearer ', '');
}
if (!token) {
return null;
}
let tokenUser;
try {
tokenUser = await User.verifyToken(token);
return { tokenUser, token };
} catch (e) {
return null;
}
};

View File

@@ -1,56 +0,0 @@
import { User } from '../models/user.ts';
import type { App } from '@kevisual/router';
/**
* 添加auth中间件, 用于验证token
* 添加 id: auth 必须需要user成功
* 添加 id: auth-can 可以不需要user成功有则赋值
*
* @param app
*/
export const addAuth = (app: App) => {
app
.route({
path: 'auth',
id: 'auth',
})
.define(async (ctx) => {
const token = ctx.query.token;
if (!token) {
app.throw(401, 'Token is required');
}
const user = await User.getOauthUser(token);
if (!user) {
app.throw(401, 'Token is invalid');
}
if (ctx.state) {
ctx.state.tokenUser = user;
} else {
ctx.state = {
tokenUser: user,
};
}
})
.addTo(app);
app
.route({
path: 'auth',
key: 'can',
id: 'auth-can',
})
.define(async (ctx) => {
if (ctx.query?.token) {
const token = ctx.query.token;
const user = await User.getOauthUser(token);
if (ctx.state) {
ctx.state.tokenUser = user;
} else {
ctx.state = {
tokenUser: user,
};
}
}
})
.addTo(app);
};