Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Credential auth #13

Open
12 tasks
Security2431 opened this issue Oct 17, 2023 · 0 comments · May be fixed by #92
Open
12 tasks

Credential auth #13

Security2431 opened this issue Oct 17, 2023 · 0 comments · May be fixed by #92

Comments

@Security2431
Copy link
Owner

Security2431 commented Oct 17, 2023

Good to know:

That's what I've achived so far:

import Credentials from "@auth/core/providers/credentials";
import Github from "@auth/core/providers/github";
import Google from "@auth/core/providers/google";
import type { DefaultSession } from "@auth/core/types";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { TRPCError } from "@trpc/server";
import * as bcrypt from "bcrypt";
import NextAuth from "next-auth";

import type { Prisma } from "@acme/db";
import { prisma } from "@acme/db";

import { env } from "./env.mjs";

export type { Session } from "next-auth";

// Update this whenever adding new providers so that the client can
export const providers = ["google", "github", "credentials"] as const;
export type OAuthProviders = (typeof providers)[number];

declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      role: Prisma.UserCreateInput["role"];
    } & DefaultSession["user"];
  }
}

const validatePassword = (
  plainPassword: string,
  hashedPassword?: string | null,
) => {
  if (!hashedPassword) {
    return false;
  }

  return bcrypt.compare(plainPassword, hashedPassword);
};

// We hash the user entered password using crypto
const encryptPassword = async (plainPassword: string) => {
  const salt = await bcrypt.genSalt();
  const hashedPassword = await bcrypt.hash(plainPassword, salt);

  return hashedPassword;
};

export const {
  handlers: { GET, POST },
  auth,
  CSRF_experimental,
} = NextAuth({
  adapter: PrismaAdapter(prisma),
  secret: env.NEXTAUTH_SECRET,
  session: {
    strategy: "database", // TODO: https://next-auth.js.org/configuration/options#secret
    // strategy: "jwt",
    maxAge: 30 * 24 * 60 * 60, // 30 Days
    updateAge: 24 * 60 * 60, // 24 hours
  },
  providers: [
    Credentials({
      type: "credentials",
      // name: "Credentials",
      async authorize(credentials) {
        const { email, password } = credentials as {
          email: string;
          password: string;
        };

        const user = await prisma.user.findUnique({
          where: { email },
        });

        const isValidPassword = await validatePassword(
          password,
          user?.password,
        );

        if (!user || !isValidPassword) {
          throw new TRPCError({
            code: "BAD_REQUEST",
            message: "Invalid email or password",
          });
        }

        return {
          id: user.id,
          email: user.email,
          role: user.role,
        };
      },
    }),
    Google({
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
      allowDangerousEmailAccountLinking: true,
    }),
    Github({
      clientId: env.GITHUB_ID,
      clientSecret: env.GITHUB_SECRET,
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      if (credentials) {
        return true;
      }

      console.log("email", email);
      console.log("profile", profile);
      console.log("account", account);
      console.log("user", user);

      const dbUser = await prisma.user.upsert({
        where: { email: user.email! },
        update: {
          name: user.name,
          image: user.image,
        },
        create: {
          name: user.name,
          email: user.email,
          image: user.image,
          password: user.name!,
        },
      });
      // add the userId to the session object
      // user.role = dbUser.role;
      user.id = dbUser.id;

      return true;
    },
    jwt: ({ token, profile }) => {
      if (profile?.id) {
        token.id = profile.id;
        token.image = profile.picture;
        // token.role = profile.role;
        // token.email = profile.email;
      }

      return token;
    },
    session: ({ session, user }) => ({
      ...session,
      user: {
        ...session.user,
        id: user.id,
        // role: user?.role,
      },
    }),
  },
  // callbacks: {
  // session: ({ session, user }) => ({
  //   ...session,
  //   user: {
  //     ...session.user,
  //     id: user.id,
  //   },
  // }),

  // @TODO - if you wanna have auth on the edge
  // jwt: ({ token, profile }) => {
  //   if (profile?.id) {
  //     token.id = profile.id;
  //     token.image = profile.picture;
  //   }
  //   return token;
  // },

  // @TODO
  // authorized({ request, auth }) {
  //   return !!auth?.user
  // }
  // },
});
 
@Security2431 Security2431 linked a pull request Jan 4, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant