Files
cli/assistant/src/module/http-token.ts

38 lines
1.1 KiB
TypeScript
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.
import { IncomingMessage } from 'node: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;
}
}
/**
* 从请求中获取token优先级Authorization header > query parameter > cookie
* @param req
* @returns
*/
export const getToken = async (req: 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 ', '');
}
return { token };
};