Skip to content
This repository was archived by the owner on Aug 6, 2023. It is now read-only.
This repository was archived by the owner on Aug 6, 2023. It is now read-only.

[Example] How to use CredentialProvider #20

@alightinastorm

Description

@alightinastorm
import AstroAuth from "@astro-auth/core";
import { CredentialProvider } from "@astro-auth/providers";
import db from "../../../db";
import bcrypt from "bcryptjs"

type SignUpOptions = {
  email: string;
  password: string;
  confirmPassword: string;
  signUp: true;
}

type SignInOptions = {
  email: string;
  password: string;
}

type AuthOptions = SignUpOptions

const signUpHandler = async (db: any, { email, password, confirmPassword }: Omit<SignUpOptions, "signUp">) => {
  if (password !== confirmPassword) return false;
  const hashedPassword = await bcrypt.hash(password, 10)
  try {
    await db.user.create({
      data: {
        email,
        hashedPassword,
      }
    })
    return true;
  } catch (e) {
    return false
  }
}

const signInHandler = async (db: any, { email, password }: Pick<SignInOptions, "email"|"password">) => {
    const user = await db.user.findFirst({ where: { email } })
    if (!user) return false;
    const match = await bcrypt.compare(password, user.hashedPassword)
    if (!match) return false;
  
    return true;
}

export const all = AstroAuth({
  authProviders: [
    CredentialProvider({
       async authorize({ email, password, signUp, confirmPassword }: AuthOptions) {
        if (signUp) {
          return signUpHandler(db, { email, password, confirmPassword })
        }
  
        return signInHandler(db, { email, password })
  },
})
  ],
  hooks: {},
});

Assuming passwords are hashed with bcryptjs and there is a db (in this case it's prisma with sqlite)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions