Made some changes
This commit is contained in:
parent
dce7e51a53
commit
3d59e86559
@ -1,11 +1,11 @@
|
|||||||
import bcryptjs from "bcryptjs";
|
import bcryptjs from 'bcryptjs';
|
||||||
import { SignJWT } from "jose";
|
import { SignJWT } from 'jose';
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from '@prisma/client';
|
||||||
import { env } from "@utils/env";
|
import { env } from '@utils/env';
|
||||||
|
|
||||||
import { findUserByEmail, readUserCsv, User } from "../functions/csvReadWrite";
|
import { findUserByEmail, readUserCsv, User } from '../functions/csvReadWrite';
|
||||||
|
|
||||||
const usingPrisma = false;
|
const usingPrisma = false;
|
||||||
let prisma: PrismaClient;
|
let prisma: PrismaClient;
|
||||||
@ -13,8 +13,7 @@ if (usingPrisma) prisma = new PrismaClient();
|
|||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
try {
|
try {
|
||||||
const json = await req.json(); // Parse incoming JSON data
|
const { email, password } = await req.json(); // Parse incoming JSON data
|
||||||
const { email, password } = json.body;
|
|
||||||
|
|
||||||
const userData = await readUserCsv();
|
const userData = await readUserCsv();
|
||||||
console.log(userData);
|
console.log(userData);
|
||||||
@ -33,7 +32,7 @@ export async function POST(req: Request) {
|
|||||||
user = findUserByEmail(userData, email);
|
user = findUserByEmail(userData, email);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user && bcryptjs.compareSync(password, usingPrisma ? user.passwordHash : user.password)) {
|
if (user && bcryptjs.compareSync(password, usingPrisma ? user.hashedPassword : user.password)) {
|
||||||
// todo remove password from returned user
|
// todo remove password from returned user
|
||||||
|
|
||||||
// get user and relations
|
// get user and relations
|
||||||
|
|||||||
@ -1,8 +1,15 @@
|
|||||||
// app/api/logout/route.ts
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
(await cookies()).delete("jwt");
|
try {
|
||||||
return NextResponse.json({ message: "Logged out" });
|
const cookieStore = await cookies();
|
||||||
|
if (!cookieStore.has("jwt")) {
|
||||||
|
return NextResponse.json({ message: "No active session found" }, { status: 400 });
|
||||||
|
}
|
||||||
|
cookieStore.delete("jwt");
|
||||||
|
return NextResponse.json({ message: "Logged out" });
|
||||||
|
} catch (error) {
|
||||||
|
return NextResponse.json({ message: "Error logging out", error }, { status: 500 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,9 +1,13 @@
|
|||||||
import bcryptjs from "bcryptjs";
|
import bcryptjs from 'bcryptjs';
|
||||||
import { NextResponse } from "next/server";
|
import { SignJWT } from 'jose';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { env } from '@utils/env';
|
||||||
|
|
||||||
import { findUserByEmail, passwordStrengthCheck, readUserCsv, User, writeUserCsv } from "../functions/csvReadWrite";
|
import {
|
||||||
|
findUserByEmail, passwordStrengthCheck, readUserCsv, User, writeUserCsv
|
||||||
|
} from '../functions/csvReadWrite';
|
||||||
|
|
||||||
const usingPrisma = false;
|
const usingPrisma = false;
|
||||||
let prisma: PrismaClient;
|
let prisma: PrismaClient;
|
||||||
@ -11,8 +15,7 @@ if (usingPrisma) prisma = new PrismaClient();
|
|||||||
|
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
try {
|
try {
|
||||||
const json = await req.json(); // Parse incoming JSON data
|
const { email, password, name } = await req.json(); // Parse incoming JSON data
|
||||||
let { email, password, name } = json.body;
|
|
||||||
const accessLevel = "basic";
|
const accessLevel = "basic";
|
||||||
|
|
||||||
const userData = await readUserCsv();
|
const userData = await readUserCsv();
|
||||||
@ -57,9 +60,10 @@ export async function POST(req: Request) {
|
|||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
const passwordHash = await bcryptjs.hash(password, 10);
|
const passwordHash = await bcryptjs.hash(password, 10);
|
||||||
|
let user;
|
||||||
if (usingPrisma) {
|
if (usingPrisma) {
|
||||||
// todo add sending back newUser
|
// todo add sending back user
|
||||||
const newUser = await prisma.user.create({
|
user = await prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
name,
|
name,
|
||||||
email,
|
email,
|
||||||
@ -67,10 +71,26 @@ export async function POST(req: Request) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
userData.push({ name, email, password: passwordHash, accessLevel });
|
user = { name, email, password: passwordHash, accessLevel };
|
||||||
|
userData.push(user);
|
||||||
}
|
}
|
||||||
await writeUserCsv(userData);
|
await writeUserCsv(userData);
|
||||||
return NextResponse.json({ message: "Account Created" }, { status: 201 });
|
|
||||||
|
const secret = new TextEncoder().encode(env.JWT_SECRET_KEY);
|
||||||
|
const token = await new SignJWT({ userId: user.id })
|
||||||
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
|
.setExpirationTime("2w")
|
||||||
|
.sign(secret);
|
||||||
|
|
||||||
|
const response = NextResponse.json({ message: "Account Created" }, { status: 201 });
|
||||||
|
response.cookies.set("jwt", token, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
sameSite: "strict",
|
||||||
|
maxAge: 3600 * 168 * 2, // 2 weeks
|
||||||
|
path: "/",
|
||||||
|
});
|
||||||
|
return response;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error in writting :", error);
|
console.error("Error in writting :", error);
|
||||||
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
|
return NextResponse.json({ message: "Internal Server Error" }, { status: 500 });
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
|
import { env } from "@utils/env";
|
||||||
|
|
||||||
import { PrismaClient } from "@prisma/client";
|
import { PrismaClient } from "@prisma/client";
|
||||||
import { env } from "@utils/env";
|
|
||||||
import { verifyJwt } from "@utils/verifyJwt";
|
import { verifyJwt } from "@utils/verifyJwt";
|
||||||
|
|
||||||
const usingPrisma = false;
|
const usingPrisma = false;
|
||||||
|
|||||||
@ -23,17 +23,20 @@ const store = createStore<StoreModel>({
|
|||||||
conversionRates: { GBP: 0.85, USD: 1.14, EUR: 1 },
|
conversionRates: { GBP: 0.85, USD: 1.14, EUR: 1 },
|
||||||
tickers: { GBP: "£", USD: "$", EUR: "€" },
|
tickers: { GBP: "£", USD: "$", EUR: "€" },
|
||||||
},
|
},
|
||||||
// user: null,
|
user: null,
|
||||||
user: {
|
// user: {
|
||||||
id: 123456,
|
// id: 123456,
|
||||||
createdAt: new Date(8.64e15),
|
// createdAt: new Date(8.64e15),
|
||||||
email: "emily.neighbour@dyson.com",
|
// email: "tim.howitz@dyson.com",
|
||||||
passwordHash: "",
|
// passwordHash: "",
|
||||||
name: "Emily Neighbour",
|
// name: "Tim Howitz",
|
||||||
role: "ADMIN",
|
// role: "ADMIN",
|
||||||
scientist: undefined,
|
// scientist: undefined,
|
||||||
purchasedArtefacts: [],
|
// purchasedArtefacts: [],
|
||||||
},
|
// },
|
||||||
|
setUser: action((state, payload) => {
|
||||||
|
state.user = payload;
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
|
|||||||
@ -1,22 +1,208 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import axios from "axios";
|
import { useState, useEffect } from "react";
|
||||||
|
import { useStoreActions } from "@hooks/store";
|
||||||
|
import axios, { AxiosError } from "axios";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { User } from "@appTypes/Prisma";
|
||||||
|
import { FaSignOutAlt } from "react-icons/fa";
|
||||||
|
import { FaUser } from "react-icons/fa6";
|
||||||
|
|
||||||
export default function Profile() {
|
export default function Profile() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const setUser = useStoreActions((actions) => actions.setUser) as (user: User | null) => void;
|
||||||
|
const [user, setUserState] = useState<User | null>(null);
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [role, setRole] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchUser = async () => {
|
||||||
|
try {
|
||||||
|
const userData: User = {
|
||||||
|
id: 1,
|
||||||
|
createdAt: new Date(),
|
||||||
|
name: "John Doe",
|
||||||
|
email: "john.doe@example.com",
|
||||||
|
passwordHash: "hashed_password",
|
||||||
|
role: "SCIENTIST",
|
||||||
|
scientist: undefined,
|
||||||
|
purchasedArtefacts: [],
|
||||||
|
};
|
||||||
|
setUserState(userData);
|
||||||
|
setName(userData.name);
|
||||||
|
setEmail(userData.email);
|
||||||
|
setRole(userData.role);
|
||||||
|
} catch {
|
||||||
|
setError("Failed to load user data.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchUser();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!name || !email) {
|
||||||
|
setError("Name and email are required.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
setUserState({ ...user!, name, email, role });
|
||||||
|
alert("Profile updated successfully.");
|
||||||
|
setError("");
|
||||||
|
} catch {
|
||||||
|
setError("Failed to update profile. Please try again.");
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogout = async () => {
|
||||||
|
try {
|
||||||
|
const res = await axios.get("/api/logout");
|
||||||
|
if (res.status === 200) {
|
||||||
|
setUser(null);
|
||||||
|
router.push("/");
|
||||||
|
} else {
|
||||||
|
console.error("Failed to logout", res.data);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
const axiosError = error as AxiosError<{ message: string }>;
|
||||||
|
if (axiosError.response && axiosError.response.status === 400) {
|
||||||
|
setUser(null);
|
||||||
|
router.push("/");
|
||||||
|
} else {
|
||||||
|
console.error("Error during logout", axiosError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full h-full">
|
<div className="flex h-full justify-center bg-neutral-50">
|
||||||
<p>User</p>
|
<div className="w-1/2 flex flex-col">
|
||||||
|
<div className="mt-4">
|
||||||
<button
|
<button
|
||||||
className="bg-neutral-500"
|
onClick={handleLogout}
|
||||||
onClick={async () => {
|
className="float-right py-2 px-4 bg-red-500 text-white rounded-md hover:bg-red-700 transition-colors duration-200"
|
||||||
await axios.get("/api/logout");
|
aria-label="Log out"
|
||||||
router.push("/");
|
title="Log out"
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
Log out
|
{/* <FaSignOutAlt className="h-5 w-5" /> */}
|
||||||
|
Log Out
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<h2 className="mt-10 text-2xl font-semibold text-neutral-800">User Profile</h2>
|
||||||
|
<div className="w-full mt-4 bg-neutral-100 rounded-md border border-neutral-200">
|
||||||
|
<div className="p-8 justify-center flex">
|
||||||
|
{error && <p className="text-red-600 text-sm mb-2 text-center">{error}</p>}
|
||||||
|
<div className="flex flex-col py-6 justify-center w-full max-w-md">
|
||||||
|
<div className="flex justify-center items-center h-20 w-20 rounded-full bg-neutral-200">
|
||||||
|
<FaUser className="h-10 w-10"></FaUser>
|
||||||
|
</div>
|
||||||
|
<div className="mt-8 space-y-3 w-full">
|
||||||
|
<div>
|
||||||
|
<label className="text-sm text-neutral-600 block mb-1">Name</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
|
||||||
|
aria-label="User Name"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-sm text-neutral-600 block mb-1">Email</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
|
||||||
|
aria-label="User Email"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-sm text-neutral-600 block mb-1">Role</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={role}
|
||||||
|
className="w-full p-2 border border-neutral-300 rounded-md bg-neutral-100 text-sm text-neutral-600 cursor-not-allowed"
|
||||||
|
aria-label="User Role"
|
||||||
|
disabled
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-sm text-neutral-600 block mb-1">New Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="text-sm text-neutral-600 block mb-1">Confirm Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
className="w-full p-2 border border-neutral-300 rounded-md placeholder-neutral-400 focus:ring-2 focus:ring-blue-500 text-sm"
|
||||||
|
disabled={isSubmitting}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-10">
|
||||||
|
<div className="float-right flex">
|
||||||
|
<button
|
||||||
|
// onClick={handleSave}
|
||||||
|
className={`mr-4 px-4 py-2 bg-neutral-300 text-neutral-800 rounded-md hover:bg-neutral-400 flex items-center gap-2 font-medium ${
|
||||||
|
isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
|
||||||
|
}`}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
Clear Changes
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
className={`px-4 py-2 bg-blue-600 text-white rounded-md font-medium flex items-center gap-2 ${
|
||||||
|
isSubmitting ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"
|
||||||
|
}`}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
{isSubmitting ? (
|
||||||
|
<>
|
||||||
|
<svg
|
||||||
|
className="animate-spin h-5 w-5 text-white"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
|
<path
|
||||||
|
className="opacity-75"
|
||||||
|
fill="currentColor"
|
||||||
|
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||||
|
></path>
|
||||||
|
</svg>
|
||||||
|
Saving...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Save Changes"
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end mt-4"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,22 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { Dispatch, SetStateAction, useMemo, useState } from "react";
|
import { useState, useMemo } from "react";
|
||||||
import { FaTimes } from "react-icons/fa";
|
import { FaCalendarPlus, FaWarehouse, FaCartShopping } from "react-icons/fa6";
|
||||||
import { FaCalendarPlus, FaCartShopping, FaWarehouse } from "react-icons/fa6";
|
|
||||||
import { IoFilter, IoFilterCircleOutline, IoFilterOutline, IoToday } from "react-icons/io5";
|
import { IoFilter, IoFilterCircleOutline, IoFilterOutline, IoToday } from "react-icons/io5";
|
||||||
|
import { FaTimes } from "react-icons/fa";
|
||||||
|
import { SetStateAction, Dispatch } from "react";
|
||||||
// import type { Artefact } from "@prisma/client";
|
// import type { Artefact } from "@prisma/client";
|
||||||
|
import { Artefact } from "@appTypes/Prisma";
|
||||||
interface Artefact {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
location: string;
|
|
||||||
earthquakeId: string;
|
|
||||||
isRequired: boolean;
|
|
||||||
isSold: boolean;
|
|
||||||
isCollected: boolean;
|
|
||||||
dateAdded: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Warehouse Artefacts Data
|
// Warehouse Artefacts Data
|
||||||
const warehouseArtefacts: Artefact[] = [
|
const warehouseArtefacts: Artefact[] = [
|
||||||
@ -149,19 +138,7 @@ function ArtefactTable({
|
|||||||
}: {
|
}: {
|
||||||
artefacts: Artefact[];
|
artefacts: Artefact[];
|
||||||
filters: Record<string, string>;
|
filters: Record<string, string>;
|
||||||
setFilters: Dispatch<
|
setFilters: Dispatch<SetStateAction<Record<string, string>>>;
|
||||||
SetStateAction<{
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
earthquakeId: string;
|
|
||||||
location: string;
|
|
||||||
description: string;
|
|
||||||
isRequired: string;
|
|
||||||
isSold: string;
|
|
||||||
isCollected: string;
|
|
||||||
dateAdded: string;
|
|
||||||
}>
|
|
||||||
>;
|
|
||||||
setEditArtefact: (artefact: Artefact) => void;
|
setEditArtefact: (artefact: Artefact) => void;
|
||||||
clearSort: () => void;
|
clearSort: () => void;
|
||||||
}) {
|
}) {
|
||||||
@ -224,17 +201,7 @@ function ArtefactTable({
|
|||||||
<FilterInput
|
<FilterInput
|
||||||
value={filters[key]}
|
value={filters[key]}
|
||||||
onChange={(value) => {
|
onChange={(value) => {
|
||||||
setFilters({ ...filters, [key]: value } as {
|
setFilters({ ...filters, [key]: value } as Record<string, string>);
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
earthquakeId: string;
|
|
||||||
location: string;
|
|
||||||
description: string;
|
|
||||||
isRequired: string;
|
|
||||||
isSold: string;
|
|
||||||
isCollected: string;
|
|
||||||
dateAdded: string;
|
|
||||||
});
|
|
||||||
if (value === "") clearSortConfig();
|
if (value === "") clearSortConfig();
|
||||||
}}
|
}}
|
||||||
type={key === "dateAdded" ? "date" : "text"}
|
type={key === "dateAdded" ? "date" : "text"}
|
||||||
@ -707,7 +674,7 @@ export default function Warehouse() {
|
|||||||
const [showLogModal, setShowLogModal] = useState(false);
|
const [showLogModal, setShowLogModal] = useState(false);
|
||||||
const [showBulkLogModal, setShowBulkLogModal] = useState(false);
|
const [showBulkLogModal, setShowBulkLogModal] = useState(false);
|
||||||
const [editArtefact, setEditArtefact] = useState<Artefact | null>(null);
|
const [editArtefact, setEditArtefact] = useState<Artefact | null>(null);
|
||||||
const [filters, setFilters] = useState({
|
const [filters, setFilters] = useState<Record<string, string>>({
|
||||||
id: "",
|
id: "",
|
||||||
name: "",
|
name: "",
|
||||||
earthquakeId: "",
|
earthquakeId: "",
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import { useStoreActions } from "@hooks/store";
|
||||||
import { FormEvent, MouseEvent, useEffect, useRef, useState } from "react";
|
import { FormEvent, MouseEvent, useEffect, useRef, useState } from "react";
|
||||||
|
import { ErrorRes } from "@appTypes/Axios";
|
||||||
|
|
||||||
interface AuthModalProps {
|
interface AuthModalProps {
|
||||||
isOpen: boolean; // bool for if the modal should be visible
|
isOpen: boolean; // bool for if the modal should be visible
|
||||||
@ -11,7 +13,8 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
|||||||
const [isLogin, setIsLogin] = useState<boolean>(true);
|
const [isLogin, setIsLogin] = useState<boolean>(true);
|
||||||
const modalRef = useRef<HTMLDivElement>(null);
|
const modalRef = useRef<HTMLDivElement>(null);
|
||||||
const [isFailed, setIsFailed] = useState<boolean>(false);
|
const [isFailed, setIsFailed] = useState<boolean>(false);
|
||||||
const [failMessage, setFailMessage] = useState<boolean>(false);
|
const [failMessage, setFailMessage] = useState<string>();
|
||||||
|
const setUser = useStoreActions((actions) => actions.setUser);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) setIsLogin(true); // runs when isOpen changes, if it is true, the login is shown
|
if (isOpen) setIsLogin(true); // runs when isOpen changes, if it is true, the login is shown
|
||||||
@ -26,30 +29,49 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault(); // stops page from refreshing
|
e.preventDefault();
|
||||||
setIsFailed(false);
|
setIsFailed(false);
|
||||||
|
|
||||||
const formData = new FormData(e.currentTarget);
|
const formData = new FormData(e.currentTarget);
|
||||||
const email = formData.get("email") as string;
|
const email = formData.get("email") as string;
|
||||||
const password = formData.get("password") as string;
|
const password = formData.get("password") as string;
|
||||||
const name = isLogin ? undefined : (formData.get("name") as string);
|
const name = isLogin ? undefined : (formData.get("name") as string);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await axios.post(`/api/${isLogin ? "login" : "signup"}`, {
|
const res = await axios.post(
|
||||||
|
`/api/${isLogin ? "login" : "signup"}`,
|
||||||
|
isLogin ? { email, password } : { name, email, password },
|
||||||
|
{
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: isLogin ? { email, password } : { name: name!, email, password },
|
}
|
||||||
});
|
);
|
||||||
if (res.status) {
|
|
||||||
res.data.user;
|
if (res.status === 200) {
|
||||||
|
setUser(res.data.user);
|
||||||
onClose();
|
onClose();
|
||||||
} else if (res.status >= 400 && res.status < 500) {
|
|
||||||
console.log("4xx error:", res.data);
|
|
||||||
setFailMessage(res.data.message);
|
|
||||||
setIsFailed(true);
|
|
||||||
} else {
|
} else {
|
||||||
console.error("Error:", await res.data.message);
|
console.error("Unexpected response status:", res.status, res.data);
|
||||||
|
setFailMessage("Unexpected error occurred");
|
||||||
|
setIsFailed(true);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Request failed:", error instanceof Error ? error.message : String(error));
|
const axiosError = error as ErrorRes;
|
||||||
|
if (axiosError.response) {
|
||||||
|
const { status, data } = axiosError.response;
|
||||||
|
if (status >= 400 && status < 500) {
|
||||||
|
console.log("4xx error:", data);
|
||||||
|
setFailMessage(data.message || "Invalid request");
|
||||||
|
setIsFailed(true);
|
||||||
|
} else {
|
||||||
|
console.error("Server error:", data);
|
||||||
|
setFailMessage("Server error occurred");
|
||||||
|
setIsFailed(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error("Request failed:", axiosError.message);
|
||||||
|
setFailMessage("Network error occurred");
|
||||||
|
setIsFailed(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
10
src/types/Axios.ts
Normal file
10
src/types/Axios.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { AxiosError } from "axios";
|
||||||
|
|
||||||
|
interface ErrorResponse {
|
||||||
|
message: string;
|
||||||
|
error?: Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ErrorRes = AxiosError<ErrorResponse>;
|
||||||
|
|
||||||
|
export type { ErrorRes };
|
||||||
39
src/types/Prisma.ts
Normal file
39
src/types/Prisma.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
interface Scientist {
|
||||||
|
id: number;
|
||||||
|
createdAt: Date;
|
||||||
|
name: string;
|
||||||
|
level: string;
|
||||||
|
user: User;
|
||||||
|
userId: number;
|
||||||
|
superior: Scientist | undefined;
|
||||||
|
superiorId: number | undefined;
|
||||||
|
subordinates: Scientist[];
|
||||||
|
// earthquakes: Earthquake[];
|
||||||
|
// observatories: Observatory[];
|
||||||
|
artefacts: Artefact[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Artefact {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
location: string;
|
||||||
|
earthquakeId: string;
|
||||||
|
isRequired: boolean;
|
||||||
|
isSold: boolean;
|
||||||
|
isCollected: boolean;
|
||||||
|
dateAdded: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: number;
|
||||||
|
createdAt: Date;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
passwordHash: string;
|
||||||
|
role: string;
|
||||||
|
scientist: Scientist | undefined;
|
||||||
|
purchasedArtefacts: Artefact[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type { Scientist, Artefact, User };
|
||||||
@ -1,44 +1,6 @@
|
|||||||
import { Action } from "easy-peasy";
|
import { Action } from "easy-peasy";
|
||||||
|
|
||||||
// import type { User } from "@prisma/client";
|
// import type { User } from "@prisma/client";
|
||||||
|
import { User } from "@appTypes/Prisma";
|
||||||
interface Scientist {
|
|
||||||
id: number;
|
|
||||||
createdAt: Date;
|
|
||||||
name: string;
|
|
||||||
level: string;
|
|
||||||
user: User;
|
|
||||||
userId: number;
|
|
||||||
superior: Scientist | undefined;
|
|
||||||
superiorId: number | undefined;
|
|
||||||
subordinates: Scientist[];
|
|
||||||
// earthquakes: Earthquake[];
|
|
||||||
// observatories: Observatory[];
|
|
||||||
artefacts: Artefact[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Artefact {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
location: string;
|
|
||||||
earthquakeId: string;
|
|
||||||
isRequired: boolean;
|
|
||||||
isSold: boolean;
|
|
||||||
isCollected: boolean;
|
|
||||||
dateAdded: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface User {
|
|
||||||
id: number;
|
|
||||||
createdAt: Date;
|
|
||||||
name: string;
|
|
||||||
email: string;
|
|
||||||
passwordHash: string;
|
|
||||||
role: string;
|
|
||||||
scientist: Scientist | undefined;
|
|
||||||
purchasedArtefacts: Artefact[];
|
|
||||||
}
|
|
||||||
|
|
||||||
type Currency = "GBP" | "USD" | "EUR";
|
type Currency = "GBP" | "USD" | "EUR";
|
||||||
|
|
||||||
@ -53,6 +15,7 @@ interface CurrencyModel {
|
|||||||
interface StoreModel {
|
interface StoreModel {
|
||||||
currency: CurrencyModel;
|
currency: CurrencyModel;
|
||||||
user: User | null;
|
user: User | null;
|
||||||
|
setUser: Action<StoreModel, User | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type { StoreModel, Currency };
|
export type { StoreModel, Currency };
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user