From 54e06aa44a3134dfc42db3e4b473abf5e181fc42 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Sat, 19 Nov 2022 18:41:35 +0100 Subject: cleaned up the distinction between routes and controllers --- controllers/login.js | 13 ------------- controllers/root/login.js | 43 +++++++++++++++++++++++++++++++++++++++++++ controllers/root/logout.js | 7 +++++++ controllers/root/root.js | 6 ++++++ 4 files changed, 56 insertions(+), 13 deletions(-) delete mode 100644 controllers/login.js create mode 100644 controllers/root/login.js create mode 100644 controllers/root/logout.js create mode 100644 controllers/root/root.js (limited to 'controllers') diff --git a/controllers/login.js b/controllers/login.js deleted file mode 100644 index b274a9e..0000000 --- a/controllers/login.js +++ /dev/null @@ -1,13 +0,0 @@ -function makeController(req) { - return { - title: "Connexion", - user: req.session.user, - data: { - username: "", - password: "", - }, - errors: {}, - }; -} - -export default makeController; diff --git a/controllers/root/login.js b/controllers/root/login.js new file mode 100644 index 0000000..b3e407b --- /dev/null +++ b/controllers/root/login.js @@ -0,0 +1,43 @@ +import { validationResult } from "express-validator"; + +import { login } from "../../database/users.js"; + +function makePageData(user) { + return { + title: "Connexion", + user: user, + data: { + username: "", + password: "", + }, + errors: {}, + }; +} + +export function login_get(req, res) { + if (req.session.user !== undefined) { + return res.redirect(302, "/play"); + } + return res.render("login", makePageData(req.session.user)); +} + +export async function login_post(req, res) { + if (req.session.user !== undefined) { + return res.redirect(302, "/play"); + } + let page = makePageData(req.session.user); + page.data = req.body; + page.errors = validationResult(req).mapped(); + if (Object.keys(page.errors).length === 0) { + const user = await login(page.data.username, page.data.password); + if (user !== null) { + req.session.user = user; + } else { + page.errors.mismatch = "L'identifiant et le mot de passe ne correspondent pas, ou l'identifiant n'existe pas."; + } + } + if (Object.keys(page.errors).length === 0) { + return res.redirect(302, "/games"); + } + return res.render("login", page); +} diff --git a/controllers/root/logout.js b/controllers/root/logout.js new file mode 100644 index 0000000..078df9a --- /dev/null +++ b/controllers/root/logout.js @@ -0,0 +1,7 @@ +export function logout_get(req, res) { + if (req.session.user !== undefined) { + res.clearCookie("JDMSessionId"); + req.session.destroy(); + } + return res.redirect(302, "/"); +} diff --git a/controllers/root/root.js b/controllers/root/root.js new file mode 100644 index 0000000..062edf4 --- /dev/null +++ b/controllers/root/root.js @@ -0,0 +1,6 @@ +export function root_get(req, res) { + if (req.session.user !== undefined) { + return res.redirect(302, "/games"); + } + return res.redirect(302, "/login"); +} -- cgit v1.2.3