Skip to content

Commit

Permalink
fixes: fixed logout issue and improvements (#228)
Browse files Browse the repository at this point in the history
* fix: check isRegistered after signin

* fixes: profile fixes

* fixes: auth

* chore: add toast for duplicate entries!
  • Loading branch information
ayussh-2 authored Oct 27, 2024
1 parent d1f69cd commit e916439
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 48 deletions.
53 changes: 37 additions & 16 deletions src/app/register/page.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use client';
import { useContext, useLayoutEffect, useState } from 'react';
import { useContext, useEffect, useState } from 'react';

import Cookies from 'js-cookie';
import Link from 'next/link';
Expand Down Expand Up @@ -29,7 +29,8 @@ import { useIsLoggedIn } from '@/hooks/useIsLoggedIn';
import { useUserDetails } from '@/hooks/useUserDetails';
import handleLoadingAndToast from '@/utils/handleLoadingToast';
import { uploadToCloudinary } from '@/utils/uploadToCloudinary';
import { useMutation } from '@apollo/client';
import { useMutation, useSuspenseQuery, skipToken } from '@apollo/client';
import { GET_USER_BY_UID } from '@/graphql/queries/userQueries';

import {
DisclaimerPara,
Expand Down Expand Up @@ -72,6 +73,10 @@ function Page() {
const router = useRouter();
const storedUserId = getUserDetails().uid;
const isNitR = userDetails.instituteId === nitrID;
const { data: userDataDB, error: userErr } = useSuspenseQuery(
GET_USER_BY_UID,
storedUserId ? { variables: { uid: storedUserId } } : skipToken,
);

async function handleChange(event) {
const { name, value, type, checked } = event.target;
Expand Down Expand Up @@ -251,14 +256,9 @@ function Page() {
},
});

const newCookies = JSON.parse(Cookies.get('userData'));
Cookies.set('userData', JSON.stringify({ ...newCookies, isNitR }), {
expires: 7,
sameSite: 'strict',
});

Cookies.set('userDataDB', res.data.createUser.id, {
expires: 7,
const user = res.data.createUser;
Cookies.set('userDataDB', JSON.stringify({ ...user, isNitR }), {
expires: 1,
sameSite: 'strict',
});

Expand All @@ -275,22 +275,43 @@ function Page() {
}, 1300);
} catch (error) {
console.error(error);
toast.error('Registration failed! If the issue persists, try logging in again.', {
duration: 5000,
});
if (error.message.includes('Unique constraint failed')) {
toast.error('Registration failed! User already exists with the same credentials!', {
duration: 5000,
});
} else {
toast.error('Registration failed! If the issue persists, try logging in again.', {
duration: 5000,
});
}
} finally {
setLoading(false);
}
}

useLayoutEffect(() => {
if (Cookies.get('userDataDB')) {
useEffect(() => {
if (userErr) {
console.error('User query error:', userErr);
return;
}

const userCookie = Cookies.get('userDataDB');
const hasUserData = userDataDB?.user?.data?.length > 0;
const userData = hasUserData ? userDataDB.user.data[0] : null;
const isNitR = userData?.college === nitrID;
if (userCookie || hasUserData) {
if (!userCookie && userData) {
Cookies.set('userDataDB', JSON.stringify({ ...userData, isNitR }), {
expires: 1,
sameSite: 'strict',
});
}
router.push('/');
toast.success('You have been already registered!', {
duration: 5000,
});
}
}, []);
}, [userErr, userDataDB, router]);

return (
<RegisterContainer>
Expand Down
40 changes: 27 additions & 13 deletions src/components/HeroSection/Hero.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,25 @@ import { motion } from 'framer-motion';
import Cookies from 'js-cookie';
import Image from 'next/image';
import Link from 'next/link';

import { HeroGreenPrimaryButton, HeroLogoText, HeroPrimaryButton } from './styles';
import { useState, useEffect } from 'react';

export const Hero = () => {
const [isRegistered, setIsRegistered] = useState(false);
useEffect(() => {
function hasRegistered() {
try {
const status = JSON.parse(Cookies.get('userDataDB')).id;
if (status) {
setIsRegistered(true);
}
} catch (error) {
console.log('User not registered');
}
}
hasRegistered();
}, []);

const container = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0, transition: { duration: 0.8, delay: 0.2 } },
Expand All @@ -17,9 +32,6 @@ export const Hero = () => {
hidden: { scale: 0.9, opacity: 0 },
visible: { scale: 1, opacity: 1, transition: { duration: 1.2, ease: 'easeOut' } },
};

const isRegistered = Cookies.get('userDataDB');

return (
<div className='relative h-screen overflow-hidden md:h-[105vh] flex-col justify-center items-center'>
<motion.div
Expand Down Expand Up @@ -93,16 +105,18 @@ export const Hero = () => {
transition={{ duration: 1, delay: 1 }}
>
{!isRegistered && (
<Link href='/register'>
<HeroPrimaryButton>Register</HeroPrimaryButton>
</Link>
<HeroPrimaryButton>
<Link href='/register'>Register</Link>
</HeroPrimaryButton>
)}
<Link
href='https://drive.google.com/file/d/1jglpl2SzbmpRc73ML80zREhnpxxQF4qx/view?usp=sharing'
target='_blank'
>
<HeroGreenPrimaryButton>Brochure</HeroGreenPrimaryButton>
</Link>
<HeroGreenPrimaryButton>
<Link
href='https://drive.google.com/file/d/1jglpl2SzbmpRc73ML80zREhnpxxQF4qx/view?usp=sharing'
target='_blank'
>
Brochure
</Link>
</HeroGreenPrimaryButton>
</motion.div>
</motion.div>
</div>
Expand Down
88 changes: 74 additions & 14 deletions src/components/ProfileMenu/ProfileMenu.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
'use client';
import { useContext } from 'react';

import { useContext, useEffect, useState } from 'react';
import Cookies from 'js-cookie';

import { AuthContext } from '@/context/auth-context';
import { useUserDetails } from '@/hooks/useUserDetails';

import {
CloseButton,
Container,
Expand All @@ -23,10 +19,46 @@ import {

function ProfileMenu({ handleProfileToggle, handleNavClose }) {
const { handleSignOut } = useContext(AuthContext);
const getUserDetails = useUserDetails();
const user = getUserDetails();
const isNitr = getUserDetails()?.isNitR;
const isRegistered = Cookies.get('userDataDB');
const [userDetails, setUserDetails] = useState({
name: '',
email: '',
photoUrl: '',
id: '',
hasPaid: false,
isNitR: false,
});
const [error, setError] = useState(null);

useEffect(() => {
const fetchUserData = () => {
try {
const userProfileCookie = Cookies.get('userData');
const userDBCookie = Cookies.get('userDataDB');

if (!userProfileCookie || !userDBCookie) {
throw new Error('User data not found in cookies');
}

const userProfile = JSON.parse(userProfileCookie);
const userInDB = JSON.parse(userDBCookie);

setUserDetails({
name: userProfile.name,
email: userProfile.email,
photoUrl: userProfile.photoUrl,
id: userInDB.id,
hasPaid: userInDB.hasPaid,
isNitR: userInDB.isNitR,
});
} catch (e) {
console.error('Error fetching user data:', e);
setError('Failed to load user data');
}
};

fetchUserData();
}, []);

const handleLogout = () => {
handleSignOut();
handleProfileToggle();
Expand All @@ -38,6 +70,26 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {
handleNavClose(false);
};

if (error) {
return (
<Container>
<MenuCard
initial={menuVariants.initial}
animate={menuVariants.animate}
exit={menuVariants.exit}
transition={menuTransition}
key='profile-menu'
>
<MenuContent>
<CloseButton onClick={handleCloseMenu}>X</CloseButton>
<p className='text-red-500'>{error}</p>
<LogoutButton onClick={handleLogout}>Logout</LogoutButton>
</MenuContent>
</MenuCard>
</Container>
);
}

return (
<Container>
<MenuCard
Expand All @@ -49,12 +101,20 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {
>
<MenuContent>
<CloseButton onClick={handleCloseMenu}>X</CloseButton>
<ProfileImage src={user?.photoUrl} alt='User Profile' width={500} height={500} />
<UserName>{user?.name}</UserName>
<UserEmail>{user?.email}</UserEmail>
{userDetails.photoUrl && (
<ProfileImage src={userDetails.photoUrl} alt='User Profile' width={500} height={500} />
)}
{userDetails.name && <UserName>{userDetails.name}</UserName>}
{userDetails.email && <UserEmail>{userDetails.email}</UserEmail>}
<MenuLinks>
{isRegistered ? (
!isNitr && <p>Your payment is being verified! You will be mailed shortly</p>
{userDetails.id ? (
!userDetails.isNitR && (
<p className='text-center'>
{userDetails.hasPaid
? 'Congrats! you can now register for events!'
: 'Your payment is being verified! You will be mailed shortly'}
</p>
)
) : (
<StyledLink href='/register' onClick={handleProfileToggle}>
Complete Your Registration
Expand Down
3 changes: 2 additions & 1 deletion src/context/auth-context.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ export const AuthProvider = ({ children }) => {
email: user.email,
uid: user.uid,
photoUrl: user.photoURL,
token: user.accessToken,
};
Cookies.set('userData', JSON.stringify(userData), {
expires: 7,
expires: 1,
sameSite: 'strict',
});
setUserInfo(userData);
Expand Down
1 change: 1 addition & 0 deletions src/graphql/mutations/userMutations.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { gql } from '@apollo/client';
export const REGISTER_USER = gql`
mutation RegisterUser($user: UserCreateInputType!) {
createUser(user: $user) {
name
id
hasPaid
}
Expand Down
2 changes: 2 additions & 0 deletions src/graphql/queries/userQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export const GET_USER_BY_UID = gql`
data {
name
id
hasPaid
college
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/utils/generateToken.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { getAuth } from 'firebase/auth';

import Cookies from 'js-cookie';
const generateToken = async () => {
try {
const auth = getAuth();
const user = auth.currentUser;

if (user) {
const token = await user.getIdToken();
console.log('Generated Token:', token);
return token;
} else {
console.error('No user is signed in.');
return null;
const storedToken = JSON.parse(Cookies.get('userData')).token;
console.warn('Returning stored token..');
return storedToken;
}
} catch (error) {
console.error('Error generating token:', error);
Expand Down

0 comments on commit e916439

Please sign in to comment.