Next.js role based access to component - next.js

I'm trying to restrict access to a admin area based on a int flag called isAdmin that is set to either 0 or 1 in my users table.
In the admin component I've made a function to fetch an API route that returns a unique user based on email, which will allow me to pass this parameter from the session to the API route - but it never returns true value
This is the code for the lookup function and how I restrict access in the component
export const getServerSideProps: GetServerSideProps = async () => {
const dashboards = await prisma.dashboard.findMany({
orderBy: {
id: "asc",
}
})
return {
props: JSON.parse(JSON.stringify({ dashboards })),
}
}
async function checkAdminUser(email: string) {
try {
const result = await fetch(`/api/user/${email}`, {
method: "GET",
})
const user = await result.json()
if (user.isAdmin == 1) {
return true
} else {
return false
}
} catch (error) {
console.error(error)
}
}
const Dashboard: React.FC<Props> = (props) => {
const { data: session, status } = useSession()
if (!session || !checkAdminUser(session.user?.email)) {
return (
<Layout>
<AccessDenied />
</Layout>
)
}
return (
<Layout>
..Layout code
</Layout>
)
}
I've also tried the checkAdminUser function as a Promise without success. The API route has been checked for valid output
"{"id":1,"image":null,"name":null,"email":"censoredfor#crawlers.com","emailVerified":null,"isAdmin":1,"createdAt":"2022-09-21T07:52:20.263Z","updatedAt":"2022-09-21T10:22:39.024Z"}"
Any tips to get me rolling would be greatly appreciated!

This answer assumes that console.log(user) gives you: {"id":1,"image":null,"name":null,"email":"censoredfor#crawlers.com","emailVerified":null,"isAdmin":1,"createdAt":"2022-09-21T07:52:20.263Z","updatedAt":"2022-09-21T10:22:39.024Z"}
Then you should better handle how you check if the user is an Admin. checkAdminUser returns a promise that is not resolved when you're checking for the value. A better solution would be to use react state to manage access to a specific component:
const Dashboard: React.FC<Props> = (props) => {
const { data: session, status } = useSession()
const [isAdmin, setAdmin] = useState(false);
const checkAdminUser = useCallback(async () => {
try {
const result = await fetch(`/api/user/${session?.user?.email}`, {
method: "GET",
})
const user = await result.json()
if (user.isAdmin == 1) {
setAdmin(true)
} else {
setAdmin(false)
}
} catch (error) {
console.error(error)
}
},[session?.user?.email])
useEffect(() => {
checkAdminUser()
},[checkAdminUser])
if (!session || !isAdmin) {
return (
<Layout>
<AccessDenied />
</Layout>
)
}
return (
<Layout>
..Layout code
</Layout>
)
}
Don't forget to: import {useCallback, useEffect, useState} from 'react'

Related

How to create a function that returns new session format with extra key value pair

I am using NextJS with NextAuth with google and email providers. Unfortunately, the session returns only few fields that does not include userId of the user from the database.
I created however a function that I intend to use with every getServerSideProps request. The function returns the following:
{
user: {
name: 'daniel sas',
email: 'emailofuser#gmail.com',
image: 'https://lh3.gooleusercontent.com/a/AEdFTp6r44ZwqcfJORNnuYtbVv_LYbab-wv5Uyxk=s96-c',
userId: 'clbcpc0hi0002sb1wsiea3q5d'
},
expires: '2022-12-17T20:18:52.580Z'
}
The problem is I am getting an error that does not allow me to pass the props in the page:
Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
In the function I get the user by the email, and attach the userId.
import { getSession } from "next-auth/react";
import prisma from './prisma'
// This function get the email and returns a new session object that includes
// the userId
export const requireAuthentication = async context => {
const session = await getSession(context);
const errorOrUserNotFound = () => {
return {
redirect: {
destination: '/signup',
permanent: false
}
}
}
// If there is no user or there is an error ret to signup page
if (!session) {
errorOrUserNotFound();
}
// If the user is not found return same redirect to signup
else {
try {
const user = await prisma.user.findUnique({where: { email: session.user.email }});
if (!user) return errorOrUserNotFound();
// Must return a new session here that contains the userId...
else {
const newSession = {
user: {
...session.user,
userId: user.id
},
expires: session.expires
};
console.log(newSession);
return {
props: {
session: newSession
}
}
}
}
catch (error) {
if (error) {
console.log(error);
}
}
}
}
The react component looks like this. In the getServerSideProps i return the await function. The problem is that when I log the prop in the serverside, I get the following:
{
props: { session: { user: [Object], expires: '2022-12-17T20:18:52.580Z' } }
}
However, if i log the props in the clientside, I get an empty object...
//Clientside compoen
import { getSession } from "next-auth/react"
import { Fragment, useState } from "react";
import { requireAuthentication } from "../../lib/requireAuthentication";
import CreateListModal from "./CreateListModal";
const DashboardPage = props => {
const [loading, setloading] = useState(false);
console.log(props);
return (
<section className="border-4 border-orange-800 max-w-5xl mx-auto">
<CreateListModal userId={props.userId} loading={loading} setloading={setloading} />
</section>
)
}
export const getServerSideProps = async context => {
const session = await getSession(context);
const reqAuth = await requireAuthentication(context);
console.log(reqAuth);
return reqAuth
}
export default DashboardPage;

How do you do server side rendering with nextjs [id].js in headless wordpress? fetch single page using graphql from Wordpress. like service/[id].js

I have a nextjs project that is using apollo graphql to fetch data from the backend. I am trying to render my page using server side rendering. But I am currently using graphql apollo hooks to fetch my data from the backend, and the react hooks prevents me from calling my backend inside of the getServerSideProps.
Create and fetch single page using graphql from Wordpress with clean URLs like services/[id].js
N.B: Warning Show ( Error: Response not successful: Received status code 500)
import {
gql,
ApolloClient,
InMemoryCache
} from "#apollo/client";
export const client = new ApolloClient({
uri: 'https://.........../graphql',
cache: new InMemoryCache()
});
const serviceDetail = (serviceOutput) => {
return (
<div>
{serviceOutput.serviceTitle}
{serviceOutput.serviceContent}
</div>
)
}
export const getServerSideProps = async (context) => {
const result = await client.query({
query: gql`
query serData($id: id!) {
HomePage: pageBy(uri: "https://......./home/") {
aboutSection {
serviceSec(id: $id) {
id
serviceTitle
serviceContent
serviceImage {
sourceUrl
}
}
}
}
}
`,
variables: {
id: context.params.id
}
})
return {
props: {
serviceOutput: result.data.HomePage.aboutSection.serviceSec;
},
};
}
export default serviceDetail;
i am not an expert, but as far i have used. you cannot use Apollo together with next js fetching method(ssg,ssr,isr).
Apollo runs queries on client side, and can be used with useQuery and useLazyQuery. while next js fetching is completely different.
I will demonstrate 2 ways here.
-- Using Apollo --
const FETCH_ALL = gql`
query MyQuery($first: Int!, $after: String) {
posts(first: $first, after: $after) {
edges {
node {
title
}
}
}
}
`;
export default function LoadMoreList() {
const { data } = useQuery(FETCH_ALL, {
variables: { first: 5, after: null },
notifyOnNetworkStatusChange: true,
});
return (
<>
<div>
{postdata.map((node, index) => {
{
return (
<div key={index}>
<h1>{node?.node?.title}</h1>
</div>
);
}
})}
</div>
</>
)}
=== using fetch and getStaticProps ==
--File1 (this is a fetch function, to which you pass your queries and variables)
async function fetchAPI(query, { variables } = {}) {
const headers = { "Content-Type": "application/json" };
const res = await fetch(process.env.WP_API, {
method: "POST",
headers,
body: JSON.stringify({ query, variables }),
});
const json = await res.json();
if (json.errors) {
console.log(json.errors);
throw new Error("Failed to fetch API");
}
return json.data;
}
export default fetchAPI;
-- File2 (this is a file that contains your query)
import fetchAPI from "./fetching";
export async function homeheadposts() {
const data = await fetchAPI(
`
query homeheadposts {
posts(first: 7) {
edges {
node {
id
slug
title
featuredImage {
node {
sourceUrl
}
}
excerpt(format: RAW)
}
}
}
}
`
);
return data?.posts;
}
-- File3 (place this function , where you wanna call and use the data, )
export async function getStaticProps() {
const latestPosts = await homeheadposts();
return {
props: { latestPosts },
};
}
export default function CallingData({ latestPosts }) {
console.log(latestPosts);
return <h1>hello</h1>;
}

Expected server HTML to contain a matching <input> in <div>

Whenever I check for the existence of the condition isAuthorized (true or false) I get this error message on the console. Basically the error refers to server-side rendering, but I can't identify where I should fix it. When i remove isAuthorized the error disappears.
I have my context, I return isAuthorized as true or false depending on the existence of the token in the cookie.
GlobalContext.js
const Global = createContext();
export function GlobalContextProvider({ children }) {
const { push } = useRouter();
const userCookie = Cookies.getJSON("user");
const [authUser, setAuthUser] = useState(() => {
if (userCookie) return userCookie;
if (!userCookie) return {};
});
const [isAuthorized, setIsAuthorized] = useState(() => {
return !authUser || Object.keys(authUser).length == 0 ? false : true;
});
useEffect(() => {
if (!isAuthorized) {
return push("/auth/login");
}
}, [isAuthorized]);
const value = {
isAuthorized,
setIsAuthorized,
authUser,
setAuthUser,
};
return <Global.Provider value={value}>{children}</Global.Provider>;
}
export const useGlobalContext = () => useContext(Global);
Index.jsx
export default function PanelLayout({ children, title }) {
const { push } = useRouter();
const { isAuthorized, setIsAuthorized } = useGlobalContext();
useEffect(() => {
const userData = Cookies.getJSON("user");
if (!userData || !userData.access_token) {
return push("/auth/login");
setIsAuthorized(false);
}
}, []);
return (
<>
{isAuthorized && (
<>
<Head>
// Content
</Head>
<input type="checkbox" id="sidebar-toggle" />
<div className="main-content">
// Content
</div>
</>
)}
</>
);
}
use this code in routes file where all the routes with components are placed.
and place this useEffect there if this condition meets give the access to that routes otherwise redirect it to login.
useEffect(() => {
const userData = Cookies.getJSON("user");
if (!userData || !userData.access_token) {
return push("/auth/login");
setIsAuthorized(false);
}
}, []);

too many renders react hooks, useEffect, map

hey guys I'm trying to add to sum a simple product price for each iteration and notice its runs too manytimes. in the use effect I have to listen to the UserCart. can't do it with an empty array/[userCart].
also I get the following error in more components which i couldnt fix for the same reason with the last argument in the useEffect:
update: I did divide the useEffect as suggusted but it with [userCart ] it enter infinite loop
the code:
import React, { useState, useEffect } from 'react'
import firebase from 'firebase';
import { useAuth, useStoreUpdate } from '../contexts/FirebaseContext';
export default function Cart() {
const [userMail, setUserMail] = useState(undefined)
const [userCart, setUserCart] = useState(undefined)
const [totalAmmout, setTotalAmmout] = useState(0)
const user = useAuth()
const userDoc = firebase.firestore().collection("cart").doc(userMail)
const updateStore = useStoreUpdate()
const updateCart = () => {
userDoc.get().then((doc) => {
if (doc.exists) {
let cart = doc.data()
setUserCart(cart)
}
})
}
async function removeFromCart(itemId, name, url, price, category, type, description) {
const cartItem = { itemId, name, url, price, category, type, description }
await userDoc.update({
item: firebase.firestore.FieldValue.arrayRemove(cartItem)
})
await updateCart()
await updateStore()
}
useEffect(() => {
if (user.currentUser) {
setUserMail(user.currentUser.email)
updateCart()
updateStore()
}
},userCart)
if (!userCart) return <h1>hold</h1>
let total = 0
return (
<main className="main-cart">
<div className="container">
{userCart.item && userCart.item.length >= 1 && userCart.item.map((item, i, arr) => {
console.log(item); //it runs more than 20 times
return (
< div className="item-container" key={item.itemId} >
<h3>{item.name}</h3>
<p>{item.price}</p>
<img height="150px" width="150px" src={item.url} alt="" />
<button onClick={async () => {
await removeFromCart(item.itemId, item.name, item.url, item.price, item.category, item.type, item.description)
}}>X</button>
</div>
)
})}
</div>
<div className="fixed-bottom-link">
<button>finish purchase</button>
</div>
</main >
)
}
edit :
I found the major component, but still couldnt make it work
the 2nd useEffect [userCart] wont run, it works only when not in the array, but it enter a loop:
import React, { useContext, useState, useEffect } from 'react';
import { auth } from '../firebase/firebase';
import firebase from '../firebase/firebase';
const FirebaseContext = React.createContext()
const StoreContext = React.createContext()
const StoreContextUpdate = React.createContext()
export function useAuth() {
return useContext(FirebaseContext)
}
export function useStore() {
return useContext(StoreContext)
}
export function useStoreUpdate() {
return useContext(StoreContextUpdate)
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true)
const [userMail, setUserMail] = useState(undefined)
const [userCart, setUserCart] = useState(undefined)
const userDoc = firebase.firestore().collection("cart").doc(userMail)
const updateCart = () => {
userDoc.get().then((doc) => {
if (doc.exists) {
let cart = doc.data()
setUserCart(cart)
}
})
}
function signup(email, password) {
return auth.createUserWithEmailAndPassword(email, password)
}
function login(email, pasword) {
return auth.signInWithEmailAndPassword(email, pasword)
}
function logout() {
return auth.signOut()
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async user => {
await setCurrentUser(user)
await setLoading(false)
})
return unsubscribe
}, [userCart])
useEffect(()=>{
async function refreshCart(){
await setUserMail(currentUser.email);
await updateCart()
}
if (currentUser && currentUser.email) {
refreshCart()
}
return
},[userCart])
const value = {
currentUser,
signup,
login,
logout
}
return (
<FirebaseContext.Provider value={value}>
<StoreContext.Provider value={userCart && userCart.item}>
<StoreContextUpdate.Provider value={updateCart}>
{!loading && children}
</StoreContextUpdate.Provider>
</StoreContext.Provider>
</FirebaseContext.Provider>
)
}
useEffect(() => {
if (user.currentUser) {
setUserMail(user.currentUser.email);
updateCart();
updateStore();
}
}, [userCart]); //<-- userCart needs to be inside array
and the reason for too many rerenders is you're calling updateCart function when the userCart changes and then userCart change will cause the call of updateCart again and this loop will repeat itself until you're out of memory
I think adding another useEffect might help you
useEffect(() => {
if (user.currentUser) {
setUserMail(user.currentUser.email);
updateStore();
}
}, [userCart]); //<-- userCart needs to be inside array
useEffect(() => {
if (user.currentUser) {
updateCart();
}
}, []);

nextJS SSR useRouter() does not work when refresh page

I am using nextJS SSR in my project. Now when I try to use the following code to get page parameters then it shows undefined.
function About() {
const router = useRouter();
const { plan_id } = router.query;
console.log(plan_id)
}
export default About;
It works when the page is routed from some other page (without page reload with "next/link") but it does not work when I refresh the page. Can someone please help?
I found the answer self. Actually when you refresh the page then the router does not get initialized instantly. So you can add that under UseEffect hook as following and you will be able to get the parameters
function About() {
const [param1, setParam1]=useState("");
const router = useRouter();
useEffect(() => {
if (router && router.query) {
console.log(router.query);
setParam1(router.query.param1);
}
}, [router]);
}
When this router parameter will change then it will call the "UseEffect" which can be used to retrieve the values.
function About({plan_id}) {
console.log(plan_id)
}
// this function only runs on the server by Next.js
export const getServerSideProps = async ({params}) => {
const plan_id = params.plan_id;
return {
props: { plan_id }
}
}
export default About;
You can find more intel in the docs.
I fix this problem with this method.
First add getServerSideProps to your page
//MyPage.js
export async function getServerSideProps({req, query}) {
return {
props: {
initQuery: query
}
}
}
Then created useQuery function like this
//useQuery.js
export let firstQuery = {}
export default function useQuery({slugKey = 'slug', initial = {}} = {}) {
const {query = (initial || firstQuery)} = useRouter()
useEffect(() => {
if (_.isEmpty(initial) || !_.isObject(initial))
return
firstQuery = initial
}, [initial])
return useMemo(() => {
if (!_.isEmpty(query)) {
return query
}
try {
const qs = window.location.search.split('+').join(' ');
const href = window.location.href
const slug = href.substring(href.lastIndexOf('/') + 1).replace(/\?.*/gi, '')
let params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
if (slug)
params[slugKey] = slug
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params
} catch {
}
}, [query])
}
And always use useQuery for receive query params
//MyPage.js
export default function MyPage({initQuery}) {
const query = useQuery({initial: initQuery})
return(
<div>
{query.myParam}
</div>
)
}
And in components like this
//MyComponent.js
export default function MyComponent() {
const query = useQuery()
return(
<div>
{query.myParam}
</div>
)
}
For those still having issues with this. Here is a solution that worked for me
function About() {
const [param1, setParam1]=useState("");
const router = useRouter();
const { param1 } = router.query()
useEffect(() => {
if (!param1) {
return;
}
// use param1
}, [param1]);
}
You can find the solution here

Resources