feat: 更新助手配置,添加应用ID和URL,优化身份验证和代理逻辑
This commit is contained in:
42
assistant/src/module/http-token.ts
Normal file
42
assistant/src/module/http-token.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import http from 'http';
|
||||
export const error = (msg: string, code = 500) => {
|
||||
return JSON.stringify({ code, message: msg });
|
||||
};
|
||||
const cookie = {
|
||||
parse: (cookieStr: string) => {
|
||||
const cookies: Record<string, string> = {};
|
||||
const cookiePairs = cookieStr.split(';');
|
||||
for (const pair of cookiePairs) {
|
||||
const [key, value] = pair.split('=').map((v) => v.trim());
|
||||
if (key && value) {
|
||||
cookies[key] = decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
}
|
||||
export const getToken = async (req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
let token = (req.headers?.['authorization'] as string) || (req.headers?.['Authorization'] as string) || '';
|
||||
const url = new URL(req.url || '', 'http://localhost');
|
||||
const resNoPermission = () => {
|
||||
res.statusCode = 401;
|
||||
res.end(error('Invalid authorization'));
|
||||
return { tokenUser: null, token: null };
|
||||
};
|
||||
if (!token) {
|
||||
token = url.searchParams.get('token') || '';
|
||||
}
|
||||
if (!token) {
|
||||
const parsedCookies = cookie.parse(req.headers.cookie || '');
|
||||
token = parsedCookies.token || '';
|
||||
}
|
||||
if (!token) {
|
||||
return resNoPermission();
|
||||
}
|
||||
if (token) {
|
||||
token = token.replace('Bearer ', '');
|
||||
}
|
||||
|
||||
return { token };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user