From c20ef8d4ceb49bf03ddbe1c6e09ef0ad50c45446 Mon Sep 17 00:00:00 2001 From: reslear Date: Sat, 8 Jun 2024 14:20:05 +0200 Subject: [PATCH] chore(docs): add `express` credentials example (#11097) Co-authored-by: Kawahara Shotaro <121674121+k-taro56@users.noreply.github.com> Co-authored-by: Nico Domino --- .../authentication/credentials.mdx | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/docs/pages/getting-started/authentication/credentials.mdx b/docs/pages/getting-started/authentication/credentials.mdx index da30e8f878..9cb05b03b7 100644 --- a/docs/pages/getting-started/authentication/credentials.mdx +++ b/docs/pages/getting-started/authentication/credentials.mdx @@ -102,6 +102,50 @@ export { handle } from "./auth" ``` + + + +```ts filename="./src/routes/auth.route.ts" {2, 11} +import { ExpressAuth } from '@auth/express' +import Credentials from '@auth/express/providers/credentials' +import express from "express" +// Your own logic for dealing with plaintext password strings; be careful! +import { saltAndHashPassword } from "@/utils/password" + +const app = express() +app.use("/auth/*", ExpressAuth({ + providers: [ + Credentials({ + // You can specify which fields should be submitted, by adding keys to the `credentials` object. + // e.g. domain, username, password, 2FA token, etc. + credentials: { + email: {}, + password: {}, + }, + authorize: async (credentials) => { + let user = null + + // logic to salt and hash password + const pwHash = saltAndHashPassword(credentials.password) + + // logic to verify if user exists + user = await getUserFromDb(credentials.email, pwHash) + + if (!user) { + // No user found, so this is their first attempt to login + // meaning this is also the place you could do registration + throw new Error("User not found.") + } + + // return user object with the their profile data + return user + }, + }), + ], +})) +``` + +