Last active
January 30, 2022 19:52
-
-
Save tadeaspetak/24cce64fd38d834be85006d09ef133a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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