Skip to content

Commit

Permalink
Redflag fixes (#442)
Browse files Browse the repository at this point in the history
* Fix: Red flag of user creation

* Removed redundant calls to /users/me

* Fix: Role based Authentication data check

* Fix: Removed redundance API calls during route change in dashboard

* Fix: Fixed appropriate route changes

* Fix: Fixed API Call fetch during sign up and removed console.logs

---------

Co-authored-by: krishnanx <[email protected]>
  • Loading branch information
subru-37 and krishnanx authored Sep 9, 2024
1 parent fe9b47f commit 4fd54e3
Show file tree
Hide file tree
Showing 39 changed files with 354 additions and 10,934 deletions.
2 changes: 1 addition & 1 deletion apps/core-admin/src/controllers/organizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const createNewOrganization = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
const { id, name } = req.body;

console.log(id, name);
const newOrganization = await prisma.organization.create({
data: {
id,
Expand Down
27 changes: 26 additions & 1 deletion apps/core-admin/src/controllers/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const fetchAccountDetails = async (req: Request, res: Response) => {
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}

// console.log(prisma.)
const user = await prisma.user.findUnique({
where: {
id: userId,
Expand All @@ -26,7 +26,32 @@ export const fetchAccountDetails = async (req: Request, res: Response) => {
return res.status(500).json({ error: 'Something went wrong' });
}
};
export const myCredential = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
// console.log(userId);

if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
// console.log(prisma.)
const userDetails = await prisma.organizationUser.findFirst({
where: {
userId: userId, // assuming userId is a unique identifier
},
});
// console.log(userDetails);
if (userDetails) {
return res.status(200).json({ data: userDetails }); // Return the details of the user
} else {
console.log('User not found');
return res.status(404).json({ error: 'User not found' });
}
} catch (err: any) {
console.log(err);
return res.status(500).json({ error: 'Something went wrong' });
}
};
export const updateAccountDetails = async (req: Request, res: Response) => {
try {
const userId = req?.auth?.payload?.sub;
Expand Down
4 changes: 3 additions & 1 deletion apps/core-admin/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
getAttributeById,
getAttributeParticipants,
} from './controllers/attributes';
import { fetchAccountDetails, updateAccountDetails } from './controllers/users';
import { fetchAccountDetails, myCredential, updateAccountDetails } from './controllers/users';
import { validateOrganizationUser, validateOrganizationAdmin } from './middlewares/authorization';
import { addNewExtra, checkInExtra, getAllExtras, getExtraById } from './controllers/extras';
import { validateUUID } from './middlewares/validateParams';
Expand All @@ -48,6 +48,8 @@ router.get('/', (req: any, res: any) => {
}
});

router.get('/users/mycreds', myCredential);

router.get('/users/me', fetchAccountDetails);
router.put('/users/me', updateAccountDetails);

Expand Down
3 changes: 3 additions & 0 deletions apps/web-admin/next.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ['s.gravatar.com', 'cdn.auth0.com'], // Add all allowed domains here
},
};

module.exports = nextConfig;
61 changes: 60 additions & 1 deletion apps/web-admin/src/components/ProtectedRoute.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@ import { useEffect } from 'react';
import { useRouter } from 'next/router';
import { useAuth0 } from '@auth0/auth0-react';
import { Spinner, VStack, AbsoluteCenter } from '@chakra-ui/react';
import { useFetch } from '@/hooks/useFetch';
import { useContext } from 'react';
import { account } from '@/contexts/MyContext';
import { useMemo } from 'react';

export const ProtectedRoute = ({ children }) => {
const router = useRouter();
const { user, isAuthenticated, isLoading, loginWithRedirect } = useAuth0();
const { accountDetails, setAccountDetails, updateAccountDetails } = useContext(account);

const handleLogin = async () => {
loginWithRedirect({
Expand All @@ -13,11 +19,64 @@ export const ProtectedRoute = ({ children }) => {
},
});
};
const { loading, get, post } = useFetch();
// useEffect();
useMemo(() => {
// console.log(accountDetails);
if (accountDetails.orgId) {
// console.log('route')
router.replace(`/${accountDetails.orgId}`);
// console.log('trigger');
// console.log(accountDetails);
}
}, [isAuthenticated, accountDetails.orgId]);
async function postOrg() {
const id = user.sub.substring(6);
const name = user.nickname;
const { data, mystatus } = await post(`/core/organizations`, {}, { id, name });
if (mystatus === 200) {
showAlert({
title: 'Success',
description: 'Organization has been created successfully.',
status: 'success',
});
}
}
async function checkOrg() {
const response = await get('/core/users/mycreds');
// console.log(response.data.data);
if (response.status === 200) {
setAccountDetails((preValue) => {
return {
...preValue,
role: `${response.data.data.role}`,
orgId: `${response.data.data.organizationId}`,
};
});
} else {
postOrg();
}
}

// useEffect();
useMemo(() => {
// if (!isAuthenticated) {
// router.replace('/');
// console.log('not check')
// } else {
// checkOrg();
// // console.log(user.sub.substring(6));
// }
if (isAuthenticated) {
checkOrg();
// console.log('trigger');
}
}, [isAuthenticated]);
if (!isLoading) {
if (!isAuthenticated && router.pathname !== '/auth') router.replace('/');
else if (isAuthenticated && !user.email_verified) {
router.push('/onboarding/verify-email');
router.replace('/onboarding/verify-email');
// console.log('reroute');
return children;
}
return children;
Expand Down
57 changes: 57 additions & 0 deletions apps/web-admin/src/contexts/MyContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React, { createContext, useState, useEffect } from 'react';
import { useFetch } from '@/hooks/useFetch';
import { useAlert } from '@/hooks/useAlert';
import { useAuth0 } from '@auth0/auth0-react';
export const account = createContext();
const MyContext = ({ children }) => {
const [accountDetails, setAccountDetails] = useState({});
const { user, isAuthenticated, isLoading, loginWithRedirect } = useAuth0();
const { loading, get, put } = useFetch();
const showAlert = useAlert();
useEffect(() => {
const fetchAccountDetails = async () => {
if (isAuthenticated) {
const { data, status } = await get('/core/users/me');
const response = await get('/core/users/mycreds');
// console.log(response, data);
setAccountDetails((preValue) => ({ ...preValue, ...(data.accountDetails || {}) }));
}
};
fetchAccountDetails();
// console.log('trigger');
}, [isAuthenticated]);

const updateAccountDetails = async () => {
const { data, status } = await put('/core/users/me', {}, accountDetails);
// console.log(data);
if (status === 200) {
showAlert({
title: 'Success',
description: 'Account details updated successfully.',
status: 'success',
});
console.log(data);
setAccountDetails((prev) => {
return {
...prev,
...(data.accountDetails || {}),
};
});
} else {
showAlert({
title: 'Error',
description: data.error,
status: 'error',
});
}
};
return (
<div>
<account.Provider value={{ accountDetails, setAccountDetails, updateAccountDetails }}>
{children}
</account.Provider>
</div>
);
};

export default MyContext;
29 changes: 23 additions & 6 deletions apps/web-admin/src/layouts/DashboardLayout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ import { RxHamburgerMenu } from 'react-icons/rx';

import Sidebar from '@/components/Sidebar';
import { useAuth0 } from '@auth0/auth0-react';

export default function DashboardLayout({ previousPage, pageTitle, headerButton, children }) {
import Image from 'next/image';
import { useContext } from 'react';
import { account } from '@/contexts/MyContext';
export default function DashboardLayout({ headerButton, children }) {
const router = useRouter();
// console.log(accountDetails?.orgId, 'hi');
const { accountDetails, setAccountDetails } = useContext(account);

const [isMobile] = useMediaQuery('(max-width: 768px)');
const [isSidebarOpen, setSidebarOpen] = useState(isMobile);
const { user, isAuthenticated, isLoading } = useAuth0();

// router.
if (isAuthenticated) {
return (
<Flex height="100vh" flexDirection="column">
Expand All @@ -28,7 +32,7 @@ export default function DashboardLayout({ previousPage, pageTitle, headerButton,
alignItems="center"
>
<Text fontSize="4xl" fontWeight="bold">
{pageTitle}
{accountDetails?.name}
</Text>
<Flex
height={10}
Expand Down Expand Up @@ -63,12 +67,25 @@ export default function DashboardLayout({ previousPage, pageTitle, headerButton,
<Flex width="100%" alignItems="center" gap={10}>
<IoMdArrowRoundBack
size={30}
style={{
cursor: 'pointer',
}}
onClick={() => {
router.back();
}}
/>
<Image
src={user.picture}
alt="logo"
height={50}
width={50}
style={{ cursor: 'pointer' }}
onClick={() => {
router.push(previousPage);
router.push(`/${accountDetails?.orgId}`);
}}
/>
<Text fontSize="4xl" fontWeight="bold">
{pageTitle}
{accountDetails?.name}
</Text>
</Flex>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export default function AttributeById() {
columns={columns}
rows={attributeDetails}
onRowClick={(row) => {
router.push(`/organizations/${orgId}/events/${eventId}/participants/${row.id}`);
router.push(`/${orgId}/events/${eventId}/participants/${row.id}`);
}}
/>
</DashboardLayout>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default function Attributes() {
<>
<Button
onClick={() => {
router.push(`/organizations/${orgId}/events/${eventId}/attributes/new`);
router.push(`/${orgId}/events/${eventId}/attributes/new`);
}}
isLoading={loading}
>
Expand All @@ -70,7 +70,7 @@ export default function Attributes() {
columns={columns}
rows={attributes}
onRowClick={(row) => {
router.push(`/organizations/${orgId}/events/${eventId}/attributes/${row.id}`);
router.push(`/${orgId}/events/${eventId}/attributes/${row.id}`);
}}
/>
</DashboardLayout>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function NewAttribute() {
description: 'Attribute has been added successfully.',
status: 'success',
});
router.push(`/organizations/${orgId}/events/${eventId}/attributes`);
router.push(`/${orgId}/events/${eventId}/attributes`);
} else {
showAlert({
title: 'Error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default function CheckInExtra() {
description: 'Extra for participant has been checked in successfully.',
status: 'success',
});
router.push(`/organizations/${orgId}/events/${eventId}/extras/${extraId}`);
router.push(`/${orgId}/events/${eventId}/extras/${extraId}`);
} else {
showAlert({
title: 'Error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default function ExtraById() {
<>
<Button
onClick={() => {
router.push(`/organizations/${orgId}/events/${eventId}/extras/${extraId}/check-in`);
router.push(`/${orgId}/events/${eventId}/extras/${extraId}/check-in`);
}}
isLoading={loading}
disabled="true"
Expand All @@ -93,7 +93,7 @@ export default function ExtraById() {
</Button>
<Button
onClick={() => {
router.push(`/organizations/${orgId}/events/${eventId}/extras/${extraId}/settings`);
router.push(`/${orgId}/events/${eventId}/extras/${extraId}/settings`);
}}
isLoading={loading}
disabled="true"
Expand All @@ -109,7 +109,7 @@ export default function ExtraById() {
columns={columns}
rows={extraDetails}
onRowClick={(row) => {
router.push(`/organizations/${orgId}/events/${eventId}/participants/${row.id}`);
router.push(`/${orgId}/events/${eventId}/participants/${row.id}`);
}}
/>
</DashboardLayout>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default function Extras() {
<>
<Button
onClick={() => {
router.push(`/organizations/${orgId}/events/${eventId}/extras/new`);
router.push(`/${orgId}/events/${eventId}/extras/new`);
}}
isLoading={loading}
>
Expand All @@ -72,7 +72,7 @@ export default function Extras() {
columns={columns}
rows={extras}
onRowClick={(row) => {
router.push(`/organizations/${orgId}/events/${eventId}/extras/${row.id}`);
router.push(`/${orgId}/events/${eventId}/extras/${row.id}`);
}}
/>
</DashboardLayout>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default function NewExtra() {
description: 'Extra has been added successfully.',
status: 'success',
});
router.push(`/organizations/${orgId}/events/${eventId}/extras`);
router.push(`/${orgId}/events/${eventId}/extras`);
} else {
showAlert({
title: 'Error',
Expand Down
Loading

0 comments on commit 4fd54e3

Please sign in to comment.