2023-07-26 18:11:25 +02:00

56 lines
1.9 KiB
TypeScript

import mysql2, { Connection, RowDataPacket, OkPacket, QueryError } from "mysql2";
import { getConnection } from "@/db";
import { Post, postPlaceholder } from "@/model/Models";
import { getPosts, IPost } from "@/controller/Post";
import { NextApiRequest, NextApiResponse } from "next";
import { MPost } from "@/model/sequelize/Post";
import { MAttachment } from "@/model/sequelize/Attachment";
import { validatePassword, hashPassword } from "@/util/Auth";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'Post') {
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();
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);
}
}