Next.js Discord

Discord Forum

trying to update users in mongo but can't get the authenticated user

Unanswered
ayrreervae posted this in #help-forum
Open in Discord
hello
as explained in the title, i am logged in with nextauth credentials and am trying to update the logged on user. not sure if there is a better way, but here is how i am doing it:
1- get the id of the authenticated user
2- pass the id to update function as a param
3- get the user doc from the mongodb using the id
4- modify the user object
5- use the collection.updateOne to update the user
i am very open to a better/more advanced way of doing that.

BACK TO MY ISSUE
using
const session=await auth()
const user=session?.user;

returns a undefined user, and all properties (e.g. name ) of that user are empty.

2 Replies

auth.config.ts
import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login',
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isOnProfile = nextUrl.pathname.startsWith('/profile');
      const isOnLogin = nextUrl.pathname.startsWith('/login');
      if (isOnProfile) {
        if (isLoggedIn) 
          return true;
        return false; 
      } else if(isOnLogin)
        if(isLoggedIn) return Response.redirect(new URL('/profile',nextUrl));
      else false;
       return true;
    },
    
  },
  providers: [], 
} satisfies NextAuthConfig;
auth.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import Credentials from 'next-auth/providers/credentials';
import { z } from 'zod';

import bcrypt from 'bcrypt';
import { User } from '@/app/lib/definitions/user';
import { MongoDBAdapter } from '@auth/mongodb-adapter';
import clientPromise from './app/lib/db';
 
async function  getUser(email: string): Promise<User | undefined> {
  try {
    const db=(await clientPromise).db("menu-manager");
    const collection=db.collection("users");
    const user:User|any = await collection.findOne({email});
    console.log(user);
    if(user)
    {
      return user;      
    }
    throw Error( "no user");
  return;
  } catch (error) {
    throw new Error('Failed to fetch user.');
  }
}
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  adapter:MongoDBAdapter(clientPromise),
  providers: [
    Credentials({
      async authorize(credentials) {
        const parsedCredentials = z
          .object({ email: z.string(), password: z.string() })
          .safeParse(credentials);

          if(parsedCredentials.success){
            const {email, password}=parsedCredentials.data;
            const user:User|undefined=await getUser(email);
            if(!user) return null;
            else if(await bcrypt.compare(password,user.password)) return user;
        }
        throw Error('Invalid credentials error');
      }
    }),
  ],
});