From 79406667f6c989ad1ce1e9754cc0cda112dc6e48 Mon Sep 17 00:00:00 2001 From: Andreas Date: Mon, 12 Jun 2023 06:10:28 +0200 Subject: [PATCH] refactored --- src/pages/api/auth/index.ts | 72 ++++++++++++------------------------- 1 file changed, 22 insertions(+), 50 deletions(-) diff --git a/src/pages/api/auth/index.ts b/src/pages/api/auth/index.ts index da277a8..863d03d 100644 --- a/src/pages/api/auth/index.ts +++ b/src/pages/api/auth/index.ts @@ -32,55 +32,27 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) const username = auth[0]; const password = auth[1]; // console.log(req.body); - MUser.sync() - .then(async user => { - // console.log(user); - return await MAuth.sync(); - }) - .then(async auth => { - // console.log(auth); - return await MUser.findOne({ where: { username: username } }); - }) - .then(async user => { - // console.log(user); - if (user == undefined) { - throw "no such user exists"; - } - else { - return user; - } - }) - .then(async user => { - const passIsValid = await validatePassword(password, user.password); - return { passIsValid, user }; - }) - .then(async ({ passIsValid, user }) => { - if (passIsValid) { - const authtoken = await MAuth.findOne({ where: { user_id: user.id } }); - return { authtoken, user } - } - else { - throw ("invalid password"); - } - }) - .then(async ({ authtoken, user }) => { - if (authtoken == undefined) { - if (user.id != undefined) { - // console.log("creating new auth token") - return await MAuth.create({ user_id: user.id }); - } - } - else { - return authtoken - } - }).then(authtoken => { - if (authtoken != null) { - // console.log(authtoken); - res.status(200).json(authtoken); - } - }) - .catch(error => { - res.status(500).json(error); - }); + await MUser.sync(); + await MAuth.sync(); + + let user = await MUser.findOne({ where: { username: username } }); + if (user == undefined) { + res.status(401).json("User does not exist"); + return; + } + + if (!(await validatePassword(password, user.password))) { + res.status(401).json("Invalid password"); + return; + } + + let authtoken = await MAuth.findOne({ where: { user_id: user.id } }); + if (authtoken == undefined) { + if (user.id != undefined) { + authtoken = await MAuth.create({ user_id: user.id }); + } + } + + res.status(200).json(authtoken); } } \ No newline at end of file