i changed the default session of the session interface given by authjs (nextauth) however its being read all over the project but one file wish containes the authorized method
when i console log the user in all the project i find all the new attributes that i need but in the auth.config.ts the user has the default user attributes
i tried to get the user with an api but when i do so it gives me erros maybe because the middleware and authorized are dependant on imported dependancies
can anyone help me with this keep in mind my database is hosted on aws dynamodb if that matters .
PS : when consuming the auth.user.role in other components it works fine the problem is in this file alone.
this is the auth.ts file :
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
import { InternshipType, ROLE, User } from "./User";
import { addUserWithoutImageFile, getUserByEmail } from "./data";
import NextAuth, { DefaultSession } from "next-auth";
import { authConfig } from "./auth.config";
declare module "next-auth" {
interface Session {
user: {
name: string | undefined | null;
email: string | undefined | null;
password: string | null;
address: string | null;
role: ROLE;
image: string | undefined | null;
CV: string | null;
internshipStartDate: Date | null;
internshipDuration: number | null;
internshipType: InternshipType | null;
supervisor: string | null;
} & DefaultSession["user"];
}
}
export const {
handlers: { GET, POST },
signIn,
signOut,
auth,
} = NextAuth({
...authConfig,
providers: [
GithubProvider({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
CredentialsProvider({
async authorize(credentials) {
try {
const existingUser = await getUserByEmail(
credentials.email as string
);
if (!existingUser) {
throw new Error("Utilisateur n'existe plus!");
}
const isPasswordCorrect = await bcrypt.compare(
credentials.password as string,
existingUser.password as string
);
if (!isPasswordCorrect) {
throw new Error("Mot de passe incorrect!");
}
return existingUser;
} catch (error) {
throw error;
}
},
}),
],
callbacks: {
async signIn({ user, account }) {
if (account?.provider === "github") {
try {
const existingUser = await getUserByEmail(user.email as string);
if (existingUser) return true;
const newUser: User = {
email: user.email,
name: user.name,
image: user.image,
password: null,
address: null,
role: ROLE.INTERN,
CV: null,
internshipDuration: null,
internshipStartDate: null,
internshipType: null,
supervisor: null,
};
await addUserWithoutImageFile(newUser);
} catch (error) {
console.error("SignIn error:", error);
return false;
}
}
return true;
},
async jwt({ token }) {
const user = await getUserByEmail(token.email as string);
if (user) {
token.user = {
name: user.name,
email: user.email,
address: user.address,
role: user.role,
image: user.image,
CV: user.CV,
internshipStartDate: user.internshipStartDate,
internshipDuration: user.internshipDuration,
internshipType: user.internshipType,
supervisor: user.supervisor,
};
}
return token;
},
async session({ session, token }) {
const user: User = token.user as User;
return {
...session,
user: {
...user,
},
};
},
...authConfig.callbacks,
},
});
and this is the auth.config.ts :
import { NextRequest } from "next/server";
import { DefaultSession, Session } from "next-auth";
import { InternshipType, ROLE, User } from "./User";
export const authConfig = {
pages: {
signIn: "/login",
},
providers: [],
callbacks: {
async authorized({
request,
auth,
}: {
request: NextRequest;
auth: Session | null;
}) {
const user: User | undefined = auth?.user;
console.log("user", user);
const communRoutes = ["/home", "/contact", "/about"];
const isOnCommunRoutes = communRoutes.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
const isOnAdminRoute = request.nextUrl.pathname.startsWith("/admin");
const userRoutes = ["/profile"];
const isOnUserRoute = userRoutes.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
const authRoutes = ["/login", "/register"];
const isOnUnAuthenticatedRoute = authRoutes.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
if (isOnCommunRoutes && user?.role === ROLE.ADMIN) {
return Response.redirect(new URL("/admin", request.nextUrl));
}
if (isOnAdminRoute && user?.role !== ROLE.ADMIN) {
return Response.redirect(new URL("/home", request.nextUrl));
}
if (isOnUserRoute && user?.role === ROLE.ADMIN) {
return Response.redirect(new URL("/admin", request.nextUrl));
}
if (isOnUserRoute && !user) {
return false;
}
if (isOnUnAuthenticatedRoute && user) {
return Response.redirect(new URL("/home", request.nextUrl));
}
return true;
},
},
};
i tried consuming the user by api gave me weird error
i tried rewriting the interface of the session in the auth.config.ts file didnt work
expected : auth.user object to have the same attributes that i defined in auth.ts file but no i get default values.
Tamim Hmizi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.