Hi there! I am doing a next.js application and i have a issue, when i use /signup and create a user, it’s supossed to redirect in /usuario, but instead is going to /signin after being a moment in /usuario, idk why it’s making that
To clarify, i using nextAuth for the login
Here is the signup page:
"use client"
import Link from "next/link"
import Image from 'next/image';
import CustomButton from '../../components/CustomButton';
import {signIn, useSession} from 'next-auth/react'
import { Navbar2 } from "@/components";
import { useRouter } from "next/navigation";
import React, {useState} from "react";
import CustomAlert from '@/components/CustomAlert';
export default function Form(){
const router = useRouter();
const { data: session, status: sessionStatus } = useSession();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const res = await fetch("/api/usuarios",{
method: "POST",
body: JSON.stringify(formData),
headers:{
"Content-Type": "application/json"
}
})
if(res.ok){
router.replace("/usuario");
} else {
throw new Error("Error al crear el usuario")
}
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) =>{
const value = e.target.value;
const name = e.target.name;
setFormData((prevState) => ({
...prevState,
[name]: value,
}));
}
const startingUsuariosData={
nombre: "",
apellido: "",
correo: "",
contrasena: "",
role: "usuario",
};
const [formData, setFormData] = useState(startingUsuariosData);
export default function Form(){
return(
<>
The signin page
"use client"
import Link from "next/link"
import Image from 'next/image';
import CustomButton from '@/components/CustomButton';
import {signIn, useSession} from 'next-auth/react'
import { Navbar2 } from "@/components";
import { useRouter } from "next/navigation";
import React, {useEffect, useState} from "react";
import CustomAlert from '@/components/CustomAlert';
export default function Form(){
// const session = useSession();
const router = useRouter();
const { data: session, status: sessionStatus } = useSession();
const [alertMessage, setAlertMessage] = useState(""); // Mensaje de alerta
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
if (sessionStatus === "authenticated") {
//router.replace("/usuario");
if(session?.user?.role === "usuario"){
router.replace("/usuario");
}else{
router.replace("/terapeuta");
}}
}, [sessionStatus, router]);
const handleSubmit = async (e: any) => {
e.preventDefault();
const email = e.target[0].value;
const password = e.target[1].value;
const res = await signIn('credentials', {
email,
password,
redirect: false,
});
if (res?.error) {
setAlertMessage("Contraseña y/o correo eléctronico incorrecto");
setIsVisible(true);
}
};
if (sessionStatus === "loading") {
return <h1>Loading...</h1>;
}
return(
<>
The route.ts (who is in charge of the signin process and signup in case of using google)
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import CredentialsProvider from "next-auth/providers/credentials";
import { connectDB } from "@/libs/mongodb";
import User from "@/models/usuarios";
import { GoogleProfile } from 'next-auth/providers/google';
import getServersession from 'next-auth';
const authOptions = { //const handler = NextAuth({ -> lo que estaba antes
providers: [
GoogleProvider ({
profile(profile:GoogleProfile){
return{
...profile,
role: "usuario",
id: profile.sub,
}
},
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
CredentialsProvider({
id: 'credentials',
name: "Credentials",
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "text" },
},
async authorize(credentials: any) { //credentials: any
{
await connectDB();
try {
const user = await User.findOne({ correo: credentials.email });
if (user && user.contrasena === credentials.password) {
// La contraseña coincide, puedes devolver el usuario
// console.log(user);
return user;
} else {
// La contraseña no coincide
return null;
}
} catch (err: any) {
throw new Error(err);
}}
},
})
],
callbacks: {
async signIn({user, account}: { user: any, account: any }) {
if (account?.provider === 'credentials') {
//console.log(user);
return true;
}
if (account && account.provider === 'google') {
const {name, email} = user;
try {
const res = await fetch('http://localhost:3000/api/usuarios', { //http://localhost:3000/api/usuarios
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
nombre: name,
correo: email,
role: "usuario",
}),
});
if (res.ok) {
console.log(user)
return true;
}
} catch (error) {
console.error(error);
return false;
}
}
return true;
},
jwt({ token, user }: { token: any, user: any }) {
// Persist the OAuth access_token to the token right after signin
if (user) {
token.role = user.role
}
//console.log(token);
return token;
},
session({ session, token}: { token: any, session: any }) { //, user
// Send properties to the client, like an access_token from a provider.
//session.accessToken = token.accessToken
session.user.role = token.role
//console.log(session);
return session;
}
}
};
const handler = NextAuth(authOptions);
export {handler as GET, handler as POST};
And the route.js (this in a file called usuarios, here you insert users into the database)
import { connectDB } from "@/libs/mongodb";
import Usuarios from "@/models/usuarios";
import { NextResponse } from "next/server";
//Función GET para obtener todos los usuarios
export async function GET() {
await connectDB();
const usuarios = await Usuarios.find({});
return NextResponse.json({ usuarios });
}
export async function POST(request) {
await connectDB();
const data = await request.json();
const userExists = await Usuarios.findOne({ correo: data.correo });
if (!userExists) {
const usuarios = await Usuarios.create(data);
return NextResponse.json({ usuarios });
} else{
//Si el usuario ya existe, no hace nada
return NextResponse.json({ message: "Usuario ya existe" });
}
}
export async function DELETE(request) {
const id = request.nextUrl.searchParams.get("id");
await connectDB();
await Usuarios.findByIdAndDelete(id);
return NextResponse.json({ message: "Usuario eliminado" });
}