First commit
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import type { FastifyPluginCallback } from "fastify";
|
||||
import fp from "fastify-plugin";
|
||||
import { TokenEntity } from "@/modules/entities/Token";
|
||||
import logger from "./logger";
|
||||
import { DatabaseError, ErrorBase } from "@/errors";
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
token: TokenEntity | ReturnType<typeof ErrorBase>;
|
||||
}
|
||||
}
|
||||
|
||||
const Authorization: FastifyPluginCallback = (fastify) => {
|
||||
fastify.addHook("onRequest", async (req, res) => {
|
||||
const token = req.headers["authorization"];
|
||||
if (typeof token !== "string") {
|
||||
return req.token = ErrorBase({
|
||||
bad: "client",
|
||||
code: "token_none",
|
||||
message: "トークンが設定されていません。",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fastify.orm.em.getRepository(TokenEntity).authToken(token);
|
||||
|
||||
req.token = result;
|
||||
} catch (err) {
|
||||
logger.error("Database Error: Token authorization failed:", err);
|
||||
|
||||
return res.code(500).send(DatabaseError());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default fp(Authorization);
|
||||
Reference in New Issue
Block a user