Thursday 22 June 2023

How to update user session from backend after updating user's metadata?

I´m using Next.js for the client side, auth0 to handle authentication and Django Rest Framework for the backend. Following the Auth0's Manage Metadta Using the Management API guide, I achieved to set new metadata values (I have checked it from the Dashboard). As it is spectated, if the user refresh its profile page (pages/profile.js), the old session metadata is rendered.

So my question is, how can I update user session after the metadata values has been set?

I have tried to use updateSession from @auth/nextjs-auth I also have tried nextjs-auth0: update user session (without logging out/in) after updating user_metadata , but checkSession() is not defined so I got lost there.

index.js

   async function handleAddToFavourite() {
      if (selected) {
         const data = await axios.patch("api/updateUserSession",)
         // Update the user session for the client side
         checkSession() //this function is not defined
         
      }
   }

api/updateUserSession.js

async function handler(req, res) {

  const session = await getSession(req, res);

  if (!session || session === undefined || session === null) {
    return res.status(401).end();
  }

  const id = session?.user?.sub;
  const { accessToken } = session;

  const currentUserManagementClient = new ManagementClient({
    token: accessToken,
    domain: auth0_domain.replace('https://', ''),
    scope: process.env.AUTH0_SCOPE,
  });

  const user = await currentUserManagementClient.updateUserMetadata({ id }, req.body);
  await updateSession(req, res, { ...session, user }); // Add this to update the session

  return res.status(200).json(user);
}

export default withApiAuthRequired(handler);

api/auth/[...auth0].js

const afterRefetch = (req, res, session) => {
     const newSession = getSession(req, res)
     if (newSession) {
          return newSession as Promise<Session>
     }
     return session
}


export default handleAuth({
  async profile(req, res) {
    try {
      await handleProfile(req, res, {
        refetch: true,
        afterRefetch 
      });
    } catch (error: any) {
      res.status(error.status || 500).end(error.message);
    }
  },

});

But I still have to log out and log in to see the new metadata values. Is there any way to update user's session from Django Rest Framework after performing the metadata update? If not, how can I update it using updateSession in Node.js?

Thank you in advance for your time.



from How to update user session from backend after updating user's metadata?

No comments:

Post a Comment