Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active January 30, 2022 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tadeaspetak/24cce64fd38d834be85006d09ef133a9 to your computer and use it in GitHub Desktop.
Save tadeaspetak/24cce64fd38d834be85006d09ef133a9 to your computer and use it in GitHub Desktop.
import express from "express";
const authApi = express.Router();
authApi.post("/session", async (req, res) => {
const params: { email: string; password: string } = req.body;
if (!req.headers["x-csrf-token"] || req.headers["x-csrf-token"] !== req.cookies["xCsrfToken"]) {
return res.status(400).json({ message: "Invalid CSRF token." });
}
const user = Users.findByEmail(params.email);
if (!user || !Users.verifyPassword(params.password, user)) {
return res.status(401).json({ message: "Invalid credentials." });
}
const sessionId = generateToken();
res.cookie("sessionId", sessionId, { httpOnly: true, maxAge: 1000 * 3600 * 24, sameSite: "lax" });
Sessions.add({ sessionId, userEmail: user.email });
const response: ApiSessionRes = { email: user.email, name: user.name };
res.status(200).json(response);
});
authApi.delete("/session", async (req, res) => {
if (req.cookies["sessionId"]) Sessions.remove(req.cookies["sessionId"]);
res.clearCookie("sessionId");
res.status(200).json({ message: "Signed out." });
});
export { authApi };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment