From c9f2411910e20a5356d2f828a06e79b112c504e0 Mon Sep 17 00:00:00 2001 From: LimJiaYan Date: Fri, 18 Oct 2024 19:51:50 +0800 Subject: [PATCH] Delete duplicate profile page --- frontend/app/(TobeDeleted)profiles/page.tsx | 316 -------------------- 1 file changed, 316 deletions(-) delete mode 100644 frontend/app/(TobeDeleted)profiles/page.tsx diff --git a/frontend/app/(TobeDeleted)profiles/page.tsx b/frontend/app/(TobeDeleted)profiles/page.tsx deleted file mode 100644 index 9f25ed3ea0..0000000000 --- a/frontend/app/(TobeDeleted)profiles/page.tsx +++ /dev/null @@ -1,316 +0,0 @@ -"use client" - -import React, { useEffect, useRef, useState } from 'react'; -import { Input } from "@/components/ui/input"; // Shadcn Input component -import { Button } from "@/components/ui/button"; // Shadcn Button component -import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; // Shadcn Avatar component -import { IoIosLogOut } from "react-icons/io"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogOverlay } from '@/components/ui/dialog'; -import Link from 'next/link'; -import { Badge } from '@/components/ui/badge'; -import { useRouter } from 'next/navigation'; -import { z } from 'zod'; -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { useForm } from 'react-hook-form'; -import { zodResolver } from "@hookform/resolvers/zod"; -import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; -import { Info, LoaderCircle } from 'lucide-react'; - -const formSchema = z.object({ - username: z.string().min(4, "Username requires at least 4 characters"), - email: z.string().min(1, "Email is required").email({ message: "Invalid email address" }), -}); - -const UserProfile = () => { - const router = useRouter(); - const [isLoading, setIsLoading] = useState(false); - const [feedback, setFeedback] = useState({ message: '', type: '' }); - const [username, setUsername] = useState(null); - const [email, setEmail] = useState(null); - const userId = useRef(null); - - const form = useForm>({ - resolver: zodResolver(formSchema), - defaultValues: { - username: "", - email: "", - }, - }); - - useEffect(() => { - const authenticateUser = async () => { - try { - const token = localStorage.getItem('token'); - - if (!token) { - router.push('/'); // Redirect to login if no token - return; - } - - // Call the API to verify the token - const response = await fetch(`${process.env.NEXT_PUBLIC_USER_API_AUTH_URL}/verify-token`, { - headers: { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${token}`, - }, - }); - - if (!response.ok) { - localStorage.removeItem("token"); // remove invalid token from browser - router.push('/'); // Redirect to login if not authenticated - return; - } - - const data = (await response.json()).data; - - setUsername(data.username); - setEmail(data.email); - form.setValue("username", data.username); - form.setValue("email", data.email); - userId.current = data.id; - } catch (error) { - console.error('Error during authentication:', error); - router.push('/login'); // Redirect to login in case of any error - } - }; - - authenticateUser(); - }, []); - - async function onChangeUserProfile(values: z.infer) { - let isErrorSet = false; - try { - await form.trigger(); - if (!form.formState.isValid) { - return; - } - - setIsLoading(true); - setFeedback({ message: '', type: '' }); // three type: "success", "error", or "email-verification" - - if (username != values.username) { - console.log("In user profile page: call update user api"); - const signUpResponse = await fetch(`${process.env.NEXT_PUBLIC_USER_API_USERS_URL}/${userId.current}`, { - method: "PATCH", - headers: { - 'Content-Type': 'application/json', - 'authorization': `Bearer ${localStorage.getItem('token')}` - }, - body: JSON.stringify({ username: values.username }), - }); - if (signUpResponse.status == 409) { - const responseMessage = (await signUpResponse.json()).message; - if (responseMessage.includes("username")) { - setFeedback({ message: "Username already in use. Please choose a different one", type: "error"}); - isErrorSet = true; - throw new Error("username already exists " + signUpResponse.statusText); - } else { - setFeedback({ message: 'Email already in use. Please choose a different one', type: 'error' }); - isErrorSet = true; - throw new Error("email already exist " + signUpResponse.statusText); - } - } else if (!signUpResponse.ok) { - setFeedback({ message: 'Failed to update profile.', type: 'error' }); - isErrorSet = true; - throw new Error("User not found" + signUpResponse.statusText); - } - } - - // Send email verifcation if user is changing email - if (email != values.email) { - // detect duplicate email - console.log("In user profile page: call api to check email exist in db"); - const userResponse = await fetch(`${process.env.NEXT_PUBLIC_USER_API_USERS_URL}/check?email=${values.email}`, { - headers: { - 'Content-Type': 'application/json', - } - }); - - if (userResponse.status == 200) { - console.log("duplicate email") - setFeedback({ message: "This email is already in use. Please choose another one.", type: 'error' }); - isErrorSet = true; - throw new Error("Email already exists in the database when user update their profile."); - } else if (userResponse.status !== 404) { - throw new Error("Error happen when calling API to detect duplicate email") - } - - const emailResponse = await fetch(`${process.env.NEXT_PUBLIC_USER_API_EMAIL_URL}/send-verification-email`, { - method: "POST", - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ id: userId.current, type: 'email-update', ...values }), - }) - - if (emailResponse.ok) { - setFeedback({ message: "An email has been sent to your new address for verification.", type: "email-verification" }); - } else { - setFeedback({ message: "There was an error sending the verification email.", type: 'error' }); - throw new Error("Error during email verification process."); - } - return; - } - - setFeedback({ message: 'Profile updated successfully.', type: 'success' }); - } catch(err) { - if (!isErrorSet) { - setFeedback({ message: "Something went wrong on our backend. Please retry shortly.", type: 'error' }); - } - console.error(err); - } finally { - setIsLoading(false); - } - } - - return ( -
-
-
- - PeerPrep - - {process.env.NODE_ENV == "development" && ( - - DEV - - )} -
-
- -
-
- -
- - - User Profile - - -
- - - {username?.slice(0, 2)} - -

{username}

-

{email}

-
-
- - ( - - -
- Username - - - - -

Minimum 4 characters

-
-
-
-
-
- - - - -
- )} - /> - ( - - Email - - - - - - )} - /> - - - -
-
- -
- { feedback.message && ( - setFeedback({ message: '', type: '' })}> - e.preventDefault()} - onInteractOutside={(e) => e.preventDefault()} - onEscapeKeyDown={(e) => e.preventDefault()}> - - - {feedback.type === 'error' && 'Error'} - {feedback.type === 'success' && 'Success'} - {feedback.type === 'email-verification' && 'Email Verification Required'} - - - {feedback.message} - - - - - - - - )} -
- ); -}; - -export default UserProfile;