next.jsbackendnext.js13next-authweb-development-server

Next.js NextAuth: fetching session id from two different schema, (parent and kid), parent uses google provider and kid uses credentials for login


When using NextAuth in a Next.js application to handle authentication, there's a problem with assigning the session ID correctly based on the user type (parent or kid) during login. The application has two types of users: parents and kids. Parents can add kids to their account, and kids can log in with a username and password. when a kid log in, the parent id is returned instead of the kids,

async session({ session, user }) {
    console.log("sessions start", user);
    try {
        await connectToDB(); 

        let query = {};
        if (session.user?.email) {
            query = { email: session.user.email };
        } else if (session.user?.name) {
            query = { username: session.user.name };
            console.log(query, "query 2");
        }

        const parentUser = await User.findOne(query);
        const kidUser = await Kids.findOne(query);

        if (parentUser) {
            session.user.id = parentUser._id.toString();
        } else if (kidUser) {
            session.user.id = kidUser._id.toString();
        }

        return session;
    } catch (error) {
        console.error("Error retrieving session:", error);
        throw error;
    }
},

async signIn({ profile }: { profile: ProfileType }) {
    try {
        await connectToDB(); // Connect to the database
        const userExist = await User.findOne({
            email: profile?.email,
        });

        if (!userExist) {
            await User.create({
                email: profile?.email,
                username: profile?.name?.replace(" ", " ").toLowerCase(),
                image: profile?.picture,
                points: 0,
                completedTasks: [],
                ongoingTasks: [],
                kids: [],
            });
        }

        return true;
    } catch (error) {
        console.error("Error signing in:", error);
        throw error;
    }
},

i tried some manipulations and i got the kids id but the kids sessioon doesnt return the name, from the session.user


Solution

  • for any one having this issue, i solved it by returning the profile on authorize

    async authorize(credentials) {
            // console.log(credentials, "credentials");
            try {
              if (!credentials || !credentials.username || !credentials.password) {
                // Return null if required credentials are missing
                return null;
              }
              const foundKid = await Kids.findOne({
                username: credentials.username,
              })
                .lean()
                .exec();
              // console.log(foundUser, "found user");
    
              if (foundKid) {
                const match = await bcrypt.compare(
                  credentials?.password,
                  foundKid.password
                );
                if (match) {
                 
                  return {
                    id: foundKid._id,
                    name: foundKid.username,
                  
                  };
                }
              }
            } catch (error) {
              console.log(error);
            }
            return null;
          },
        ```