User credentials displays to terminal but access denies #2160
-
Question 💬I am trying to implement NextAuth with Credentials (email and password). But the problem starts with after logging in. when I log in, credentials return in the vscode terminal (I console log in here is my import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { connectToDatabase } from '../../../util/mongodb';
let userAccount = null;
const options = {
providers: [
// Providers.GitHub({
// clientId: process.env.GITHUB_ID,
// clientSecret: process.env.GITHUB_SECRET,
// }),
// Providers.Email({
// server: {
// host: process.env.EMAIL_SERVER_HOST,
// port: process.env.EMAIL_SERVER_PORT,
// auth: {
// user: process.env.EMAIL_SERVER_USER,
// pass: process.env.EMAIL_SERVER_PASSWORD,
// },
// },
// from: process.env.EMAIL_FROM,
// }),
// Providers.Auth0({
// clientId: process.env.AUTH0_CLIENT_ID,
// clientSecret: process.env.AUTH0_CLIENT_SECRET,
// domain: process.env.AUTH0_DOMAIN,
// }),
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
let user;
const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
user = await res.json();
// const user = { id: '1', name: 'Suat Bayrak', email: 'test@test.com2' };
if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async signIn(user, account, profile) {
if (typeof user.userId !== typeof undefined) {
if (user.isActive === '1') {
return user;
} else {
return false;
}
} else {
return false;
}
},
async session(session, token) {
if (userAccount !== null) {
session.user = userAccount;
} else if (
typeof token.user !== typeof undefined &&
(typeof session.user === typeof undefined ||
(typeof session.user !== typeof undefined &&
typeof session.user.userId === typeof undefined))
) {
session.user = token.user;
} else if (typeof token !== typeof undefined) {
session.token = token;
}
return session;
},
async jwt(token, user, account, profile, isNewUser) {
if (typeof user !== typeof undefined) {
token.user = user;
}
return token;
},
},
// callbacks: {
// async redirect(url, baseUrl) {
// console.log(`url is ${url} and baseUrl is ${baseUrl}`);
// return `${baseUrl}/about`;
// },
// },
database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
};
export default (req, res) => NextAuth(req, res, options);
by the way, when I use static user credentials like i commented in the code above, it works perfectly fine and returns session info correctly... Also here is my import { signIn } from 'next-auth/client';
import { useState } from 'react';
import { useRouter } from 'next/router';
export default function SignIn() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
console.log('submitted!');
signIn('credentials', {
email: email,
password: password,
// email: '[email protected]',
// password: '1234',
callbackUrl: 'http://localhost:3000/about',
redirect: false,
}).then(function (result) {
console.log(result);
if (result.error !== null) {
if (result.status === 401) {
setLoginError(
'Your username/password combination was incorrect. Please try again'
);
} else {
setLoginError(result.error);
}
} else {
console.log(result);
router.push(result.url);
}
});
};
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input
name='email'
type='text'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<label>
Password
<input
name='password'
type='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<button type='submit'>Sign in</button>
</form>
);
} also here is my github repo for this whole code; GitHub Repo |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
When I remove |
Beta Was this translation helpful? Give feedback.
-
I'm not sure, but you could simplify your callbacks significantly. the I took the liberty to simplify your code, see if that somehow helps: import NextAuth from "next-auth"
import Providers from "next-auth/providers"
export default NextAuth({
providers: [
// Providers.GitHub({
// clientId: process.env.GITHUB_ID,
// clientSecret: process.env.GITHUB_SECRET,
// }),
// Providers.Email({
// server: {
// host: process.env.EMAIL_SERVER_HOST,
// port: process.env.EMAIL_SERVER_PORT,
// auth: {
// user: process.env.EMAIL_SERVER_USER,
// pass: process.env.EMAIL_SERVER_PASSWORD,
// },
// },
// from: process.env.EMAIL_FROM,
// }),
// Providers.Auth0({
// clientId: process.env.AUTH0_CLIENT_ID,
// clientSecret: process.env.AUTH0_CLIENT_SECRET,
// domain: process.env.AUTH0_DOMAIN,
// }),
Providers.Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const res = await fetch("http://localhost:3000/api/profile", {
method: "POST",
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" },
})
// Assuming that /api/profile returns null if user is not found/wrong credentials
return await res.json()
},
}),
],
pages: {
signIn: "/signin",
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async signIn(user) {
return user.userId && user.isActive === "1"
},
async session(session, token) {
session.user = token.user
return session
},
async jwt(token, user) {
if (user) token.user = user
return token
},
},
database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
}) |
Beta Was this translation helpful? Give feedback.
-
Huge thanks to @balazsorban44 , finally solved this issue. import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
import { connectToDatabase } from '../../../util/mongodb';
import User from '../../../models/User';
let userAccount = null;
const options = {
providers: [
// Providers.GitHub({
// clientId: process.env.GITHUB_ID,
// clientSecret: process.env.GITHUB_SECRET,
// }),
// Providers.Email({
// server: {
// host: process.env.EMAIL_SERVER_HOST,
// port: process.env.EMAIL_SERVER_PORT,
// auth: {
// user: process.env.EMAIL_SERVER_USER,
// pass: process.env.EMAIL_SERVER_PASSWORD,
// },
// },
// from: process.env.EMAIL_FROM,
// }),
// Providers.Auth0({
// clientId: process.env.AUTH0_CLIENT_ID,
// clientSecret: process.env.AUTH0_CLIENT_SECRET,
// domain: process.env.AUTH0_DOMAIN,
// }),
Providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials, req) {
console.log(credentials);
let user;
const res = await fetch('http://localhost:3000/api/profile/', {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
});
const arrayToJson = await res.json();
user = arrayToJson[0];
// ///////////////////////////////////////////////////////////////////
// const { db } = await connectToDatabase();
// const response = await db.collection('bookings').findOne({
// email: credentials.email,
// password: credentials.password,
// });
// const json = await JSON.parse(response);
// user = json;
// const user = { id: '1', name: 'Suat Bayrak', email: 'test@test.com2' };
if (user) {
return user;
} else {
return null;
}
},
}),
],
pages: {
signIn: '/signin',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async signIn(user) {
return user.userId && user.isActive === '1';
},
async session(session, token) {
session.user = token.user;
return session;
},
async jwt(token, user) {
if (user) token.user = user;
return token;
},
},
database: `mongodb+srv://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@nextjs-academia-sb.ki5vd.mongodb.net/test`,
};
export default (req, res) => NextAuth(req, res, options); |
Beta Was this translation helpful? Give feedback.
I'm not sure, but you could simplify your callbacks significantly.
the
typeof undefined
checks seem to be a very verbose way of checking property existence and wonder if they cause some kind of a problem.I took the liberty to simplify your code, see if that somehow helps: