Skip to content

Commit

Permalink
chore: generate token on connect
Browse files Browse the repository at this point in the history
  • Loading branch information
ayussh-2 committed Oct 27, 2024
1 parent 2a6b6e1 commit 85b9be6
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 71 deletions.
78 changes: 40 additions & 38 deletions src/app/register/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { v4 } from 'uuid';

import Loader from '@/components/Loading/Loader';
import CampusAmbassador from '@/components/Register/CampusAmbassador/CampusAmbassador';
import FileInput from '@/components/Register/FileInput/FileInput';
import CheckBox from '@/components/Register/InputCheckBox/CheckBox';
Expand Down Expand Up @@ -251,13 +250,22 @@ 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,
sameSite: 'strict',
});

toast.success(
'Registration successful! You will recieve confirmation email within 4-5 days!',
isNitR
? 'Registration successful!'
: 'Registration successful! You will recieve confirmation email within 4-5 days!',
{
duration: 5000,
},
Expand Down Expand Up @@ -290,45 +298,39 @@ function Page() {

{isLoggedIn ? (
<RegisterInnerContainer>
{loading ? (
<Loader />
) : (
<>
<RegisterHeading>Register</RegisterHeading>
<RegisterForm>
{formFields.map((field) => {
if (isNitR && notNitrFields.includes(field.id)) {
return null;
}
return returnFormFields(field);
})}
</RegisterForm>

{!isNitR && (
<>
<UndertakingLink href={undertakingContent.link} target='_blank'>
{undertakingContent.text}
</UndertakingLink>
<PaymentPolicyInfo>
<Link href='/refundPolicy'>
Please review the Payment Policy before registering.
</Link>
<br />
NOTE: Registration Fees (₹899)
</PaymentPolicyInfo>
<CampusAmbassador
handleChange={handleChange}
userReferral={userDetails.phone}
isCampusAmbassador={userDetails.campusAmbassador}
/>
</>
)}
<RegisterHeading>Register</RegisterHeading>
<RegisterForm>
{formFields.map((field) => {
if (isNitR && notNitrFields.includes(field.id)) {
return null;
}
return returnFormFields(field);
})}
</RegisterForm>

<RegsiterButton onClick={handleSubmit} disabled={loading}>
{loading ? 'Loading...' : 'Register'}
</RegsiterButton>
{!isNitR && (
<>
<UndertakingLink href={undertakingContent.link} target='_blank'>
{undertakingContent.text}
</UndertakingLink>
<PaymentPolicyInfo>
<Link href='/refundPolicy'>
Please review the Payment Policy before registering.
</Link>
<br />
NOTE: Registration Fees (₹899)
</PaymentPolicyInfo>
<CampusAmbassador
handleChange={handleChange}
userReferral={userDetails.phone}
isCampusAmbassador={userDetails.campusAmbassador}
/>
</>
)}

<RegsiterButton onClick={handleSubmit} disabled={loading}>
{loading ? 'Loading...' : 'Register'}
</RegsiterButton>
</RegisterInnerContainer>
) : (
<PrimaryButton onClick={handleGoogleSignIn} disabled={authLoading}>
Expand Down
13 changes: 2 additions & 11 deletions src/components/ProfileMenu/ProfileMenu.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {
const user = getUserDetails();
const router = useRouter();
const path = usePathname();

// const { data: userDataInDb } = useSuspenseQuery(
// GET_USER_BY_UID,
// user.uid ? { variables: { uid: user.uid } } : skipToken,
// );
const isNitr = getUserDetails()?.isNitR;

const handleLogout = () => {
handleSignOut();
Expand All @@ -49,9 +45,6 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {

useEffect(() => {
const mongoId = Cookies.get('userDataDB');

console.log('mongoId:', mongoId);
// userDataInDb?.user.data.length > 0;
if (mongoId) {
if (path === '/register') {
toast.success('You are already registered!');
Expand All @@ -61,8 +54,6 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {
} else {
setIsRegistered(false);
}

// console.log('userDataInDb:', userDataInDb);
}, []);

return (
Expand All @@ -81,7 +72,7 @@ function ProfileMenu({ handleProfileToggle, handleNavClose }) {
<UserEmail>{user?.email}</UserEmail>
<MenuLinks>
{isRegistered ? (
<p>Your payment is being verified! You will be mailed shortly</p>
!isNitr && <p>Your payment is being verified! You will be mailed shortly</p>
) : (
<StyledLink href='/register' onClick={handleProfileToggle}>
Complete Your Registration
Expand Down
5 changes: 0 additions & 5 deletions src/context/auth-context.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,17 @@ export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [userInfo, setUserInfo] = useState({});
const [authLoading, setAuthLoading] = useState(false);
const [userMongoId, setUserMongoId] = useState('');

const handleGoogleSignIn = async () => {
setAuthLoading(true);
try {
const user = await signInWithGoogle();
const token = `Bearer ${user.accessToken}`;

if (user) {
const userData = {
name: user.displayName,
email: user.email,
uid: user.uid,
token,
photoUrl: user.photoURL,
};
Cookies.set('userData', JSON.stringify(userData), {
Expand Down Expand Up @@ -64,8 +61,6 @@ export const AuthProvider = ({ children }) => {
handleGoogleSignIn,
handleSignOut,
authLoading,
userMongoId,
setUserMongoId,
}}
>
{children}
Expand Down
21 changes: 4 additions & 17 deletions src/lib/apollo-client.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import Cookies from 'js-cookie';

import generateToken from '@/utils/generateToken';
import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { onError } from '@apollo/client/link/error';
Expand Down Expand Up @@ -44,24 +43,12 @@ const httpLink = new HttpLink({
fetch: reconnectFetch,
});

const authLink = setContext((_, { headers }) => {
let token;

if (typeof window !== 'undefined') {
try {
const userDataFromCookie = Cookies.get('userData');
const parsedUserData = JSON.parse(userDataFromCookie);
token = parsedUserData.token;
} catch (error) {
console.error(error);
throw new Error('Error parsing userData from cookie');
}
}

const authLink = setContext(async (_, { headers }) => {
const token = await generateToken();
return {
headers: {
...headers,
Authorization: token || '',
Authorization: `Bearer ${token}` || '',
},
};
});
Expand Down
22 changes: 22 additions & 0 deletions src/utils/generateToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { getAuth } from 'firebase/auth';

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;
}
} catch (error) {
console.error('Error generating token:', error);
return null;
}
};

export default generateToken;

0 comments on commit 85b9be6

Please sign in to comment.