summaryrefslogtreecommitdiff
path: root/controllers/root/login.js
diff options
context:
space:
mode:
authorJulien Dessaux2022-11-19 18:41:35 +0100
committerJulien Dessaux2022-11-19 18:41:35 +0100
commit54e06aa44a3134dfc42db3e4b473abf5e181fc42 (patch)
tree35c2358e0cbe47d21972535b8485aa0fd9756b8d /controllers/root/login.js
parentUpdated dependencies and fixed lint errors (diff)
downloadjeux-de-mots-54e06aa44a3134dfc42db3e4b473abf5e181fc42.tar.gz
jeux-de-mots-54e06aa44a3134dfc42db3e4b473abf5e181fc42.tar.bz2
jeux-de-mots-54e06aa44a3134dfc42db3e4b473abf5e181fc42.zip
cleaned up the distinction between routes and controllers
Diffstat (limited to '')
-rw-r--r--controllers/root/login.js43
1 files changed, 43 insertions, 0 deletions
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);
+}