#Saved Session is not JWT Token, it's the User Object?

13 messages · Page 1 of 1 (latest)

lyric sky
#

Hey, it's my first time using NextAuth.js and I had a lot of problems when trying to implement it into NextJS_14.

I'm using Javascript + App Router.

Could anyone tell me if I have any mistakes here or if I understood something wrong.

[...nextauth]/route.js File


import NextAuth from 'next-auth';

import CredentialsProvider from "next-auth/providers/credentials";
import userModel from "@/models/User";
import dbConnect from "@/lib/dbConnect";
import bcrypt from "bcrypt";

dbConnect();

export const AuthOptions = {
    providers: [
        CredentialsProvider({
            async authorize(credentials) {
                try {
                    const { username, password } = credentials;

                    // Find the user in the database
                    const user = await userModel.findOne({ username });

                    if (user) {
                        // Compare the provided password with the hashed password in the database
                        const passwordMatch = await bcrypt.compare(password, user.password);

                        if (passwordMatch) {
                            // Return the user object
                            return user;
                        } else {
                            console.log("Password does not match");
                        }
                    }

                    // Return null if the user is not found or the password does not match
                    return null;
                } catch (e) {
                    console.log(e);
                    return null;
                }
            }
        })
    ],
    session: {
        strategy: "jwt",
        maxAge: 24 * 60 * 60, // 1 day
    },
    pages: {
        signIn: "/login",
    },
    secret: process.env.JWT_SECRET,
    debug: process.env.NODE_ENV === "development",
    callbacks: {
        async session({ session, token }) {
            session.user = token.user;

            // verify if session is still valid
            const user = await userModel.findById(token?.user?._id);

            if (!user) {
                return null;
            }

            // verify if password matches
            if (user.password !== token.user.password) {
                return null;
            }

            // verify if username matches
            if (user.username !== token.user.username) {
                return null;
            }

            return session;
        },
        async jwt({ token, user }) {
            if (user) {
                token.user = user;
            }
            return token;
        }
    }
};

const handler = NextAuth(AuthOptions);

export { handler as GET, handler as POST };

dashboard/page.js

"use client";

import { useSession } from "next-auth/react";
import { redirect } from "next/navigation";

export default function Dashboard() {
    const { data: session, status } = useSession();

    if (status === "loading") {
        return <p>Loading...</p>;
    }

    if (!session) {
        return redirect("/login");
    }

    return (
        <>
            <h1>Dashboard</h1>
            <p>Welcome {JSON.stringify(session)}</p>
        </>
    );
}```
surreal duneBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

lyric sky
#

Yeah I am unsure whether this is the correct way of using NextAuth, I have indeed read the documentation, but it didn't really help me understand if I have correctly implemented it.

fair oriole
#

yes it return you the user object

lyric sky
#

Yeah, but I am unsure if this is the correct way to do it.

fair oriole
#

look good to me

lyric sky
#

But is it a good Idea to also return the hashed password in the session?

lyric sky
fair oriole
#

next-auth will omit it but you also can omit it before the return

lyric sky
#

I dont think I understand

fair oriole
#
if (passwordMatch) {
                            // Return the user object
delete user.password
                            return user;
                        } else {
                            console.log("Password does not match");
                        }
                    }
fair oriole
#

then use a database session