Authorized file not reading the session user added attributes only the default ones NEXTJS / NEXTAUTH

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 :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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,
},
});
</code>
<code>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, }, }); </code>
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 :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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;
},
},
};
</code>
<code>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; }, }, }; </code>
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.

New contributor

Tamim Hmizi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật