Help NextAuth Credentials
Answered
Mugger Crocodile posted this in #help-forum
Mugger CrocodileOP
This is my app/api/auth/[...nextauth]/route.ts
import User from "@/lib/models/User.model";
import connect from "@/lib/mongodb";
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from 'bcryptjs';
export const handler = NextAuth({
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
username: { label: 'Username', type: 'text'},
password: { label: 'Password', type: 'password'}
},
async authorize(credentials) {
console.log('ce cacat')
await connect();
const { username, password } = credentials!;
const user = await User.findOne({ username })
console.log(username)
if (!user) {
throw new Error('No user found!')
}
const isValid = await bcrypt.compare(password, user.password)
if (!isValid) {
throw new Error('Invalid password!')
}
return { id: user._id, username: user.username}
}
})
],
session: {
strategy: 'jwt'
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.username = user.username
}
return token;
},
async session({ session, token }) {
session.user.id = token.id;
session.user.username = token.username;
return session;
}
},
debug: true
})
export { handler as GET, handler as POST }
Answered by Mugger Crocodile
Apparently it does not work with idx.google.com's emulator
4 Replies
Mugger CrocodileOP
import { signIn } from 'next-auth/react';
const onSubmit = async (values: z.infer<typeof LoginSchema>) => {
const res = await signIn('credentials', {
redirect: false,
username: values.username,
password: values.password,
})
if (res?.error) {
setError(res.error)
} else {
router.push('/portal')
}
}
but nothing happens on the authorize() function even when the signIn function is called.
Mugger CrocodileOP
Apparently it does not work with idx.google.com's emulator
Answer
Mugger CrocodileOP
When I tried in browser, everything was fine.