summaryrefslogtreecommitdiff
path: root/controllers/root/login.js
blob: dc506cc29a4898a07338838ab054f9056c723e2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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, '/games');
	}
	return res.render('login', makePageData(req.session.user));
}

export async function login_post(req, res) {
	if (req.session.user !== undefined) {
		return res.redirect(302, '/games');
	}
	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');
	}
	res.status(403);
	return res.render('login', page);
}