refactored

This commit is contained in:
Andreas 2023-06-12 06:10:28 +02:00
parent 73685614ab
commit 79406667f6

View File

@ -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);
}
}