From 5832a696a8ed4e3a57114e92a91c4ac52f7f4ee4 Mon Sep 17 00:00:00 2001 From: Josh Moore Date: Sun, 15 Oct 2023 12:06:04 -0600 Subject: [PATCH] feat: authenticate sessions with bcrypt --- backend/routers/api.ts | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/backend/routers/api.ts b/backend/routers/api.ts index 555ef05..a39b6ba 100644 --- a/backend/routers/api.ts +++ b/backend/routers/api.ts @@ -48,9 +48,29 @@ router.post('/setup', BodyParserJson(), async (req, res) => { }); // User login -router.post('/login', BodyParserJson(), validateSessions, async (req, res) => { - log.success('User logged in', req.body.username); - res.json({ success: true, message: `User [${req.body.username}] logged in` }); +router.post('/login', BodyParserJson(), validateSessions, (req, res) => { + const { username, password } = req.body; + + data.getAll('users') + .then((users) => { + if (!users) throw new Error('Missing users data'); + else return Object.entries(users as { [key: string]: AssUser }) + .filter(([_uid, user]: [string, AssUser]) => user.username === username)[0][1]; // [0] is the first item in the filter results, [1] is is AssUser + }) + .then((user) => Promise.all([bcrypt.compare(password, user.password), user])) + .then(([success, user]) => { + success ? log.success('User logged in', user.username) + : log.warn('User failed to log in', user.username); + + // Set up the session information + if (success) req.session.ass!.auth = { + uid: user.id, + token: '' + }; + + res.json({ success, message: `User [${user.username}] ${success ? 'logged' : 'failed to log'} in` }); + }) + .catch((err) => res.status(400).json({ success: false, message: err.message })); }); // todo: authenticate API endpoints