38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
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 };
|
||
}; |