57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
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 logger = new Logger("Lib | auth");
|
|
|
|
const Authorization: FastifyPluginCallback = (fastify) => {
|
|
fastify.addHook("onRequest", async (req, res) => {
|
|
if (!(req.url.startsWith("/api"))) {
|
|
return req.token = ErrorBase({
|
|
bad: "client",
|
|
code: "token_invalid",
|
|
message: "トークンが不正です。",
|
|
});
|
|
}
|
|
|
|
let token = req.headers["authorization"];
|
|
if (typeof token !== "string") {
|
|
return req.token = ErrorBase({
|
|
bad: "client",
|
|
code: "token_invalid",
|
|
message: "トークンが不正です。",
|
|
});
|
|
}
|
|
|
|
if (!token.startsWith("Bearer ")) {
|
|
return req.token = ErrorBase({
|
|
bad: "client",
|
|
code: "token_invalid",
|
|
message: "トークンが不正です。",
|
|
});
|
|
}
|
|
|
|
token = token.replace("Bearer ", "");
|
|
|
|
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);
|