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";
|
2025-01-01 21:41:31 -05:00
|
|
|
import response from "@server/lib/response";
|
2024-10-04 23:14:40 -04:00
|
|
|
import logger from "@server/logger";
|
2024-10-13 17:13:47 -04:00
|
|
|
import {
|
|
|
|
createBlankSessionTokenCookie,
|
2025-01-26 14:42:02 -05:00
|
|
|
invalidateSession
|
2025-01-01 21:41:31 -05:00
|
|
|
} from "@server/auth/sessions/app";
|
2025-01-26 14:42:02 -05:00
|
|
|
import { verifySession } from "@server/auth/sessions/verifySession";
|
2025-01-27 22:43:32 -05:00
|
|
|
import config from "@server/lib/config";
|
2024-10-02 20:04:51 -04:00
|
|
|
|
|
|
|
export async function logout(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
2024-12-21 21:01:12 -05:00
|
|
|
next: NextFunction
|
2024-10-02 20:04:51 -04:00
|
|
|
): Promise<any> {
|
2025-01-26 14:42:02 -05:00
|
|
|
const { user, session } = await verifySession(req);
|
|
|
|
if (!user || !session) {
|
2025-01-27 22:43:32 -05:00
|
|
|
if (config.getRawConfig().app.log_failed_attempts) {
|
|
|
|
logger.info(
|
|
|
|
`Log out failed because missing or invalid session. IP: ${req.ip}.`
|
|
|
|
);
|
|
|
|
}
|
2024-10-02 20:04:51 -04:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.BAD_REQUEST,
|
2024-12-21 21:01:12 -05:00
|
|
|
"You must be logged in to sign out"
|
|
|
|
)
|
2024-10-02 20:04:51 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-10-04 23:14:40 -04:00
|
|
|
try {
|
2025-02-05 22:00:29 -05:00
|
|
|
try {
|
|
|
|
await invalidateSession(session.sessionId);
|
|
|
|
} catch (error) {
|
|
|
|
logger.error("Failed to invalidate session", error)
|
|
|
|
}
|
|
|
|
|
2025-01-13 23:59:10 -05:00
|
|
|
const isSecure = req.protocol === "https";
|
|
|
|
res.setHeader("Set-Cookie", createBlankSessionTokenCookie(isSecure));
|
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",
|
2024-12-21 21:01:12 -05:00
|
|
|
status: HttpCode.OK
|
2024-10-04 23:14:40 -04:00
|
|
|
});
|
|
|
|
} catch (error) {
|
2024-12-21 21:01:12 -05:00
|
|
|
logger.error(error);
|
2024-10-04 23:14:40 -04:00
|
|
|
return next(
|
2024-12-21 21:01:12 -05:00
|
|
|
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "Failed to log out")
|
2024-10-04 23:14:40 -04:00
|
|
|
);
|
|
|
|
}
|
2024-10-02 20:04:51 -04:00
|
|
|
}
|