Skip to content

Commit

Permalink
Chore: added recommended changes and logs user auth token (#206)
Browse files Browse the repository at this point in the history
* chore: add changes

* chore: add toast validation

* chore: add auth token

* chore: add console logs for bearer toekn

* chore: added logout button to navbar
  • Loading branch information
ayussh-2 authored Oct 24, 2024
1 parent c296395 commit 7747ec0
Show file tree
Hide file tree
Showing 10 changed files with 104 additions and 33 deletions.
15 changes: 14 additions & 1 deletion src/app/register/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import { useUserDetails } from '@/hooks/useUserDetails';
import CampusAmbassador from '@/components/Register/CampusAmbassador/CampusAmbassador';
import { PrimaryButton } from '@/components/shared/Typography/Buttons';
import { AuthContext } from '@/context/auth-context';
// import { RegistrationModal } from './RegistrationModal';
import { RegistrationModal } from './RegistrationModal';
import toast from 'react-hot-toast';

function Page() {
const [userDetails, setUserDetails] = useState({
Expand Down Expand Up @@ -51,6 +52,8 @@ function Page() {
const userDetails = getUserDetails();
if (userDetails.name) {
setIsLoggedIn(true);
} else {
setIsLoggedIn(false);
}
}, [getUserDetails, userInfo]);

Expand All @@ -75,6 +78,11 @@ function Page() {
}
return;
}

if (name === 'campusAmbassador' && userDetails.phone.length !== 10) {
toast.error('Please enter a valid phone number to proceed');
return;
}
setErrors((prev) => ({ ...prev, [name]: '' }));
setUserDetails((prev) => ({
...prev,
Expand Down Expand Up @@ -190,6 +198,9 @@ function Page() {
<UndertakingLink href={undertakingContent.link} target='_blank'>
{undertakingContent.text}
</UndertakingLink>
<PaymentPolicyInfo>
<Link href='/refundPolicy'>Please review the Payment Policy before registering.</Link>
</PaymentPolicyInfo>
<CampusAmbassador
handleChange={handleChange}
userReferral={userDetails.phone}
Expand All @@ -204,6 +215,8 @@ function Page() {
{authLoading ? 'Loading...' : 'Sign In with Google'}
</PrimaryButton>
)}

<RegistrationModal isOpen={isModalOpen} onClose={() => setModalOpen(false)} />
</RegisterContainer>
);
}
Expand Down
44 changes: 33 additions & 11 deletions src/components/Marginals/navbar/navbar.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use client';
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useContext } from 'react';
import {
HamburgerContainer,
MainBar,
Expand All @@ -19,10 +19,14 @@ import Image from 'next/image';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { AnimatePresence, motion } from 'framer-motion';
import { AuthContext } from '@/context/auth-context';
import { useUserDetails } from '@/hooks/useUserDetails';

const Navbar = () => {
const [isOpen, setIsOpen] = useState(false);
const pathname = usePathname();
const { handleSignOut, userInfo } = useContext(AuthContext);
const [isLoggedIn, setIsLoggedIn] = useState(false);

function handleToggle() {
setIsOpen(!isOpen);
Expand All @@ -36,6 +40,16 @@ const Navbar = () => {
handleCloseMenu();
}, [pathname]);

const getUserDetails = useUserDetails();
useEffect(() => {
const userDetails = getUserDetails();
if (userDetails.name) {
setIsLoggedIn(true);
} else {
setIsLoggedIn(false);
}
}, [getUserDetails, userInfo]);

return (
<NavContainer>
<div>
Expand All @@ -54,11 +68,15 @@ const Navbar = () => {
</MainBarItems>
))}
</MainBar>
<RegisterButton>
<Link href='/register' onClick={handleCloseMenu}>
{ButtonData.title}
</Link>
</RegisterButton>
{isLoggedIn ? (
<RegisterButton onClick={handleSignOut}>Logout</RegisterButton>
) : (
<RegisterButton>
<Link href='/register' onClick={handleCloseMenu}>
{ButtonData.title}
</Link>
</RegisterButton>
)}
<HamburgerContainer>
<Hamburger toggled={isOpen} toggle={handleToggle} size={20} />
</HamburgerContainer>
Expand Down Expand Up @@ -89,11 +107,15 @@ const Navbar = () => {
</ResItem>
))}

<HamburgerRegisterButton>
<Link href={ButtonData.link} onClick={handleCloseMenu}>
{ButtonData.title}
</Link>
</HamburgerRegisterButton>
{isLoggedIn ? (
<HamburgerRegisterButton onClick={handleSignOut}>Logout</HamburgerRegisterButton>
) : (
<HamburgerRegisterButton>
<Link href='/register' onClick={handleCloseMenu}>
{ButtonData.title}
</Link>
</HamburgerRegisterButton>
)}
</ResList>
</ResMen>
</motion.div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function CampusAmbassador({ handleChange, userReferral, isCampusAmbassador }) {
>
Your referral code is <strong>{userReferral}</strong>
<br />
<code className='text-lg'>Use this while referring to your peers.</code>
<p className='text-sm mt-2'>Use this while referring to your peers.</p>
</Description>
)}
</Container>
Expand Down
29 changes: 18 additions & 11 deletions src/components/Register/InputCheckBox/CheckBox.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
import React from 'react';
import { CheckBoxContainer, CheckBoxInput, CheckBoxLabel } from './CheckBox.styles';
import {
CheckBoxContainer,
CheckBoxInput,
CheckBoxLabel,
CheckBoxParentContainer,
} from './CheckBox.styles';
import { ErrorMessage } from '../InputField/InputField.styles';

function CheckBox({ label, checked, onChange, className, name, error }) {
return (
<CheckBoxContainer className={className}>
<CheckBoxLabel>{label}</CheckBoxLabel>
<CheckBoxInput
type='checkbox'
checked={checked}
onChange={onChange}
name={name}
$hasError={error && true}
/>
<CheckBoxParentContainer>
<CheckBoxContainer className={className}>
<CheckBoxLabel>{label}</CheckBoxLabel>
<CheckBoxInput
type='checkbox'
checked={checked}
onChange={onChange}
name={name}
$hasError={error && true}
/>
</CheckBoxContainer>
{error && <ErrorMessage>{error}</ErrorMessage>}
</CheckBoxContainer>
</CheckBoxParentContainer>
);
}

Expand Down
4 changes: 4 additions & 0 deletions src/components/Register/InputCheckBox/CheckBox.styles.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import styled from 'styled-components';
import tw from 'twin.macro';

export const CheckBoxParentContainer = styled.div`
${tw`flex flex-col gap-2 items-start`}
`;

export const CheckBoxContainer = styled.div`
${tw`flex items-center justify-between space-x-2 sm:space-x-3 md:space-x-4 w-full md:w-[35rem]`}
`;
Expand Down
20 changes: 18 additions & 2 deletions src/components/Register/SelectField/SelectField.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ function SelectField({
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref]);

function returnSortedOptions(array) {
const sortedOptions = array.sort((a, b) => a.label.localeCompare(b.label));

const othersIndex = sortedOptions.findIndex((option) => option.value === 'others');
if (othersIndex !== -1) {
const [othersOption] = sortedOptions.splice(othersIndex, 1);
sortedOptions.push(othersOption);
}

return sortedOptions;
}

const sortedOptions = returnSortedOptions(options);

return (
<div ref={ref}>
<SelectFieldParentContainer>
Expand All @@ -93,13 +108,14 @@ function SelectField({
{label && <Label>{label}</Label>}
<SelectFieldContainer $hasError={!!error} onClick={handleToggle}>
<SelectFieldInput>
{selectedOption || placeholder || 'Select an option'}
{isOthers ? 'Others' : selectedOption || placeholder || 'Select an option'}
</SelectFieldInput>
<DropdownIcon size={20} />
</SelectFieldContainer>

{isOpen && (
<DropdownList>
{options.map((option, index) => (
{sortedOptions.map((option, index) => (
<DropdownItem key={index} onClick={() => handleSelectChange(option.value)}>
{option.label}
</DropdownItem>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Register/SelectField/SelectField.styles.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const SelectFieldContainer = styled.div`
`;

const SelectFieldInput = styled.div`
${tw`appearance-none capitalize outline-none border-0 shadow-none flex-1 cursor-pointer w-32 truncate`}
${tw`appearance-none capitalize outline-none border-0 shadow-none flex-1 cursor-pointer w-32 truncate`}
`;

const DropdownIcon = styled(ChevronDown)`
Expand Down
4 changes: 4 additions & 0 deletions src/config/content/Registration/details.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ export const formFields = [
label: 'National Institute of Technology, Patna (NIT Patna)',
value: 'National Institute of Technology, Patna (NIT Patna)',
},
{
label: 'National Institute of Technology, Rourkela (NIT Rourkela)',
value: 'National Institute of Technology, Rourkela (NIT Rourkela)',
},
{
label: 'National Institute of Technology, Andhra Pradesh (NIT Andhra Pradesh)',
value: 'National Institute of Technology, Andhra Pradesh (NIT Andhra Pradesh)',
Expand Down
16 changes: 10 additions & 6 deletions src/context/auth-context.jsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
import { createContext, useEffect, useState } from 'react';
import { createContext, useState } from 'react';
import { toast } from 'react-hot-toast';
import { signInWithGoogle, signOutUser } from '@/firebase/auth';
import Cookies from 'js-cookie';
import { auth } from '@/firebase/firebase';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
const [userInfo, setUserData] = useState({});
const [userInfo, setUserInfo] = useState({});
const [authLoading, setAuthLoading] = useState(false);

const handleGoogleSignIn = async () => {
setAuthLoading(true);
try {
const user = await signInWithGoogle();

const token = await auth.currentUser.getIdToken();
console.log(`Bearer ${token}`);
if (user) {
const userData = { name: user.displayName, email: user.email, uid: user.uid };
const userData = { name: user.displayName, email: user.email, uid: user.uid, token: token };
Cookies.set('userData', JSON.stringify(userData), {
expires: 7,
sameSite: 'strict',
});
setUserData(userData);
setUserInfo(userData);
toast.success('Successfully signed in with Google.');
} else {
toast.error('Google sign-in failed. Please try again.');
Expand All @@ -35,7 +39,7 @@ export const AuthProvider = ({ children }) => {
const handleSignOut = async () => {
try {
await signOutUser();
setUserData({});
setUserInfo({});
Cookies.remove('userData');
toast.success('Successfully signed out.');
} catch (error) {
Expand All @@ -46,7 +50,7 @@ export const AuthProvider = ({ children }) => {

return (
<AuthContext.Provider
value={{ userInfo, setUserData, handleGoogleSignIn, handleSignOut, authLoading }}
value={{ userInfo, setUserInfo, handleGoogleSignIn, handleSignOut, authLoading }}
>
{children}
</AuthContext.Provider>
Expand Down
1 change: 1 addition & 0 deletions src/hooks/useUserDetails.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const useUserDetails = () => {
console.error('Error parsing userData from cookie:', error);
}
}

return userInfo;
}, [userInfo]);

Expand Down

0 comments on commit 7747ec0

Please sign in to comment.