Ek4m
Ek4m

Reputation: 15

Next-auth credentials provider doesn't work as expected

I'm using next-app-router for my app and next-auth for authentication. I have this next-auth config options:

import { AuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { User } from "./models";
import SequelizeAdapter from "@next-auth/sequelize-adapter";
import sequelize from "./sequelize";
import { Encryption } from "@/utils";
import { ValidationError } from "yup";
import { LoginSchema } from "@/app/api/auth/schema";

export const authOptions: AuthOptions = {
adapter: SequelizeAdapter(sequelize, { models: { User }, synchronize: true }),
session: { strategy: "database" },
debug: true,
providers: [
GithubProvider({
  clientId: process.env.GITHUB_CLIENT_ID!,
  clientSecret: process.env.GITHUB_SECRET_ID!,
  allowDangerousEmailAccountLinking: true,
}),
    CredentialsProvider({
  name: "Credentials",
  type: "credentials",
  credentials: {
    email: { label: "Email", type: "email" },
    password: { label: "Password", type: "password" },
  },
  async authorize(credentials) {
    try {
      await LoginSchema.validate(credentials, { abortEarly: false });
      const user = await User.findOne({
        where: { email: credentials!.email, provider: "credentials" },
      });
      if (!user) throw new Error("User not found");
      const isValid = await Encryption.isMatched(
        credentials!.password,
        user.password
      );
      if (!isValid) throw new Error("Invalid credentials");
      return user;
    } catch (error) {
      if (error instanceof ValidationError) {
        throw new Error(error.errors[0]);
      } else {
        throw new Error((error as Error).message);
      }
    }
  },
  }),
  ],
  callbacks: {
session({ session, user }) {
  session.user = user;
  if ("password" in session.user) delete session.user.password;
  return session;
  },
  async signIn({ user, account }) {
  if (account?.provider !== "github") {
    let existingUser = await User.findOne({
      where: { email: user.email },
    });
    if (!existingUser) {
      existingUser = await User.create({
        firstName: user?.name?.split(" ")[0],
        email: user.email,
        lastName: user.name?.split(" ")[1] || "_",
        provider: "github",
      });
    }
  }
  return true;
},
},
 };

And I have this login form:

"use client";
import { FaGithub } from "react-icons/fa";
import React from "react";
import { signIn, SignInOptions } from "next-auth/react";
import Link from "next/link";

const LoginForm = () => {
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const body: SignInOptions = {
  email: formData.get("email"),
  password: formData.get("password"),
};
await signIn("credentials", body);
}
  return (
<>
  <form onSubmit={handleSubmit}>
    <input placeholder="Email" name="email" type="email" />
    <input placeholder="Password" name="password" type="password" />
    <button>Sign in now</button>
  </form>
  <button onClick={() => signIn("github")}>
    <FaGithub />
    Sign in
  </button>
  <Link href="/register">Create account</Link>
</>
 );
 };

export default LoginForm;

Whenever I do github login it works just fine,But when I try to use fill the form and submit signing up works fine, but no session is created. Every time I check the db but there is no session for specific user. That's why the user is always logged out

Upvotes: 0

Views: 59

Answers (0)

Related Questions