Accessing props of user returned by CredentialsProvider
Unanswered
Asian Whale posted this in #help-forum
In my middleware logic (which I have in the
In
authorized
callback of auth.config.ts
), I would like to be able to access a field of the user object returned by the authorize()
function of the CredentialsProvider. For context, here is the structure of the user object:export type User = {
userID: number;
username: string;
email: string;
password: string;
isClosed: boolean;
isFrozen: boolean;
funds: number;
accountType: string;
}
In
authorized
, I would like to be able to get auth?.user.accountType
to use in my logic, but I am not sure if I need to do something extra to be able to do this. How can I get this to work, or if I can just do it, how do I resolve the error I get saying that accountType is not a property of user?3 Replies
For further context, here are the relevant auth files:
auth.ts
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ username: z.string().min(1).max(45), password: z.string().min(1).max(80) })
.safeParse(credentials);
if (parsedCredentials.success) {
const { username, password } = parsedCredentials.data;
const user = await getUser(username);
if (!user) return null;
const passwordsMatch = await bcrypt.compare(password, user.password);
if (passwordsMatch) return user;
}
console.log("Invalid credentials");
return null;
}
})
]
});
auth.config.ts
import type { NextAuthConfig } from "next-auth";
export const authConfig = {
pages: {
signIn: "/login"
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const user = auth?.user;
const isLoggedIn = !!user;
const isOnAccountInfo = nextUrl.pathname.startsWith("/buyerAccountInfo") || nextUrl.pathname.startsWith("/sellerAccountInfo");
if (isOnAccountInfo) {
if (isLoggedIn) return true;
return false;
} else if (isLoggedIn) {
if (nextUrl.pathname.startsWith("/login")) {
// if (user.accountType === "seller") {
return Response.redirect(new URL("/sellerAccountInfo", nextUrl));
// } else if (user.accountType == "buyer") {
// return Response.redirect(new URL("/buyerAccountInfo", nextUrl));
// }
}
}
return true;
}
},
providers: []
} satisfies NextAuthConfig;
middleware.ts
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";
export default NextAuth(authConfig).auth;
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)']
};
bumping since it has been a day