diff --git a/src/model/sequelize/User.ts b/src/model/sequelize/User.ts index 8c4a8fd..4f949c0 100644 --- a/src/model/sequelize/User.ts +++ b/src/model/sequelize/User.ts @@ -14,7 +14,7 @@ class UserModel extends Model{ updatedAt?: Date; username: string = ""; password: string = ""; - id: undefined; + id?:number; // declare title } export const MUser = sequelize.define( diff --git a/src/pages/api/auth/index.ts b/src/pages/api/auth/index.ts index 5096ae6..da277a8 100644 --- a/src/pages/api/auth/index.ts +++ b/src/pages/api/auth/index.ts @@ -15,19 +15,24 @@ import { validatePassword, hashPassword } from "@/util/Auth"; export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'GET') { - let auth; - try { - const authString = Buffer.from(req.headers.authorization.split(" ")[1], "base64").toString("utf8"); - auth = authString.split(":"); - } catch (error) { - res.status(500).json("Basic Auth is required"); - return; - } + let getAuth = () => { + try { + if (req.headers.authorization === undefined) { + throw "Basic Auth is required"; + } + const authString = Buffer.from(req.headers.authorization.split(" ")[1], "base64").toString("utf8"); + return authString.split(":"); + } catch (error) { + res.status(500).json(error); + return; + } + }; + const auth = getAuth() || ["",""]; console.log(auth); const username = auth[0]; const password = auth[1]; // console.log(req.body); - await MUser.sync() + MUser.sync() .then(async user => { // console.log(user); return await MAuth.sync(); @@ -41,26 +46,26 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) if (user == undefined) { throw "no such user exists"; } - else{ + else { return user; } }) .then(async user => { const passIsValid = await validatePassword(password, user.password); - return {passIsValid, user}; + return { passIsValid, user }; }) - .then(async ({passIsValid, user})=>{ - if(passIsValid){ + .then(async ({ passIsValid, user }) => { + if (passIsValid) { const authtoken = await MAuth.findOne({ where: { user_id: user.id } }); - return {authtoken, user} + return { authtoken, user } } - else{ - throw("invalid password"); + else { + throw ("invalid password"); } - }) - .then(async ({authtoken, user}) => { - if (authtoken == null) { - if (typeof user.id === "number") { + }) + .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 }); }