2024-10-02 20:04:51 -04:00
|
|
|
import { Request, Response, NextFunction } from "express";
|
|
|
|
import createHttpError from "http-errors";
|
|
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
import response from "@server/utils/response";
|
2024-10-04 23:14:40 -04:00
|
|
|
import logger from "@server/logger";
|
2024-10-13 17:13:47 -04:00
|
|
|
import {
|
|
|
|
createBlankSessionTokenCookie,
|
|
|
|
invalidateSession,
|
|
|
|
SESSION_COOKIE_NAME,
|
|
|
|
} from "@server/auth";
|
2024-10-02 20:04:51 -04:00
|
|
|
|
|
|
|
export async function logout(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
|
|
|
next: NextFunction,
|
|
|
|
): Promise<any> {
|
2024-10-13 17:13:47 -04:00
|
|
|
const sessionId = req.cookies[SESSION_COOKIE_NAME];
|
2024-10-02 20:04:51 -04:00
|
|
|
|
|
|
|
if (!sessionId) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.BAD_REQUEST,
|
|
|
|
"You must be logged in to sign out",
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-10-04 23:14:40 -04:00
|
|
|
try {
|
2024-10-13 17:13:47 -04:00
|
|
|
await invalidateSession(sessionId);
|
|
|
|
res.setHeader("Set-Cookie", createBlankSessionTokenCookie());
|
2024-10-02 20:04:51 -04:00
|
|
|
|
2024-10-04 23:14:40 -04:00
|
|
|
return response<null>(res, {
|
|
|
|
data: null,
|
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "Logged out successfully",
|
|
|
|
status: HttpCode.OK,
|
|
|
|
});
|
|
|
|
} catch (error) {
|
2024-10-06 09:55:45 -04:00
|
|
|
logger.error("Failed to log out", error);
|
2024-10-04 23:14:40 -04:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.INTERNAL_SERVER_ERROR,
|
|
|
|
"Failed to log out",
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2024-10-02 20:04:51 -04:00
|
|
|
}
|