Online Status of Users

I am trying to write logic that will keep track of Users online by updating my database column “isLoggedIn”. Currently when a user logs in using NextAuth as the authenticator is successfully writes to the database a vaule of 1. However, when the user logs out the database is not being updated. Please any assistance in this would be appreciated I am sure that I am just overlooking something here, or possibly I am going about this all wrong. Nevertheless here is the code snippet. Again thanks in advance for any support you may provide.

const authOptions = {
  adapter: PrismaAdapter(prisma),

  providers: [
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        username: { label: "Username", type: "text", placeholder: "jsmith" },
        password: { label: "Password", type: "password" },
        email: { label: "Email", type: "text", placeholder: "jsmith" },
      },
      async authorize(credentials) {
        if (!credentials.email || !credentials.password) {
          return null;
        }
      
        // Check if user exists
        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
        });
      
        if (!user) {
          return null;
        }
      
        // Check if password matches
        const passwordsMatch = await bcrypt.compare(
          credentials.password,
          user.password
        );
      
        if (!passwordsMatch) {
          return null;
        }
      
        // Update the isLoggedIn field based on login/logout
        const isLoggedIn = credentials ? true : false;
      
        const updatedUser = await prisma.user.update({
          where: {
            id: user.id,
          },
          data: {
            isLoggedIn,
          },
        });
      
        prisma.$disconnect(); // Disconnect from the database
      
        return updatedUser;
      },
    }),
  ],
  callbacks: {
    async jwt({token, user, session, trigger}){
      //console.log("jwt callback", {token, user, session});
      if (trigger ==="update" && session?.name) {
        token.name = session.name;
      }
      //pass in user id and title to token
      if(user){
        return {
          ...token,
          id: user.id,
          title: user.title,
          role: user.role,
        };
      }
      // update the usr in the database
      const newUser = await prisma.user.update({
        where: {
          id: token.id,
        },
        data: {
          name: token.name,
        },
      
      });
      //console.log("newUser", newUser);
      prisma.$disconnect(); // Disconnect from the database
      return token;
    },
    async session({ session, token, user }) {
      if (!token) {
        // User is not authenticated, update isLoggedIn field to false
        const updatedUser = await prisma.user.update({
          where: {
            id: user.id,
          },
          data: {
            isLoggedIn: false,
          },
        });
    
        prisma.$disconnect(); // Disconnect from the database
    
        return {
          ...session,
          user: {
            ...session.user,
            isLoggedIn: false,
          },
        };
      }
    
      // User is authenticated, include necessary information in the session
      return {
        ...session,
        user: {
          ...session.user,
          id: token.id,
          title: token.title,
          role: token.role,
          name: token.name,
        },
      };
    },
  },
  
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: 'jwt',
  },
  debug: process.env.NODE_ENV === 'development',
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

As you can see I am trying to use nextAuth authorized user to achieve this but i think this may not work.. any help will be appreciated.

Leave a Comment