72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
|
|
import { NextResponse } from "next/server";
|
||
|
|
import path from "path";
|
||
|
|
import fs from "fs";
|
||
|
|
import csv from "csv-parser";
|
||
|
|
|
||
|
|
type User = {
|
||
|
|
name: string;
|
||
|
|
email: string;
|
||
|
|
password: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @returns {array} - Array of Objects containing user data
|
||
|
|
*/
|
||
|
|
async function readUserCsv(): Promise<User[]>{
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
// Dynamic csv location generation
|
||
|
|
let csvPath = path.dirname(__dirname); // /login
|
||
|
|
csvPath = path.dirname(csvPath); // /api
|
||
|
|
csvPath = path.dirname(csvPath); // /app
|
||
|
|
csvPath = path.dirname(csvPath); // /src
|
||
|
|
csvPath = path.dirname(csvPath); // /[project] // ? not sure why this dirfolder is here...
|
||
|
|
csvPath = path.dirname(csvPath); // /termor-tracker
|
||
|
|
csvPath = path.join(csvPath,"src","databases","Users.csv");
|
||
|
|
//Forms array for user data
|
||
|
|
let results : User[] = [];
|
||
|
|
|
||
|
|
//Reads data and adds it to results
|
||
|
|
fs.createReadStream(csvPath)
|
||
|
|
.pipe(csv())
|
||
|
|
.on("data", (data) => results.push(data))
|
||
|
|
.on("end", () => {
|
||
|
|
resolve(results)
|
||
|
|
})
|
||
|
|
.on("error", (error) => {
|
||
|
|
reject(error)
|
||
|
|
})
|
||
|
|
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
function findUserByEmail(users: User[], email: string): User | undefined {
|
||
|
|
return users.find((user) => user.email === email);
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function POST(request: Request) {
|
||
|
|
try {
|
||
|
|
const body = await request.json(); // Parse incoming JSON data
|
||
|
|
const {email, password } = body;
|
||
|
|
console.log("Login API received data");
|
||
|
|
|
||
|
|
const userData = await readUserCsv();
|
||
|
|
|
||
|
|
console.log(userData)
|
||
|
|
console.log("Email:", email); // ! remove
|
||
|
|
console.log("Password:", password);// ! remove
|
||
|
|
|
||
|
|
const foundUser = findUserByEmail(userData,email)
|
||
|
|
if (foundUser && foundUser.password === password) {
|
||
|
|
console.log("User Details Correct")
|
||
|
|
return NextResponse.json({ message: "Login successful!" }, { status: 200 });
|
||
|
|
} else {
|
||
|
|
console.log("User email or password is invalid")
|
||
|
|
return NextResponse.json({ message: "Email and/or password are invalid" }, { status: 401 });
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
console.error("Error in signup endpoint:", error);
|
||
|
|
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
|
||
|
|
}
|
||
|
|
}
|