import { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify' import fastifyPlugin from 'fastify-plugin' const getTokenFromHeader = function (request) { let token: string | undefined if (request.headers && request.headers.authorization) { const parts = request.headers.authorization.split(' ') if (parts.length === 2) { const scheme = parts[0] if (/^Bearer$/i.test(scheme)) { token = parts[1] } } } return token } const getTokenFromCookie = function (request) { let token: string | undefined if (request.cookies) { if (request.cookies['token']) { token = request.cookies['token'] } } return token } const getTokenFromParams = function (request) { let token: string | undefined token = request.params && request.params.token return token } const getTokenFromQuery = function (request) { let token: string | undefined token = request.query && request.query.token return token } const getTokenFromBody = function (request) { let token: string | undefined token = request.body && request.body.token return token } const zTokenParserPlugin: FastifyPluginAsync = async function (fastify: FastifyInstance, options?: any) { fastify.addHook('preValidation', async (request: FastifyRequest, reply: FastifyReply) => { request['token'] = getTokenFromHeader(request) || getTokenFromCookie(request) || getTokenFromParams(request) || getTokenFromQuery(request) || getTokenFromBody(request) }) return } /** * 依次从request的header, cookie, params, query和body中获取token, 加入到request.token中 * header中的字段key为authorization, 格式为 Bearer xxxx * 其他位置的key都为 token */ export default fastifyPlugin(zTokenParserPlugin, '4.x')