Compare commits

...

26 Commits

Author SHA1 Message Date
github-actions
f5da5a5f33 chore(release): bump package version(s) [skip ci] 2022-12-23 04:31:30 +01:00
Balázs Orbán
3b85f46c21 Update release.yml 2022-12-23 04:11:44 +01:00
Balázs Orbán
6aa1af2ffb Update release.yml 2022-12-23 04:11:00 +01:00
Balázs Orbán
9364625681 Update release.yml 2022-12-23 04:09:30 +01:00
Balázs Orbán
1bf2e1d468 Merge branch 'main' of github.com:nextauthjs/next-auth 2022-12-23 03:58:39 +01:00
Balázs Orbán
ac304f17da docs: fix link to sveltekit 2022-12-23 03:58:35 +01:00
Balázs Orbán
3a685b28f8 Update release.yml 2022-12-23 02:56:15 +00:00
Balázs Orbán
5b34b95c58 Update release.yml 2022-12-23 02:42:21 +00:00
Balázs Orbán
a706105205 chore: skip dynamodb as it times out 2022-12-23 03:28:07 +01:00
Balázs Orbán
39c78f27b5 fix(sveltekit): update to latest @auth/core, autogenerate API reference (#6153)
* docs(sveltekit): autogenerate API reference

* feat(sveltekit): update to use latest `@auth/core`

* chore: format

* chore: add auth packages as docs dependency

* chore: format

* chore: more formatting

* chore: don't run build before tests
2022-12-23 02:17:24 +00:00
Balázs Orbán
b179f15cf3 chore: tweak release config 2022-12-23 01:49:04 +01:00
Jordan Calhoun
54561a1231 docs: Typo correction (#6151)
PROT -> PORT
2022-12-22 22:42:56 +00:00
Nico Domino
0ea9ada3a9 chore(docs): remaining authjs.dev and repo clean up (#6097) 2022-12-22 18:04:52 +01:00
Nico Domino
209c368a73 chore(docs): add adapters and providers subdomain redirect in vercel.json (#6146) 2022-12-22 17:40:22 +01:00
Nico Domino
52c5b7cad3 chore(docs): update auth.js og-image (#6145) 2022-12-22 17:36:28 +01:00
Balázs Orbán
b8d83f52b3 chore(examples): attempt to fix gatsby deployment 2022-12-22 05:42:26 +01:00
Balázs Orbán
7dacfbabf0 chore(examples): attempt to fix gatsby deployment 2022-12-22 04:41:20 +01:00
Balázs Orbán
bb372cc5cc docs: main page improvements 2022-12-22 04:05:22 +01:00
Unieveth
c6ca01a99e docs: fix closing tag on oauth-tutorial (#6134)
Fixed wrong closing tag on oauth-tutorial

Changed closing tag on pages/overview.tsx from `</img>` to `</>
2022-12-22 02:37:36 +00:00
Balázs Orbán
6c45abf383 feat(core): improved logging / renames / new exports (#6085)
- Cleans up logging. Logs are now color-coded, added more debug logs, and errors can include some simple metadata (like provider id) to know which provider caused an issue.
- All errors are exposed via `@auth/core/errors`. Each error has a URL like: https://errors.authjs.dev#errorcode in the terminal, which points to the documentation explaining the problem in detail, suggesting a fix.
- Added a bunch of documentation that autogenerates the pages under https://authjs.dev/reference/core/modules/main
- Renames `AuthHandler`  to `Auth` and `AuthOptions` to `AuthConfig`
- Throwing an error in `signIn` callback will now be caught as a general error and will redirect to `/error?error=Configuration`. If the callback returns `false`, it will redirect to `/error?error=AccessDenied`.
2022-12-22 02:36:54 +00:00
Balázs Orbán
2ba5314e35 docs(core): update jwtand types description 2022-12-21 02:05:55 +01:00
Balázs Orbán
582a3c339a refactor(core): move types moduile to top-level 2022-12-21 01:54:49 +01:00
Balázs Orbán
ea23a93442 refactor(core): move jwt to a single file 2022-12-21 01:39:35 +01:00
ndom91
1d67ad41cc chore(docs): add cleanUrls: true 2022-12-19 20:29:08 +01:00
Yahav
7c50b3da98 chore(docs): fix typo in 02-oauth-tutorial.mdx (#6093) 2022-12-19 20:24:55 +01:00
Balázs Orbán
1b2c373fa1 docs: capitalize 2022-12-19 13:39:23 +00:00
154 changed files with 3249 additions and 3114 deletions

View File

@@ -29,7 +29,7 @@ module.exports = {
env: { jest: true },
},
{
files: ["docs"],
files: ["docs/**"],
plugins: ["@docusaurus"],
extends: ["plugin:@docusaurus/recommended"],
},

View File

@@ -29,8 +29,6 @@ jobs:
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm build
- name: Run tests
run: pnpm test
env:
@@ -64,15 +62,11 @@ jobs:
- name: Install dependencies
run: pnpm install
- name: Publish to npm and GitHub
run: |
git config --global user.email "balazsorban44@users.noreply.github.com"
git config --global user.name "Balázs Orbán"
pnpm release
run: pnpm release
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
NPM_TOKEN_PKG: ${{ secrets.NPM_TOKEN_PKG }}
NPM_TOKEN_ORG: ${{ secrets.NPM_TOKEN_ORG }}
GITHUB_TOKEN: ${{ secrets.GH_PAT }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NO_VERIFY: 1
release-pr:
name: Publish PR
runs-on: ubuntu-latest
@@ -100,19 +94,20 @@ jobs:
PR_NUMBER: ${{ github.event.number }}
- name: Publish to npm
run: |
cd packages/next-auth
cd packages/core
echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> .npmrc
pnpm publish --no-git-checks --access public --tag experimental
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN_PKG }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Comment version on PR
uses: NejcZdovc/comment-pr@v2
with:
message:
"🎉 Experimental release [published 📦️ on npm](https://npmjs.com/package/next-auth/v/${{ env.VERSION }})!\n \
```sh\npnpm add next-auth@${{ env.VERSION }}\n```\n \
```sh\nyarn add next-auth@${{ env.VERSION }}\n```\n \
```sh\nnpm i next-auth@${{ env.VERSION }}\n```"
"🎉 Experimental release [published 📦️ on npm](https://npmjs.com/package/@auth/core/v/${{ env.VERSION }})!\n \
```sh\npnpm add @auth/core@${{ env.VERSION }}\n```\n \
```sh\nyarn add @auth/core@${{ env.VERSION }}\n```\n \
```sh\nnpm i @auth/core@${{ env.VERSION }}\n```"
env:
VERSION: ${{ steps.determine-version.outputs.version }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GH_PAT }}

View File

@@ -16,3 +16,4 @@ jobs:
with:
GH_PAT: ${{ secrets.SYNC_EXAMPLE_PAT }}
SKIP_PR: true
ORIGINAL_MESSAGE: true

8
.gitignore vendored
View File

@@ -81,13 +81,13 @@ docs/.docusaurus
docs/providers.json
# Core
packages/core/adapters.*
packages/core/index.*
packages/core/jwt
packages/core/*.js
packages/core/*.d.ts
packages/core/*.d.ts.map
packages/core/lib
packages/core/providers
packages/core/docs
docs/docs/reference/03-core
docs/docs/reference/04-sveltekit
# SvelteKit

View File

@@ -6,10 +6,11 @@ module.exports = {
singleQuote: false,
overrides: [
{
files: "apps/dev/pages/api/auth/[...nextauth].ts",
options: {
printWidth: 150,
},
files: [
"apps/dev/pages/api/auth/[...nextauth].ts",
"docs/{sidebars,docusaurus.config}.js",
],
options: { printWidth: 150 },
},
],
}

View File

@@ -1,6 +1,6 @@
{
"files.exclude": {
"packages/core/{jwt,lib,providers,*.js,*.d.ts*}": true,
"packages/core/{lib,providers,*.js,*.d.ts,*.d.ts.map}": true,
"packages/next-auth/{client,core,css,jwt,next,providers,react,utils,*.js,*.d.ts}": true
},
"typescript.tsdk": "node_modules/typescript/lib",

View File

@@ -1,6 +1,6 @@
ISC License
Copyright (c) 2018-2021, Iain Collins
Copyright (c) 2022-2023, Balázs Orbán
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above

View File

@@ -8,10 +8,10 @@ export default function Footer() {
<hr />
<ul className={styles.navItems}>
<li className={styles.navItem}>
<a href="https://next-auth.js.org">Documentation</a>
<a href="https://authjs.dev">Documentation</a>
</li>
<li className={styles.navItem}>
<a href="https://www.npmjs.com/package/next-auth">NPM</a>
<a href="https://www.npmjs.com/package/@auth/core">NPM</a>
</li>
<li className={styles.navItem}>
<a href="https://github.com/nextauthjs/next-auth-example">GitHub</a>

View File

@@ -1,4 +1,4 @@
import { AuthHandler, type AuthOptions } from "@auth/core"
import { Auth, type AuthConfig } from "@auth/core"
// Providers
import Apple from "@auth/core/providers/apple"
@@ -66,7 +66,7 @@ import WorkOS from "@auth/core/providers/workos"
// secret: process.env.SUPABASE_SERVICE_ROLE_KEY,
// })
export const authOptions: AuthOptions = {
export const authConfig: AuthConfig = {
// adapter,
// debug: process.env.NODE_ENV !== "production",
theme: {
@@ -118,9 +118,10 @@ export const authOptions: AuthOptions = {
Wikimedia({ clientId: process.env.WIKIMEDIA_ID, clientSecret: process.env.WIKIMEDIA_SECRET }),
WorkOS({ clientId: process.env.WORKOS_ID, clientSecret: process.env.WORKOS_SECRET }),
],
// debug: process.env.NODE_ENV !== "production",
}
if (authOptions.adapter) {
if (authConfig.adapter) {
// TODO:
// authOptions.providers.unshift(
// // NOTE: You can start a fake e-mail server with `pnpm email`
@@ -130,25 +131,21 @@ if (authOptions.adapter) {
}
// TODO: move to next-auth/edge
function Auth(...args: any[]) {
function AuthHandler(...args: any[]) {
const envSecret = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET
const envTrustHost = !!(process.env.NEXTAUTH_URL ?? process.env.AUTH_TRUST_HOST ?? process.env.VERCEL ?? process.env.NODE_ENV !== "production")
if (args.length === 1) {
return async (req: Request) => {
args[0].secret ??= envSecret
args[0].trustHost ??= envTrustHost
return await AuthHandler(req, args[0])
return Auth(req, args[0])
}
}
args[1].secret ??= envSecret
args[1].trustHost ??= envTrustHost
return AuthHandler(args[0], args[1])
return Auth(args[0], args[1])
}
// export default Auth(authOptions)
export default function handle(request: Request) {
return Auth(request, authOptions)
}
export default AuthHandler(authConfig)
export const config = { runtime: "experimental-edge" }

View File

@@ -5,7 +5,8 @@ export default function Page () {
<Layout>
<h1>NextAuth.js Example</h1>
<p>
This is an example site to demonstrate how to use <a href='https://next-auth.js.org'>NextAuth.js</a> for authentication.
This is an example site to demonstrate how to use{' '}
<a href="https://authjs.dev">NextAuth.js</a> for authentication.
</p>
</Layout>
)

View File

@@ -1,29 +1,31 @@
import Layout from '../components/layout'
import Layout from "../components/layout"
export default function Page () {
export default function Page() {
return (
<Layout>
<p>
This is an example site to demonstrate how to use <a href='https://next-auth.js.org'>NextAuth.js</a> for authentication.
This is an example site to demonstrate how to use{" "}
<a href="https://authjs.dev">Auth.js</a> for authentication.
</p>
<h2>Terms of Service</h2>
<p>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</p>
<h2>Privacy Policy</h2>
<p>
This site uses JSON Web Tokens and an in-memory database which resets every ~2 hours.
This site uses JSON Web Tokens and an in-memory database which resets
every ~2 hours.
</p>
<p>
Data provided to this site is exclusively used to support signing in
and is not passed to any third party services, other than via SMTP or OAuth for the
purposes of authentication.
Data provided to this site is exclusively used to support signing in and
is not passed to any third party services, other than via SMTP or OAuth
for the purposes of authentication.
</p>
</Layout>
)

View File

@@ -2,7 +2,7 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img width="150px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>
<a href="https://authjs.dev" target="_blank"><img width="150px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>
<h3 align="center">Auth.js Example App with <a href="https://kit.svelte.dev">SvelteKit</a></h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -25,4 +25,4 @@
# Documentation
- [sveltekit.authjs.dev](https://sveltekit.authjs.dev)
- [sveltekit.authjs.dev](https://sveltekit.authjs.dev)

View File

@@ -1,40 +1,40 @@
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/example-gatsby). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
> The example repository is maintained from a [monorepo](https://github.com/nextauthjs/next-auth/tree/main/apps/playground-gatsby). Pull Requests should be opened against [`nextauthjs/next-auth`](https://github.com/nextauthjs/next-auth).
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img width="150px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>
<h3 align="center">NextAuth.js Example App</h3>
<a href="https://authjs.dev" target="_blank"><img width="150px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>
<h3 align="center">Auth.js Example App</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
<p align="center" style="align: center;">
<a href="https://npm.im/next-auth">
<img alt="npm" src="https://img.shields.io/npm/v/next-auth?color=green&label=next-auth&style=flat-square">
<img alt="npm" src="https://img.shields.io/npm/v/@auth/core?color=green&label=@auth/core&style=flat-square">
</a>
<a href="https://bundlephobia.com/result?p=next-auth-example">
<img src="https://img.shields.io/bundlephobia/minzip/next-auth?label=bundle&style=flat-square" alt="Bundle Size"/>
<a href="https://bundlephobia.com/result?p=@auth/core">
<img src="https://img.shields.io/bundlephobia/minzip/@auth/core?label=bundle&style=flat-square" alt="Bundle Size"/>
</a>
<a href="https://www.npmtrends.com/next-auth">
<img src="https://img.shields.io/npm/dm/next-auth?label=20downloads&style=flat-square" alt="Downloads" />
<a href="https://www.npmtrends.com/@auth/core">
<img src="https://img.shields.io/npm/dm/@auth/core?label=downloads&style=flat-square" alt="Downloads" />
</a>
</p>
</p>
## Overview
NextAuth.js is a complete open source authentication solution.
Auth.js is a complete open source authentication solution.
This is an example application that shows how `next-auth` is applied to a basic Gatsby app. We are showing how to configure the backend both as a [Vercel Function](https://vercel.com/docs/concepts/functions/introduction) for deployment to Vercel, and also for [Gatsby Functions](https://www.gatsbyjs.com/docs/reference/functions) for other platforms.
This is an example application that shows how `@auth/core` is applied to a basic Gatsby app. We are showing how to configure the backend both as a [Vercel Function](https://vercel.com/docs/concepts/functions/introduction) for deployment to Vercel, and also for [Gatsby Functions](https://www.gatsbyjs.com/docs/reference/functions) for other platforms.
The deployed version can be found at [`next-auth-gatsby-example.vercel.app`](https://next-auth-gatsby-example.vercel.app)
### About NextAuth.js
### About Auth.js
NextAuth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for [Next.js](https://nextjs.org) and [Serverless](https://vercel.com), but this example shows how to use it in a Gatsby project. Our goal is to [support even more frameworks](https://github.com/nextauthjs/next-auth/issues/2294) in the future.
Auth.js is an easy to implement, full-stack (client/server) open source authentication library originally designed for [Next.js](https://nextjs.org) and [Serverless](https://vercel.com), but this example shows how to use it in a Gatsby project. Our goal is to [support even more frameworks](https://github.com/nextauthjs/next-auth/issues/2294) in the future.
Go to [next-auth.js.org](https://next-auth.js.org) for more information and documentation.
Go to [authjs.dev](https://authjs.dev) for more information and documentation.
> *NextAuth.js is not officially associated with Vercel or Next.js.*
> Auth.js is not officially associated with Vercel or Next.js._
## Getting Started
@@ -58,13 +58,13 @@ Add details for one or more providers (e.g. Google, Twitter, GitHub, Email, etc)
#### Database
A database is needed to persist user accounts and to support email sign in. However, you can still use NextAuth.js for authentication without a database by using OAuth for authentication. If you do not specify a database, [JSON Web Tokens](https://jwt.io/introduction) will be enabled by default.
A database is needed to persist user accounts and to support email sign in. However, you can still use Auth.js for authentication without a database by using OAuth for authentication. If you do not specify a database, [JSON Web Tokens](https://jwt.io/introduction) will be enabled by default.
You **can** skip configuring a database and come back to it later if you want.
For more information about setting up a database, please check out the following links:
* Docs: [next-auth.js.org/adapters/overview](https://next-auth.js.org/adapters/overview)
- Docs: [authjs.dev/reference/adapters/overview](https://authjs.dev/reference/adapters/overview)
### 3. Configure Authentication Providers
@@ -72,9 +72,9 @@ For more information about setting up a database, please check out the following
2. When setting up OAuth, in the developer admin page for each of your OAuth services, you should configure the callback URL to use a callback path of `{server}/api/auth/callback/{provider}`.
e.g. For Google OAuth you would use: `http://localhost:3000/api/auth/callback/google`
e.g. For Google OAuth you would use: `http://localhost:3000/api/auth/callback/google`
A list of configured providers and their callback URLs is available from the endpoint `/api/auth/providers`. You can find more information at https://next-auth.js.org/configuration/providers/oauth
A list of configured providers and their callback URLs is available from the endpoint `/api/auth/providers`. You can find more information at [authjs.dev/reference/providers/oauth-builtin](https://authjs.dev/reference/providers/oauth-builtin).
3. You can also choose to specify an SMTP server for passwordless sign in via email.
@@ -95,16 +95,15 @@ npm run start
### 5. Preparing for Production
Follow the [Deployment documentation](https://next-auth.js.org/deployment)
Follow the [Deployment documentation](https://authjs.dev/guides/basics/deployment)
## Acknowledgements
<a href="https://vercel.com?utm_source=nextauthjs&utm_campaign=oss">
<img width="170px" src="https://raw.githubusercontent.com/nextauthjs/next-auth/canary/www/static/img/powered-by-vercel.svg" alt="Powered By Vercel" />
<a href="https://vercel.com?utm_source=authjs&utm_campaign=oss">
<img width="170px" src="https://powered-by-vercel.api.soraharu.com/powered-by-vercel.svg" alt="Powered By Vercel" />
</a>
<p align="left">Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire NextAuth.js Team</p>
<p align="left">Thanks to Vercel sponsoring this project by allowing it to be deployed for free for the entire Auth.js Team</p>
## License
ISC

View File

@@ -1,5 +1,5 @@
// Gatsby Functions are not yet supported on Vercel, so you'll need to use the root `api` folder.
import NextAuth from "next-auth/next"
import NextAuth from "next-auth"
import { authConfig } from "../../nextauth.config"
export default async function handler(req, res) {

View File

@@ -1,6 +1,6 @@
// If your deployment environment supports Gatsby Functions, you won't need the root `api` folder, only this.
import NextAuth from "next-auth/next"
import NextAuth from "next-auth"
import { authConfig } from "../../nextauth.config"
export default async function handler(req, res) {

View File

@@ -11,8 +11,7 @@ export default function Home() {
<h1>NextAuth.js Example</h1>
<p>
An example site to demonstrate how to use{" "}
<a href="https://next-auth.js.org">NextAuth.js</a> for authentication in
Gatsby.
<a href="https://authjs.dev">Auth.js</a> for authentication in Gatsby.
</p>
{
{

1
docs/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.vercel

View File

@@ -1,7 +1,7 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img width="150px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>
<h3 align="center">NextAuth.js</h3>
<a href="https://authjs.dev" target="_blank"><img width="150px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>
<h3 align="center">Auth.js</h3>
<p align="center">Authentication for Next.js</p>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -10,16 +10,16 @@
<a href="https://github.com/nextauthjs/next-auth/actions/workflows/release.yml?query=workflow%3ARelease">
<img src="https://github.com/nextauthjs/next-auth/actions/workflows/release.yml/badge.svg" alt="Release" />
</a>
<a href="https://packagephobia.com/result?p=next-auth">
<img src="https://packagephobia.com/badge?p=next-auth" alt="Bundle Size"/>
<a href="https://packagephobia.com/result?p=@auth/core">
<img src="https://packagephobia.com/badge?p=@auth/core" alt="Bundle Size"/>
</a>
<a href="https://www.npmtrends.com/next-auth">
<img src="https://img.shields.io/npm/dm/next-auth" alt="Downloads" />
<a href="https://www.npmtrends.com/@auth/core">
<img src="https://img.shields.io/npm/dm/@auth/core" alt="Downloads" />
</a>
<a href="https://github.com/nextauthjs/next-auth/stargazers">
<img src="https://img.shields.io/github/stars/nextauthjs/next-auth" alt="Github Stars" />
</a>
<a href="https://www.npmjs.com/package/next-auth">
<a href="https://www.npmjs.com/package/@auth/core">
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?label=latest" alt="Github Stable Release" />
</a>
</p>
@@ -27,7 +27,7 @@
## Overview
This is the repository for the documentation page for NextAuth.js!
This is the repository for the documentation page for Auth.js!
NextAuth.js is a complete open source authentication solution for [Next.js](http://nextjs.org/) applications.

View File

@@ -0,0 +1,5 @@
{
"label": "Concepts",
"collapsible": true,
"collapsed": true
}

View File

@@ -1,5 +1,6 @@
---
title: Contributors
displayed_sidebar: null
---
## Core team

View File

@@ -1,5 +1,6 @@
---
title: Introduction
sidebar_position: 0
---
## About Auth.js

View File

@@ -47,7 +47,7 @@ Behind the scenes this creates all the relevant OAuth API routes within `/api/au
- `/api/auth/callback`
- `/api/auth/signIn`
- `/api/auth/singOut`
- `/api/auth/signOut`
- etc...
can be handled by Auth.js. In this way, Auth.js stays in charge of handling the whole authentication request/response flow of your application for you.
@@ -112,7 +112,7 @@ export default function CamperVanPage() {
<p>Signed in as {userEmail}</p>
<button onClick={() => signOut()}>Sign out</button>
<img src="https://cdn.pixabay.com/photo/2017/08/11/19/36/vw-2632486_1280.png" />
</img>
</>
)
}

View File

@@ -56,7 +56,7 @@ Next, as [per Sendgrid documentation](https://docs.sendgrid.com/for-developers/s
SMTP_USER=apikey
SMTP_PASSWORD={API_KEY}
SMTP_HOST=smtp.sendgrid.net
SMTP_PROT=587
SMTP_PORT=587
EMAIL_FROM={SENDER_EMAIL}
```

View File

@@ -269,7 +269,7 @@ The `session.jwt: boolean` option has been renamed to `session.strategy: "jwt" |
1. No adapter, `strategy: "jwt"`: This is the default. The session is saved in a cookie and never persisted anywhere.
2. With Adapter, `strategy: "database"`: If an Adapter is defined, this will be the implicit setting. No user config is needed.
3. With Adapter, `strategy: "jwt"`: The user can explicitly instruct `next-auth` to use JWT even if a database is available. This can result in faster lookups in compromise of lowered security. Read more about: https://next-auth.js.org/faq#json-web-tokens
3. With Adapter, `strategy: "jwt"`: The user can explicitly instruct `next-auth` to use JWT even if a database is available. This can result in faster lookups in compromise of lowered security. Read more about: https://authjs.dev/concepts/faq#json-web-tokens
Example:

View File

@@ -0,0 +1,5 @@
{
"label": "Getting Started",
"collapsible": true,
"collapsed": true
}

View File

@@ -12,7 +12,7 @@ A working example can be accessed [here](https://github.com/nextauthjs/next-auth
### Server Side
Using a [JWT callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) and a [session callback](https://next-auth.js.org/configuration/callbacks#session-callback), we can persist OAuth tokens and refresh them when they expire.
Using a [JWT callback](https://authjs.dev/guides/basics/callbacks#jwt-callback) and a [session callback](https://authjs.dev/guides/basics/callbacks#session-callback), we can persist OAuth tokens and refresh them when they expire.
Below is a sample implementation using Google's Identity Provider. Please note that the OAuth 2.0 request in the `refreshAccessToken()` function will vary between different providers, but the core logic should remain similar.

View File

@@ -104,7 +104,7 @@ This tutorial covers:
#### [Using Auth.js with Magic links](https://dev.to/narciero/using-nextauth-js-with-magic-links-df4) <svg style={{ marginLeft: '5px', marginBottom:'-6px'}} width="30" height="25" viewBox="0 0 50 40" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="50" height="40" rx="3" style={{ fill: '#000' }}></rect><path d="M19.099 23.508c0 1.31-.423 2.388-1.27 3.234-.838.839-1.942 1.258-3.312 1.258h-4.403V12.277h4.492c1.31 0 2.385.423 3.224 1.27.846.838 1.269 1.912 1.269 3.223v6.738zm-2.808 0V16.77c0-.562-.187-.981-.562-1.258-.374-.285-.748-.427-1.122-.427h-1.685v10.107h1.684c.375 0 .75-.138 1.123-.415.375-.285.562-.708.562-1.27zM28.185 28h-5.896c-.562 0-1.03-.187-1.404-.561-.375-.375-.562-.843-.562-1.404V14.243c0-.562.187-1.03.562-1.404.374-.375.842-.562 1.404-.562h5.896v2.808H23.13v3.65h3.088v2.808h-3.088v3.65h5.054V28zm7.12 0c-.936 0-1.684-.655-2.246-1.965l-3.65-13.758h3.089l2.807 10.804 2.808-10.804H41.2l-3.65 13.758C36.99 27.345 36.241 28 35.305 28z" style={{ fill: '#fff' }}></path></svg>
- Learn how to use [Magic.Link](https://magic.link) authentication with [Auth.js](https://next-auth.js.org) to enable passwordless authentication without a database.
- Learn how to use [Magic.Link](https://magic.link) authentication with [Auth.js](https://authjs.dev) to enable passwordless authentication without a database.
## Database

View File

@@ -1,5 +1,7 @@
---
title: Overview
sidebar_label: Guides
sidebar_position: 0
---
We're creating internal guides to help understand how to use Auth.js and all the possible configurations and uses cases it supports.

View File

@@ -1,60 +0,0 @@
---
title: SvelteKit Auth
---
:::warning
`@auth/sveltekit` is currently experimental.
:::
## Installation
```bash npm2yarn2pnpm
npm install @auth/core @auth/sveltekit
```
## Usage
Learn more about `@auth/sveltekit` [here](https://vercel.com/blog/announcing-sveltekit-auth)
```ts title="src/hooks.server.ts"
import SvelteKitAuth from "@auth/sveltekit"
import GitHub from "@auth/core/providers/github"
import { GITHUB_ID, GITHUB_SECRET } from "$env/static/private"
export const handle = SvelteKitAuth({
providers: [GitHub({ clientId: GITHUB_ID, clientSecret: GITHUB_SECRET })],
})
```
Don't forget to set the `AUTH_SECRET` [environment variable](https://kit.svelte.dev/docs/modules#$env-static-private). This should be a random 32 character string. On unix systems you can use `openssl rand -hex 32` or check out `https://generate-secret.vercel.app/32`.
When deploying your app outside Vercel, set the `AUTH_TRUST_HOST` variable to `true` for other hosting providers like Cloudflare Pages or Netlify.
## Signing in and signing out
```ts
<script>
import { signIn, signOut } from "@auth/sveltekit/client"
import { page } from "$app/stores"
</script>
<h1>SvelteKit Auth Example</h1>
<p>
{#if $page.data.session}
{#if $page.data.session.user?.image}
<span
style="background-image: url('{$page.data.session.user.image}')"
class="avatar"
/>
{/if}
<span class="signedInText">
<small>Signed in as</small><br />
<strong>{$page.data.session.user?.name ?? "User"}</strong>
</span>
<button on:click={() => signOut()} class="button">Sign out</button>
{:else}
<span class="notSignedInText">You are not signed in</span>
<button on:click={() => signIn("github")}>Sign In with GitHub</button>
{/if}
</p>
```

View File

@@ -190,4 +190,4 @@ An advanced option, hopefully you won't need it in most cases. `next-auth` uses
### `allowDangerousEmailAccountLinking` option
Normally, when you sign in with an OAuth provider and another account with the same email address already exists, the accounts are not linked automatically. Automatic account linking on sign in is not secure between arbitrary providers and is disabled by default (see our [Security FAQ](https://next-auth.js.org/faq#security)). However, it may be desirable to allow automatic account linking if you trust that the provider involved has securely verified the email address associated with the account. Just set `allowDangerousEmailAccountLinking: true` in your provider configuration to enable automatic account linking.
Normally, when you sign in with an OAuth provider and another account with the same email address already exists, the accounts are not linked automatically. Automatic account linking on sign in is not secure between arbitrary providers and is disabled by default (see our [Security FAQ](https://authjs.dev/reference/faq#security)). However, it may be desirable to allow automatic account linking if you trust that the provider involved has securely verified the email address associated with the account. Just set `allowDangerousEmailAccountLinking: true` in your provider configuration to enable automatic account linking.

View File

@@ -1,5 +1,5 @@
{
"label": "OAuth providers",
"label": "OAuth Providers",
"collapsible": true,
"collapsed": true
}

View File

@@ -38,7 +38,7 @@ AZURE_AD_TENANT_ID=<copy the tenant id here>
That will default the tenant to use the `common` authorization endpoint. [For more details see here](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints).
:::note
Azure AD returns the profile picture in an ArrayBuffer, instead of just a URL to the image, so our provider converts it to a base64 encoded image string and returns that instead. See: https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0#examples. The default image size is 48x48 to avoid [running out of space](https://next-auth.js.org/faq#:~:text=What%20are%20the%20disadvantages%20of%20JSON%20Web%20Tokens%3F) in case the session is saved as a JWT.
Azure AD returns the profile picture in an ArrayBuffer, instead of just a URL to the image, so our provider converts it to a base64 encoded image string and returns that instead. See: https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0#examples. The default image size is 48x48 to avoid [running out of space](https://authjs.dev/concepts/faq#:~:text=What%20are%20the%20disadvantages%20of%20JSON%20Web%20Tokens%3F) in case the session is saved as a JWT.
:::
In `pages/api/auth/[...nextauth].js` find or add the `AzureAD` entries:

View File

@@ -2,9 +2,6 @@
title: Database Adapters
---
:::warning WIP
`@auth/*-adapter` is work in progress. for the time being, please go to [NextAuth.js Adapters](https://next-auth.js.org/adapters/overview).
:::

View File

@@ -7,42 +7,42 @@ Auth.js can be used with any database. Models tell you what structures Auth.js e
```mermaid
erDiagram
User ||--|{ Account : ""
User {
string id
string name
string email
timestamp emailVerified
string image
}
User ||--|{ Session : ""
Session {
string id
timestamp expires
string sessionToken
string userId
}
Account {
string id
string userId
string type
string provider
string providerAccountId
string refresh_token
string access_token
int expires_at
string token_type
string scope
string id_token
string session_state
string oauth_token_secret
string oauth_token
}
VerificationToken {
string identifier
string token
timestamp expires
}
User ||--|{ Account : ""
User {
string id
string name
string email
timestamp emailVerified
string image
}
User ||--|{ Session : ""
Session {
string id
timestamp expires
string sessionToken
string userId
}
Account {
string id
string userId
string type
string provider
string providerAccountId
string refresh_token
string access_token
int expires_at
string token_type
string scope
string id_token
string session_state
string oauth_token_secret
string oauth_token
}
VerificationToken {
string identifier
string token
timestamp expires
}
```
More information about each Model / Table can be found below.

View File

@@ -3,7 +3,7 @@ id: dgraph
title: Dgraph
---
This is the Dgraph Adapter for [`next-auth`](https://next-auth.js.org).
This is the Dgraph Adapter for [`next-auth`](https://authjs.dev).
## Getting Started
@@ -20,9 +20,9 @@ import NextAuth from "next-auth"
import { DgraphAdapter } from "@next-auth/dgraph-adapter"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/provideres/oauth-builtin
providers: [],
adapter: DgraphAdapter({
endpoint: process.env.DGRAPH_GRAPHQL_ENDPOINT,

View File

@@ -3,9 +3,9 @@ id: fauna
title: FaunaDB
---
This is the Fauna Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Fauna Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
You can find the Fauna schema and seed information in the docs at [next-auth.js.org/adapters/fauna](https://next-auth.js.org/adapters/fauna).
You can find the Fauna schema and seed information in the docs at [authjs.dev/reference/adapters/fauna](https://authjs.dev/reference/adapters/fauna).
## Getting Started
@@ -30,9 +30,9 @@ const client = new FaunaClient({
})
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/providers/overview
// https://authjs.dev/reference/providers/
providers: [],
adapter: FaunaAdapter(client)
...

View File

@@ -7,7 +7,7 @@ title: Firebase
This adapter is still experimental and does not work with Auth.js 4 or newer. If you would like to help out upgrading it, please visit [this PR](https://github.com/nextauthjs/next-auth/pull/3873)
:::
This is the Firebase Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Firebase Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
## Getting Started
@@ -32,9 +32,9 @@ const firestore = (
).firestore()
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/providers/overview
// https://authjs.dev/reference/providers/
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,

View File

@@ -56,7 +56,7 @@ import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "../../../lib/mongodb"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/providers/oauth
export default NextAuth({
adapter: MongoDBAdapter(clientPromise),
...

View File

@@ -3,7 +3,7 @@ id: neo4j
title: Neo4j
---
This is the Neo4j Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Neo4j Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
## Getting Started
@@ -27,9 +27,9 @@ const driver = neo4j.driver(
const neo4jSession = driver.session()
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: Neo4jAdapter(neo4jSession),
...

View File

@@ -7,7 +7,7 @@ title: PouchDB
This adapter is still experimental and does not work with Auth.js 4 or newer. If you would like to help out upgrading it, please [open a PR](https://github.com/nextauthjs/next-auth/tree/main/packages)
:::
This is the PouchDB Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the PouchDB Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
Depending on your architecture you can use PouchDB's http adapter to reach any database compliant with the CouchDB protocol (CouchDB, Cloudant, ...) or use any other PouchDB compatible adapter (leveldb, in-memory, ...)
@@ -36,9 +36,9 @@ PouchDB.plugin(require("pouchdb-adapter-leveldb")) // Any other adapter
const pouchdb = new PouchDB("auth_db", { adapter: "leveldb" })
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/providers/overview
// https://authjs.dev/reference/providers/
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,

View File

@@ -3,7 +3,7 @@ id: sequelize
title: Sequelize
---
This is the Sequelize Adapter for [`next-auth`](https://next-auth.js.org).
This is the Sequelize Adapter for [`next-auth`](https://authjs.dev).
## Getting Started
@@ -28,9 +28,9 @@ import { Sequelize } from "sequelize"
const sequelize = new Sequelize("yourconnectionstring")
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-config
export default NextAuth({
// https://next-auth.js.org/providers/overview
// https://authjs.dev/reference/providers/
providers: [],
adapter: SequelizeAdapter(sequelize),
})
@@ -38,7 +38,7 @@ export default NextAuth({
## Updating the database schema
By default, the sequelize adapter will not create tables in your database. In production, best practice is to create the [required tables](https://next-auth.js.org/adapters/models) in your database via [migrations](https://sequelize.org/master/manual/migrations.html). In development, you are able to call [`sequelize.sync()`](https://sequelize.org/master/manual/model-basics.html#model-synchronization) to have sequelize create the necessary tables, foreign keys and indexes:
By default, the sequelize adapter will not create tables in your database. In production, best practice is to create the [required tables](https://authjs.dev/reference/adapters/models) in your database via [migrations](https://sequelize.org/master/manual/migrations.html). In development, you are able to call [`sequelize.sync()`](https://sequelize.org/master/manual/model-basics.html#model-synchronization) to have sequelize create the necessary tables, foreign keys and indexes:
> This schema is adapted for use in Sequelize and based upon our main [schema](/reference/adapters/models)
@@ -72,7 +72,7 @@ import Sequelize, { DataTypes } from "sequelize"
const sequelize = new Sequelize("sqlite::memory:")
export default NextAuth({
// https://next-auth.js.org/providers/overview
// https://authjs.dev/reference/providers/
providers: [],
adapter: SequelizeAdapter(sequelize, {
models: {

View File

@@ -5,12 +5,12 @@ title: Supabase
# Supabase
This is the Supabase Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Supabase Adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
:::note
This adapter is developed by the community and not officially maintained or supported by Supabase. It uses the Supabase Database to store user and session data in a separate `next_auth` schema. It is a standalone Auth server that does not interface with Supabase Auth and therefore provides a different feature set.
If youre looking for an officially maintained Auth server with additional features like [built-in email server](https://supabase.com/docs/guides/auth/auth-email#configure-email-settings?utm_source=next-auth-docs&medium=referral&campaign=next-auth), [phone auth](https://supabase.com/docs/guides/auth/auth-twilio?utm_source=next-auth-docs&medium=referral&campaign=next-auth), and [Multi Factor Authentication (MFA / 2FA)](https://supabase.com/contact/mfa?utm_source=next-auth-docs&medium=referral&campaign=next-auth), please use [Supabase Auth](https://supabase.com/auth) with the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs?utm_source=next-auth-docs&medium=referral&campaign=next-auth).
If youre looking for an officially maintained Auth server with additional features like [built-in email server](https://supabase.com/docs/guides/auth/auth-email#configure-email-settings?utm_source=authjs-docs&medium=referral&campaign=authjs), [phone auth](https://supabase.com/docs/guides/auth/auth-twilio?utm_source=authjs-docs&medium=referral&campaign=authjs), and [Multi Factor Authentication (MFA / 2FA)](https://supabase.com/contact/mfa?utm_source=authjs-docs&medium=referral&campaign=authjs), please use [Supabase Auth](https://supabase.com/auth) with the [Auth Helpers for Next.js](https://supabase.com/docs/guides/auth/auth-helpers/nextjs?utm_source=authjs-docs&medium=referral&campaign=authjs).
:::
## Getting Started
@@ -28,9 +28,9 @@ import NextAuth from "next-auth"
import { SupabaseAdapter } from "@next-auth/supabase-adapter"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-config
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [...],
adapter: SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
@@ -46,7 +46,7 @@ export default NextAuth({
Setup your database as described in our main [schema](/reference/adapters/models), by copying the SQL schema below in the Supabase [SQL Editor](https://app.supabase.com/project/_/sql).
Alternatively you can select the NextAuth Quickstart card on the [SQL Editor page](https://app.supabase.com/project/_/sql), or [create a migration with the Supabase CLI](https://supabase.com/docs/guides/cli/local-development#database-migrations?utm_source=next-auth-docs&medium=referral&campaign=next-auth).
Alternatively you can select the NextAuth Quickstart card on the [SQL Editor page](https://app.supabase.com/project/_/sql), or [create a migration with the Supabase CLI](https://supabase.com/docs/guides/cli/local-development#database-migrations?utm_source=authjs-docs&medium=referral&campaign=authjs).
```sql
--
@@ -156,13 +156,13 @@ GRANT ALL ON TABLE next_auth.verification_tokens TO service_role;
Expose the `next_auth` schema via the Serverless API in the [API settings](https://app.supabase.com/project/_/settings/api) by adding `next_auth` to the "Exposed schemas" list.
When developing locally add `next_auth` to the `schemas` array in the `config.toml` file in the `supabase` folder that was generated by the [Supabase CLI](https://supabase.com/docs/guides/cli/local-development#initialize-your-project?utm_source=next-auth-docs&medium=referral&campaign=next-auth).
When developing locally add `next_auth` to the `schemas` array in the `config.toml` file in the `supabase` folder that was generated by the [Supabase CLI](https://supabase.com/docs/guides/cli/local-development#initialize-your-project?utm_source=authjs-docs&medium=referral&campaign=authjs).
## Enabling Row Level Security (RLS)
Postgres provides a powerful feature called [Row Level Security (RLS)](https://supabase.com/docs/guides/auth/row-level-security?utm_source=next-auth-docs&medium=referral&campaign=next-auth) to limit access to data.
Postgres provides a powerful feature called [Row Level Security (RLS)](https://supabase.com/docs/guides/auth/row-level-security?utm_source=authjs-docs&medium=referral&campaign=authjs) to limit access to data.
This works by sending a signed JWT to your [Supabase Serverless API](https://supabase.com/docs/guides/api?utm_source=next-auth-docs&medium=referral&campaign=next-auth). There is two steps to make this work with NextAuth:
This works by sending a signed JWT to your [Supabase Serverless API](https://supabase.com/docs/guides/api?utm_source=authjs-docs&medium=referral&campaign=authjs). There is two steps to make this work with NextAuth:
### 1. Generate the Supabase `access_token` JWT in the session callback
@@ -182,9 +182,9 @@ import { SupabaseAdapter } from "@next-auth/supabase-adapter"
import jwt from "jsonwebtoken"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [...],
adapter: SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL,

View File

@@ -1,173 +0,0 @@
---
id: errors
title: Errors
---
This is a list of errors output from Auth.js.
All errors indicate an unexpected problem, you should not expect to see errors.
If you are seeing any of these errors in the console, something is wrong.
---
## Client
These errors are returned from the client. As the client is [Universal JavaScript (or "Isomorphic JavaScript")](https://en.wikipedia.org/wiki/Isomorphic_JavaScript) it can be run on the client or server, so these errors can occur both in the terminal and in the browser console.
#### `CLIENT_SESSION_ERROR`
This error occurs when the `SessionProvider` Context has a problem fetching session data.
#### `CLIENT_FETCH_ERROR`
If you see `CLIENT_FETCH_ERROR` make sure you have configured the `NEXTAUTH_URL` environment variable.
---
## Server
These errors are displayed on the terminal.
### OAuth
#### `OAUTH_GET_ACCESS_TOKEN_ERROR`
This occurs when there was an error in the POST request to the OAuth provider and we were not able to retrieve the access token.
Please double check your provider settings.
#### `OAUTH_V1_GET_ACCESS_TOKEN_ERROR`
This error is explicitly related to older OAuth v1.x providers, if you are using one of these, please double check all available settings.
#### `OAUTH_GET_PROFILE_ERROR`
N/A
#### `OAUTH_PARSE_PROFILE_ERROR`
This error is a result of either a problem with the provider response or the user canceling the action with the provider, unfortunately, we can't discern which with the information we have.
This error should also log the exception and available `profileData` to further aid debugging.
#### `OAUTH_CALLBACK_HANDLER_ERROR`
This error will occur when there was an issue parsing the JSON request body, for example.
There should also be further details logged when this occurs, such as the error is thrown, and the request body itself to aid in debugging.
---
### Signin / Callback
#### `GET_AUTHORIZATION_URL_ERROR`
This error can occur when we cannot get the OAuth v1 request token and generate the authorization URL.
Please double check your OAuth v1 provider settings, especially the OAuth token and OAuth token secret.
#### `SIGNIN_OAUTH_ERROR`
This error can occur in one of a few places, first during the redirect to the authorization URL of the provider. Next, in the signin flow while creating the PKCE code verifier. Finally, during the generation of the CSRF Token hash in the internal state during signin.
Please check your OAuth provider settings and make sure your URLs and other options are correctly set on the provider side.
#### `CALLBACK_OAUTH_ERROR`
This can occur during the handling of the callback if the `code_verifier` cookie was not found or an invalid state was returned from the OAuth provider.
#### `SIGNIN_EMAIL_ERROR`
This error can occur when a user tries to sign in via an email link; for example, if the email token could not be generated or the verification request failed.
Please double check your email settings.
#### `CALLBACK_EMAIL_ERROR`
This can occur during the email callback process. Specifically, if there was an error signing the user in via email, encoding the jwt, etc.
Please double check your Email settings.
#### `EMAIL_REQUIRES_ADAPTER_ERROR`
The Email authentication provider can only be used if a database is configured.
This is required to store the verification token. Please see the [Email provider tutorial](/getting-started/email-tutorial) for more details.
#### `CALLBACK_CREDENTIALS_JWT_ERROR`
The Credentials Provider can only be used if JSON Web Tokens are used for sessions.
JSON Web Tokens are used for Sessions by default if you have not specified a database. However, if you are using a database, then Database Sessions are enabled by default and you need to [explicitly enable JWT Sessions](/reference/configuration/auth-config#session) to use the Credentials Provider.
If you are using a Credentials Provider, Auth.js will not persist users or sessions in a database - user accounts used with the Credentials Provider must be created and managed outside of Auth.js.
In _most cases_ it does not make sense to specify a database in Auth.js options and support a Credentials Provider.
#### `CALLBACK_CREDENTIALS_HANDLER_ERROR`
This error occurs when there was no `authorize()` handler defined on the credential authentication provider.
#### `PKCE_ERROR`
The provider you tried to use failed when setting [PKCE or Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636#section-4).
The `code_verifier` is saved in a cookie called (by default) `__Secure-next-auth.pkce.code_verifier` which expires after 15 minutes.
Check if `cookies.pkceCodeVerifier` is configured correctly.
The default `code_challenge_method` is `"S256"`. This is currently not configurable to `"plain"`, [as per RFC7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2):
> If the client is capable of using "S256", it MUST use "S256", as
> S256" is Mandatory To Implement (MTI) on the server.
#### `INVALID_CALLBACK_URL_ERROR`
The `callbackUrl` provided was either invalid or not defined. See [specifying a `callbackUrl`](/reference/utilities/#specifying-a-callbackurl) for more information.
---
### Session Handling
#### `JWT_SESSION_ERROR`
JWKKeySupport: the key does not support HS512 verify algorithm
The algorithm used for generating your key isn't listed as supported. You can generate a HS512 key using
```
jose newkey -s 512 -t oct -a HS512
```
#### `SESSION_ERROR`
---
### Signout
#### `SIGNOUT_ERROR`
This error occurs when there was an issue deleting the session from the database, for example.
---
### Other
#### `SEND_VERIFICATION_EMAIL_ERROR`
This error occurs when the Email Authentication Provider is unable to send an email.
Check your mail server configuration.
#### `MISSING_NEXTAUTH_API_ROUTE_ERROR`
This error happens when `[...nextauth].js` file is not found inside `pages/api/auth`.
Make sure the file is there and the filename is written correctly.
#### `NO_SECRET`
In production, we expect you to define a `secret` property in your configuration. In development, this is shown as a warning for convenience. [Read more](/reference/configuration/auth-config#secret)
#### `oauth_callback_error expected 200 OK with body but no body was returned`
This error might happen with some of the providers. It happens due to `openid-client`(which is peer dependency) node version mismatch. For instance, `openid-client` requires `>=14.2.0` for `lts/fermium` and has similar limits for the other versions. For the full list of the compatible node versions please see [package.json](https://github.com/panva/node-openid-client/blob/2a84e46992e1ebeaf685c3f87b65663d126e81aa/package.json#L78)

View File

@@ -27,11 +27,11 @@ These warnings are displayed on the terminal.
#### NO_SECRET
In development, we generate a `secret` based on your configuration for convenience. This is volatile and will throw an error in production. [Read more](https://next-auth.js.org/configuration/options#secret)
In development, we generate a `secret` based on your configuration for convenience. This is volatile and will throw an error in production. [Read more](https://authjs.dev/reference/configuration/auth-config/#secret)
#### TWITTER_OAUTH_2_BETA
Twitter OAuth 2.0 is currently in beta as certain changes might still be necessary. This is not covered by semver. See the docs https://next-auth.js.org/providers/twitter#oauth-2
Twitter OAuth 2.0 is currently in beta as certain changes might still be necessary. This is not covered by semver. See the docs https://authjs.dev/reference/providers/twitter#oauth-2
#### EXPERIMENTAL_API

View File

@@ -1,5 +1,7 @@
---
title: Overview
sidebar_label: Overview
sidebar_position: 0
---
## Core
@@ -20,4 +22,4 @@ title: Overview
- Remix
- Nuxt
- Gatsby
- etc.
- etc.

View File

@@ -1,18 +1,28 @@
const fs = require("fs")
const path = require("path")
// list providers entries from @auth/core/providers/*.ts
const coreSrc = "../packages/core/src"
const providers = fs
.readdirSync(path.join(__dirname, coreSrc, "/providers"))
.filter((file) => file.endsWith(".ts") && !file.startsWith("oauth"))
.map((p) => `${coreSrc}/providers/${p}`)
const typedocConfig = require("./typedoc.json")
delete typedocConfig.$schema
/** @type {import("@docusaurus/types").Config} */
module.exports = {
const docusaurusConfig = {
title: "Auth.js",
tagline: "Authentication for the web.",
tagline: "Authentication for the Web.",
url: "https://authjs.dev",
baseUrl: "/",
favicon: "img/favicon.ico",
trailingSlash: false,
organizationName: "nextauthjs",
projectName: "next-auth",
// TODO: remove this once ready
onBrokenLinks: "log",
projectName: "next-auth",
themeConfig: {
prism: {
theme: require("prism-react-renderer/themes/nightOwl"),
@@ -44,7 +54,7 @@ module.exports = {
position: "left",
},
{
to: "/guides/overview",
to: "/guides",
activeBasePath: "/guides",
label: "Guides",
position: "left",
@@ -104,7 +114,7 @@ module.exports = {
},
{
html: `
<a target="_blank" rel="noopener noreferrer" href="https://vercel.com?utm_source=nextauthjs&utm_campaign=oss">
<a target="_blank" rel="noopener noreferrer" href="https://vercel.com?utm_source=authjs&utm_campaign=oss">
<img
alt="Powered by Vercel"
style="margin-top: 8px"
@@ -169,11 +179,7 @@ module.exports = {
lastVersion: "current",
showLastUpdateAuthor: true,
showLastUpdateTime: true,
remarkPlugins: [
require("@sapphire/docusaurus-plugin-npm2yarn2pnpm").npm2yarn2pnpm,
require("remark-github"),
require("mdx-mermaid"),
],
remarkPlugins: [require("@sapphire/docusaurus-plugin-npm2yarn2pnpm").npm2yarn2pnpm, require("remark-github")],
versions: {
current: {
label: "experimental",
@@ -191,23 +197,42 @@ module.exports = {
"docusaurus-plugin-typedoc",
{
...typedocConfig,
id: "core",
plugin: ["./tyepdoc"],
entryPoints: [
"../packages/core/src/index.ts",
"../packages/core/src/adapters.ts",
"../packages/core/src/providers/index.ts",
"../packages/core/src/providers/github.ts",
"../packages/core/src/providers/spotify.ts",
"../packages/core/src/providers/email.ts",
"../packages/core/src/providers/credentials.ts",
"../packages/core/src/jwt/index.ts",
"../packages/core/src/lib/types.ts",
],
entryPoints: ["index.ts", "adapters.ts", "errors.ts", "jwt.ts", "types.ts"].map((e) => `${coreSrc}/${e}`).concat(providers),
tsconfig: "../packages/core/tsconfig.json",
out: "reference/03-core",
watch: process.env.TYPEDOC_WATCH,
includeExtension: false,
},
],
[
"docusaurus-plugin-typedoc",
{
...typedocConfig,
id: "sveltekit",
plugin: ["./tyepdoc"],
entryPoints: ["index.ts", "client.ts"].map((e) => `../packages/frameworks-sveltekit/src/lib/${e}`),
tsconfig: "../packages/frameworks-sveltekit/tsconfig.json",
out: "reference/04-sveltekit",
watch: process.env.TYPEDOC_WATCH,
includeExtension: false,
},
],
],
}
docusaurusConfig.headTags = [
{ tagName: "meta", attributes: { charSet: "utf-8" } },
{ tagName: "link", attributes: { rel: "canonical", href: docusaurusConfig.url } },
{ tagName: "meta", attributes: { property: "og:title", content: docusaurusConfig.title } },
{ tagName: "meta", attributes: { property: "og:description", content: docusaurusConfig.tagline } },
{ tagName: "meta", attributes: { property: "og:image", content: `${docusaurusConfig.url}/img/og-image.png` } },
{ tagName: "meta", attributes: { property: "og:url", content: docusaurusConfig.url } },
{ tagName: "meta", attributes: { name: "twitter:card", content: "summary_large_image" } },
{ tagName: "meta", attributes: { name: "twitter:title", content: docusaurusConfig.title } },
{ tagName: "meta", attributes: { name: "twitter:description", content: docusaurusConfig.tagline } },
{ tagName: "meta", attributes: { name: "twitter:image", content: `${docusaurusConfig.url}/img/og-image.png` } },
]
module.exports = docusaurusConfig

View File

@@ -17,17 +17,19 @@
"snippets": "node ./scripts/generate-snippets"
},
"dependencies": {
"@auth/core": "workspace:*",
"@auth/sveltekit": "workspace:*",
"@mdx-js/react": "1.6.22",
"@sapphire/docusaurus-plugin-npm2yarn2pnpm": "1.1.3",
"classnames": "^2.3.1",
"mdx-mermaid": "^1.2.2",
"mermaid": "^9.0.1",
"prism-react-renderer": "1.3.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"@sapphire/docusaurus-plugin-npm2yarn2pnpm": "1.1.4",
"classnames": "^2.3.2",
"mdx-mermaid": "1.2.2",
"mermaid": "9.0.1",
"prism-react-renderer": "1.3.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-marquee-slider": "^1.1.5",
"remark-github": "^10.1.0",
"styled-components": "5.3.3"
"remark-github": "10.1.0",
"styled-components": "5.3.6"
},
"devDependencies": {
"@docusaurus/core": "2.2.0",

View File

@@ -1,6 +1,7 @@
const path = require("path")
const fs = require("fs")
// TODO: generate from core package
const providersPath = path.join(
process.cwd(),
"/docs/reference/05-oauth-providers"

View File

@@ -1,19 +1,19 @@
// @ts-check
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
module.exports = {
gettingStarted: [
gettingStartedSidebar: [
{
type: "autogenerated",
dirName: "getting-started",
},
],
guides: [
guidesSidebar: [
{
type: "autogenerated",
dirName: "guides",
},
],
reference: [
referenceSidebar: [
"reference/index",
{
type: "category",
@@ -23,32 +23,33 @@ module.exports = {
id: "reference/core/modules/main",
},
items: [
// See: https://github.com/facebook/docusaurus/issues/5689
// {
// type: "autogenerated",
// dirName: "reference/03-core/modules",
// exclude: ["index"],
// },
"reference/core/modules/adapters",
"reference/core/modules/jwt",
"reference/core/modules/providers",
"reference/core/modules/providers_github",
"reference/core/modules/types",
{
type: "autogenerated",
dirName: "reference/03-core/modules",
// See: https://github.com/facebook/docusaurus/issues/5689
// exclude: ["index"],
},
{
type: "category",
label: "Reflections",
collapsed: true,
className: "reflection-category", // See src/index.css
items: [
{
type: "autogenerated",
dirName: "reference/03-core/functions",
},
{
type: "autogenerated",
dirName: "reference/03-core/interfaces",
},
],
items: [{ type: "autogenerated", dirName: "reference/03-core" }],
},
],
},
{
type: "category",
label: "@auth/sveltekit",
link: { type: "doc", id: "reference/sveltekit/modules/main" },
items: [
{ type: "autogenerated", dirName: "reference/04-sveltekit/modules" },
{
type: "category",
label: "Reflections",
collapsed: true,
className: "reflection-category", // See src/index.css
items: [{ type: "autogenerated", dirName: "reference/04-sveltekit" }],
},
],
},
@@ -70,27 +71,33 @@ module.exports = {
},
{
type: "category",
label: "@auth/sveltekit",
link: {
type: "doc",
id: "reference/sveltekit/index",
},
items: [],
label: "Database Adapters",
link: { type: "doc", id: "reference/adapters/overview" },
items: [
{
type: "autogenerated",
dirName: "reference/06-adapters",
// See: https://github.com/facebook/docusaurus/issues/5689
// exclude: ["index"],
},
],
},
{
type: "category",
label: "Database Adapters",
link: {
type: "doc",
id: "reference/adapters/overview",
},
items: [],
label: "OAuth Providers",
items: [
{
type: "autogenerated",
dirName: "reference/05-oauth-providers",
// See: https://github.com/facebook/docusaurus/issues/5689
// exclude: ["index"],
},
],
},
"reference/utilities/client",
"reference/warnings",
"reference/errors",
],
concepts: [
conceptsSidebar: [
{
type: "autogenerated",
dirName: "concepts",

0
docs/snippets/.gitkeep Normal file
View File

View File

@@ -3,21 +3,21 @@ Add $1 login to your page.
## Example
@example
```js
import Auth from "@auth/core"
import { $1 } from "@auth/core/providers/$2"
const request = new Request("https://example.com")
const resposne = await AuthHandler(request, {
providers: [
$1({clientId: "", clientSecret: ""})
]
providers: [$1({ clientId: "", clientSecret: "" })],
})
```
---
## Resources
@see [Link 1](https://example.com)
---

View File

@@ -10,9 +10,7 @@ import { $1 } from "@auth/core/providers/$2"
const request = new Request("https://example.com")
const resposne = await AuthHandler(request, {
providers: [
$1({clientId: "", clientSecret: ""})
]
providers: [$1({ clientId: "", clientSecret: "" })],
})
```

View File

@@ -274,14 +274,25 @@ html[data-theme="dark"] #carbonads .carbon-poweredby {
background: #1e2021;
}
/*
This is a hack to hide the "Reflection" category from the sidebar.
This is because otherwise opening any page under the "Reflection" category
would hide the entire sidebar.
This is a hack to hide the "Reflection" category and "main" module from the sidebar.
This is because:
1. opening any page under the "Reflection" category would hide the entire sidebar.
2. the "main" module would show up twice.
See sidebars.js
*/
.reflection-category {
.reflection-category,
.theme-doc-sidebar-item-link-level-2 [href="/reference/core/modules/main"],
.theme-doc-sidebar-item-link-level-2
[href="/reference/sveltekit/modules/main"] {
display: none;
}
}
/*
HACK: to hide the "Classes" header and duplicate items together with the "typedoc-plugin-markdown" patch.
See: https://github.com/TypeStrong/typedoc/issues/2006
*/
#classes,
h3.anchor + p:has(code, strong) {
display: none;
}

View File

@@ -9,8 +9,9 @@ import classnames from "classnames"
import { useEffect } from "react"
import ProviderMarquee from "../components/ProviderMarquee"
import styles from "./index.module.css"
import Seo from "./seo"
import providers from "../../providers.json"
const providersCount = Object.keys(providers).length + 2 // email, credentials
const features = [
{
title: "Easy",
@@ -18,13 +19,17 @@ const features = [
description: (
<ul>
<li>
Built in support for popular services
Built in support for {providersCount}+ popular services
<br />
<em>(Google, Facebook, Auth0, Apple)</em>
</li>
<li>Use with OAuth 2+ &amp; OpenID Connect providers</li>
<li>
Use with <i>any</i> OAuth 2 or OpenID Connect provider
</li>
<li>Built in email / passwordless / magic link</li>
<li>Use with any username / password store</li>
<li>
Use with <i>any</i> username / password store
</li>
</ul>
),
},
@@ -36,7 +41,7 @@ const features = [
<li>
Runtime agnostic, runs anywhere!
<br />
<em>Vercel Edge Functions, Serverless</em>
<em>Vercel Edge Functions, Node.js, Serverless</em>
</li>
<li>
Use with any modern framework!
@@ -60,7 +65,7 @@ const features = [
<li>Signed, prefixed, server-only cookies</li>
<li>Built-in CSRF protection</li>
<li>JWT with JWS / JWE / JWK</li>
<li>Tab syncing, auto-revalidation, keepalives</li>
{/* <li>Tab syncing, auto-revalidation, keepalives</li> */}
<li>Doesn't rely on client side JavaScript</li>
</ul>
),
@@ -108,7 +113,6 @@ export default function Home() {
}, [])
return (
<Layout description={siteConfig.tagline}>
<Seo />
<div className="home-wrapper">
<header className={classnames("hero", styles.heroBanner)}>
<div className="container">
@@ -203,7 +207,7 @@ export default function Home() {
<div className="col col--6">
<div className="code">
<h4 className="code-heading">
Next.js <span>/pages/api/auth/[...nextauth].js</span>
Next.js <span>/pages/api/auth/[...nextauth].ts</span>
</h4>
<CodeBlock className="prism-code language-js">
{nextJsCode}
@@ -236,7 +240,7 @@ export default function Home() {
</div>
</section>
<div className={styles.homeSubtitle}>
<p>NextAuth.js is an open source community project.</p>
<p>Auth.js is an open source community project.</p>
</div>
</main>
</div>

View File

@@ -1,25 +0,0 @@
// eslint-disable-next-line no-use-before-define
import * as React from "react"
import Head from "@docusaurus/Head"
import useDocusaurusContext from "@docusaurus/useDocusaurusContext"
export default function Seo() {
const context = useDocusaurusContext()
const { siteConfig = {} } = context
const { title, tagline, url } = siteConfig
return (
<Head>
<meta charSet="utf-8" />
<link rel="canonical" href={url} />
<meta property="og:title" content={title} />
<meta property="og:description" content={tagline} />
<meta property="og:image" content={`${url}/img/og-image.png`} />
<meta property="og:url" content={url} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={tagline} />
<meta name="twitter:image" content={`${url}/img/og-image.png`} />
</Head>
)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 KiB

After

Width:  |  Height:  |  Size: 197 KiB

View File

@@ -17,12 +17,7 @@
"JsonValue"
],
"readme": "none",
"sort": [
"kind",
"static-first",
"required-first",
"alphabetical"
],
"sort": ["kind", "static-first", "required-first", "alphabetical"],
"kindSortOrder": [
"Function",
"TypeAlias",
@@ -47,4 +42,4 @@
"GetSignature",
"SetSignature"
]
}
}

View File

@@ -1,4 +1,5 @@
{
"cleanUrls": true,
"headers": [
{
"source": "/(.*)",
@@ -67,7 +68,7 @@
"value": "sveltekit.authjs.dev"
}
],
"destination": "https://authjs.dev/reference/sveltekit/"
"destination": "https://authjs.dev/reference/sveltekit/modules/main"
},
{
"source": "/:path(.*)",
@@ -77,7 +78,7 @@
"value": "errors.authjs.dev"
}
],
"destination": "https://authjs.dev/reference/errors/:path*"
"destination": "https://authjs.dev/reference/core/modules/errors/:path*"
},
{
"source": "/:path(.*)",
@@ -88,6 +89,26 @@
}
],
"destination": "https://authjs.dev/reference/warnings/:path*"
},
{
"source": "/:path(.*)",
"has": [
{
"type": "host",
"value": "adapters.authjs.dev"
}
],
"destination": "https://authjs.dev/reference/adapters/:path*"
},
{
"source": "/:path",
"has": [
{
"type": "host",
"value": "providers.authjs.dev"
}
],
"destination": "https://authjs.dev/reference/core/functions/providers_:path.default"
}
]
}

View File

@@ -8,7 +8,7 @@
"build": "turbo run build --filter=next-auth --filter=@next-auth/* --filter=@auth/* --no-deps",
"lint": "turbo run lint --parallel",
"format": "turbo run format --parallel",
"test": "turbo run test --concurrency=1 --filter=[HEAD^1] --filter=./packages/* --filter=!*pouchdb-* --filter=!@*upstash*",
"test": "turbo run test --concurrency=1 --filter=[HEAD^1] --filter=./packages/* --filter=!*pouchdb-* --filter=!@*upstash* --filter=!*dynamodb-*",
"clean": "turbo run clean --no-cache",
"dev:db": "turbo run dev --parallel --continue --filter=next-auth-app...",
"dev": "turbo run dev --parallel --continue --filter=next-auth-app... --filter=!./packages/adapter-*",
@@ -20,7 +20,7 @@
},
"devDependencies": {
"@actions/core": "^1.6.0",
"@balazsorban/monorepo-release": "0.1.0",
"@balazsorban/monorepo-release": "0.1.1",
"@types/jest": "^28.1.3",
"@types/node": "^17.0.25",
"@typescript-eslint/eslint-plugin": "^5.10.2",
@@ -66,6 +66,9 @@
"pnpm": {
"overrides": {
"undici": "5.11.0"
},
"patchedDependencies": {
"typedoc-plugin-markdown@3.14.0": "patches/typedoc-plugin-markdown@3.14.0.patch"
}
}
}

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://cloud.dgraph.io/logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://cloud.dgraph.io/logo.svg" />
<h3 align="center"><b>Dgraph Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,9 +14,9 @@
## Overview
This is the Dgraph Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Dgraph Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find two Graphql schemas in the [`docs`](https://next-auth.js.org/adapters/dgraph/schema.gql).
You can find two Graphql schemas in the [`docs`](https://authjs.dev/adapters/dgraph/schema.gql).
1. The unsecure don't implement any auth directive is perfect for a quick start.
2. The second one is more secure and require you replace some value before copy pasting it into your Dgraph console ([`see Securing your database`](#securing-your-database)).
@@ -36,9 +36,9 @@ import NextAuth from "next-auth"
import { DgraphAdapter } from "@next-auth/dgraph-adapter";
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [
...,
],

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/dgraph-adapter",
"version": "1.0.4",
"description": "Dgraph adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -50,4 +50,4 @@
"jest": {
"preset": "@next-auth/adapter-test/jest"
}
}
}

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/dynamodb/logo.png" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/dynamodb/logo.png" />
<h3 align="center"><b>DynamoDB Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -20,7 +20,7 @@ You need a table with a partition key `pk` and a sort key `sk`. Your table also
If you want sessions and verification tokens to get automatically removed from your table you need to [activate TTL](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) on your table with the TTL attribute name set to `expires`
You can find the DynamoDB schema in the docs at [next-auth.js.org/adapters/dynamodb](https://next-auth.js.org/adapters/dynamodb).
You can find the DynamoDB schema in the docs at [authjs.dev/reference/adapters/dynamodb](https://authjs.dev/reference/adapters/dynamodb).
## Getting Started

View File

@@ -9,7 +9,7 @@
"oauth",
"dynamodb"
],
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
},

View File

@@ -1,7 +1,7 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank">
<img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/fauna/logo.svg" />
<a href="https://authjs.dev" target="_blank">
<img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/fauna/logo.svg" />
<h3 align="center"><b>Fauna Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -15,9 +15,9 @@
## Overview
This is the Fauna Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Fauna Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find the Fauna schema and seed information in the docs at [next-auth.js.org/adapters/fauna](https://next-auth.js.org/adapters/fauna).
You can find the Fauna schema and seed information in the docs at [authjs.dev/reference/adapters/fauna](https://authjs.dev/reference/adapters/fauna).
## Getting Started
@@ -42,9 +42,9 @@ const client = new FaunaClient({
})
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: FaunaAdapter(client)
...

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/fauna-adapter",
"version": "1.0.4",
"description": "Fauna Adapter for NextAuth",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -56,4 +56,4 @@
"jest": {
"preset": "@next-auth/adapter-test/jest"
}
}
}

View File

@@ -1,7 +1,7 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank">
<img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a><img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/firebase/logo.svg" />
<a href="https://authjs.dev" target="_blank">
<img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a><img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/firebase/logo.svg" />
<h3 align="center"><b>Firebase Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -15,9 +15,9 @@
## Overview
This is the Firebase Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Firebase Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
You can find more Firebase information in the docs at [next-auth.js.org/adapters/firebase](https://next-auth.js.org/adapters/firebase).
You can find more Firebase information in the docs at [authjs.dev/reference/adapters/firebase](https://authjs.dev/reference/adapters/firebase).
## Getting Started
@@ -41,9 +41,9 @@ const app = initializeApp({ projectId: "next-auth-test" });
const firestore = getFirestore(app);
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/firebase-adapter",
"version": "1.0.3",
"description": "Firebase adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -43,4 +43,4 @@
"jest": "^27.4.3",
"next-auth": "workspace:*"
}
}
}

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/mikro-orm/logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/mikro-orm/logo.svg" />
<h3 align="center"><b>Mikro ORM Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,7 +14,7 @@
## Overview
This is the MikroORM Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the MikroORM Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
## Getting Started
@@ -31,9 +31,9 @@ This is the MikroORM Adapter for [`next-auth`](https://next-auth.js.org). This p
import { MikroOrmAdapter } from "@next-auth/mikro-orm-adapter"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: MikroOrmAdapter({
dbName: "./db.sqlite",

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/mikro-orm-adapter",
"version": "3.0.1",
"description": "MikroORM adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="./logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="./logo.svg" />
<h3 align="center"><b>MongoDB Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,7 +14,7 @@
## Overview
This is the MongoDB Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the MongoDB Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
## Getting Started
@@ -70,7 +70,7 @@ import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "lib/mongodb"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
adapter: MongoDBAdapter(clientPromise, {
databaseName: 'my-data-base-name'

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/mongodb-adapter",
"version": "1.1.1",
"description": "mongoDB adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="./logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="./logo.svg" />
<h3 align="center"><b>Neo4j Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,9 +14,9 @@
## Overview
This is the Neo4j Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Neo4j Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find the Neo4j schema in the docs at [next-auth.js.org/adapters/neo4j](next-auth.js.org/adapters/neo4j).
You can find the Neo4j schema in the docs at [authjs.dev/reference/adapters/neo4j](authjs.dev/reference/adapters/neo4j).
## Getting Started
@@ -41,7 +41,7 @@ const driver = neo4j.driver(
const neo4jSession = driver.session()
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: Neo4jAdapter(neo4jSession),
...

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/neo4j-adapter",
"version": "1.0.5",
"description": "neo4j adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/pouchdb/logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/pouchdb/logo.svg" />
<h3 align="center"><b>PouchDB Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,7 +14,7 @@
## Overview
This is the PouchDB Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the PouchDB Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
Depending on your architecture you can use PouchDB's http adapter to reach any database compliant with the CouchDB protocol (CouchDB, Cloudant, ...) or use any other PouchDB compatible adapter (leveldb, in-memory, ...)
@@ -43,9 +43,9 @@ PouchDB.plugin(require("pouchdb-adapter-leveldb")) // Or any other PouchDB-compl
const pouchdb = new PouchDB("auth_db", { adapter: "leveldb" })
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/pouchdb-adapter",
"version": "0.1.5",
"description": "PouchDB adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -51,4 +51,4 @@
"jest": {
"preset": "@next-auth/adapter-test/jest"
}
}
}

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/prisma/logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/prisma/logo.svg" />
<h3 align="center"><b>Prisma Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,9 +14,9 @@
## Overview
This is the Prisma Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Prisma Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find the Prisma schema in the docs at [next-auth.js.org/adapters/prisma](https://next-auth.js.org/adapters/prisma).
You can find the Prisma schema in the docs at [authjs.dev/reference/adapters/prisma](https://authjs.dev/reference/adapters/prisma).
## Getting Started
@@ -37,9 +37,9 @@ import * as Prisma from "@prisma/client"
const prisma = new Prisma.PrismaClient()
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: PrismaAdapter(prisma)
...

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/prisma-adapter",
"version": "1.0.5",
"description": "Prisma adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/sequelize/logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/main/packages/sequelize/logo.svg" />
<h3 align="center"><b>Sequelize Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,9 +14,9 @@
## Overview
This is the Sequelize Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Sequelize Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find the Sequelize schema in the docs at [next-auth.js.org/adapters/sequelize](https://next-auth.js.org/adapters/sequelize).
You can find the Sequelize schema in the docs at [authjs.dev/reference/adapters/sequelize](https://authjs.dev/reference/adapters/sequelize).
## Getting Started
@@ -37,7 +37,7 @@ import Sequelize from 'sequelize'
const sequelize = new Sequelize("sqlite::memory:")
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
...
adapter: SequelizeAdapter(sequelize)
@@ -47,7 +47,7 @@ export default NextAuth({
## Updating the database schema
In development, the sequelize adapter will create the necessary tables, foreign keys and indexes in your database. In production, synchronization is disabled. Best practice is to create the [required tables](https://next-auth.js.org/adapters/models) in your database via [migrations](https://sequelize.org/master/manual/migrations.html).
In development, the sequelize adapter will create the necessary tables, foreign keys and indexes in your database. In production, synchronization is disabled. Best practice is to create the [required tables](https://authjs.dev/reference/adapters/models) in your database via [migrations](https://sequelize.org/master/manual/migrations.html).
In development, if you do not want the adapter to automatically create tables, you are able to pass `{ synchronize: false }` as the second option to `SequelizeAdapter` to disable this behavior:

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/sequelize-adapter",
"version": "1.0.7",
"description": "Sequelize adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -42,4 +42,4 @@
"jest": {
"preset": "@next-auth/adapter-test/jest"
}
}
}

View File

@@ -1,7 +1,7 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank">
<img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a><img height="64px" src="./logo.svg" />
<a href="https://authjs.dev" target="_blank">
<img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a><img height="64px" src="./logo.svg" />
<h3 align="center"><b>Supabase Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -15,9 +15,9 @@
## Overview
This is the Supabase Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the Supabase Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find more Supabase information in the docs at [next-auth.js.org/adapters/supabase](https://next-auth.js.org/adapters/supabase).
You can find more Supabase information in the docs at [authjs.dev/reference/adapters/supabase](https://authjs.dev/reference/adapters/supabase).
## Getting Started
@@ -34,9 +34,9 @@ import NextAuth from "next-auth"
import { SupabaseAdapter } from "@next-auth/supabase-adapter"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [
// ...
],

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/supabase-adapter",
"version": "0.2.0",
"description": "Supabase adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" />&nbsp;&nbsp;&nbsp;&nbsp;</a><img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/canary/packages/typeorm-legacy/logo.png" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" />&nbsp;&nbsp;&nbsp;&nbsp;</a><img height="64px" src="https://raw.githubusercontent.com/nextauthjs/adapters/canary/packages/typeorm-legacy/logo.png" />
<h3 align="center"><b>TypeORM (Legacy) Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,9 +14,9 @@
## Overview
This is the TypeORM Adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` package. It is not a standalone package.
This is the TypeORM Adapter for [`auth.js`](https://authjs.dev). This package can only be used in conjunction with the primary `auth.js` package. It is not a standalone package.
You can find more TypeORM information in the docs at [next-auth.js.org/adapters/typeorm](https://next-auth.js.org/adapters/typeorm).
You can find more TypeORM information in the docs at [authjs.dev/adapters/typeorm](https://authjs.dev/reference/adapters/typeorm).
## Getting Started
@@ -33,9 +33,9 @@ import NextAuth from "next-auth"
import { TypeORMLegacyAdapter } from "@next-auth/typeorm-legacy-adapter"
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-config
export default NextAuth({
// https://next-auth.js.org/configuration/providers
// https://authjs.dev/reference/providers/oauth-builtin
providers: [],
adapter: TypeORMLegacyAdapter({
type: 'sqlite', // or mysql, postgresql, mssql
@@ -54,7 +54,7 @@ export default NextAuth({
This adapter supports MySQL, PostgreSQL, SQLite, as well as MSSQL. Further configuration options are listed below.
> If you're looking for MongoDB support, it's been pulled out into its own adapter [@next-auth/mongodb-adapter](https://next-auth.js.org/adapters/mongodb).
> If you're looking for MongoDB support, it's been pulled out into its own adapter [@next-auth/mongodb-adapter](https://authjs.dev/reference/adapters/mongodb).
### SQLite

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/typeorm-legacy-adapter",
"version": "2.0.1",
"description": "TypeORM (legacy) adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -103,7 +103,7 @@ export async function updateConnectionEntities(
if (dataSource.options.synchronize !== false) {
console.warn(
"[next-auth][warn][adapter_typeorm_updating_entities]",
"\nhttps://next-auth.js.org/warnings#adapter_typeorm_updating_entities"
"\nhttps://authjs.dev/reference/warnings#adapter_typeorm_updating_entities"
)
await dataSource.synchronize()
}

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="logo.svg" />
<h3 align="center"><b>Upstash Redis Adapter</b> - NextAuth.js</h3>
<p align="center">
Open Source. Full Stack. Own Your Data.
@@ -14,7 +14,7 @@
## Overview
This is the Upstash Redis adapter for [`next-auth`](https://next-auth.js.org). This package can only be used in conjunction with the primary `next-auth` and `@upstash/redis` packages. It is not a standalone package.
This is the Upstash Redis adapter for [`next-auth`](https://authjs.dev). This package can only be used in conjunction with the primary `next-auth` and `@upstash/redis` packages. It is not a standalone package.
## Getting Started
@@ -32,12 +32,12 @@ import { UpstashRedisAdapter } from "@next-auth/upstash-adapter"
import { Redis } from "@upstash/redis"
const redis = new Redis({
url:"UPSTASH_REDIS_REST_URL",
url:"UPSTASH_REDIS_REST_URL",
token:"UPSTASH_REDIS_REST_TOKEN",
})
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
...
adapter: UpstashRedisAdapter(redis)

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/upstash-redis-adapter",
"version": "3.0.3",
"description": "Upstash adapter for next-auth. It uses Upstash's connectionless (HTTP based) Redis client.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"

View File

@@ -1,6 +1,6 @@
<p align="center">
<br/>
<a href="https://next-auth.js.org" target="_blank"><img height="64px" src="https://next-auth.js.org/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="logo.svg" />
<a href="https://authjs.dev" target="_blank"><img height="64px" src="https://authjs.dev/img/logo/logo-sm.png" /></a>&nbsp;&nbsp;&nbsp;&nbsp;<img height="64px" src="logo.svg" />
<h3 align="center"><b>Xata Adapter</b> - NextAuth.js</h3>
<p align="center">
Think data, not databases.

View File

@@ -2,7 +2,7 @@
"name": "@next-auth/xata-adapter",
"version": "0.2.0",
"description": "Xata adapter for next-auth.",
"homepage": "https://next-auth.js.org",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth",
"bugs": {
"url": "https://github.com/nextauthjs/next-auth/issues"
@@ -43,4 +43,4 @@
"jest": {
"preset": "@next-auth/adapter-test/jest"
}
}
}

View File

@@ -1,3 +1,3 @@
# Auth.js
Authentication for the web.
Authentication for the web.

View File

@@ -1,6 +1,6 @@
{
"name": "@auth/core",
"version": "0.1.4",
"version": "0.2.0",
"description": "Authentication for the web.",
"homepage": "https://authjs.dev",
"repository": "https://github.com/nextauthjs/next-auth.git",
@@ -15,9 +15,8 @@
"type": "module",
"types": "./index.d.ts",
"files": [
"adapters.*",
"index.*",
"jwt",
"*.js",
"*.d.ts",
"lib",
"providers",
"src"
@@ -30,9 +29,13 @@
"./adapters": {
"types": "./adapters.d.ts"
},
"./errors": {
"import": "./errors.js",
"types": "./errors.d.ts"
},
"./jwt": {
"types": "./jwt/index.d.ts",
"import": "./jwt/index.js"
"types": "./jwt.d.ts",
"import": "./jwt.js"
},
"./providers": {
"types": "./providers/index.d.ts"
@@ -42,7 +45,7 @@
"import": "./providers/*.js"
},
"./types": {
"types": "./lib/types.d.ts"
"types": "./types.d.ts"
}
},
"license": "ISC",
@@ -64,10 +67,10 @@
},
"scripts": {
"build": "pnpm clean && pnpm css && tsc",
"clean": "rm -rf adapters.* index.* jwt lib providers",
"clean": "rm -rf *.js *.d.ts lib providers",
"css": "node ./scripts/generate-css.js",
"lint": "eslint src",
"format": "pnpm lint --fix",
"lint": "pnpm prettier --check src && eslint src",
"format": "pnpm prettier --write . && eslint src --fix",
"dev": "pnpm css && tsc -w"
},
"devDependencies": {
@@ -80,4 +83,4 @@
"postcss": "8.4.19",
"postcss-nested": "6.0.0"
}
}
}

View File

@@ -6,7 +6,7 @@ import autoprefixer from "autoprefixer"
import postCssNested from "postcss-nested"
import cssNano from "cssnano"
const from = path.join(process.cwd(), "src/lib/styles/index.css")
const from = path.join(process.cwd(), "src/lib/pages/styles.css")
const css = fs.readFileSync(from)
const processedCss = await postcss([
@@ -16,7 +16,7 @@ const processedCss = await postcss([
]).process(css, { from })
fs.writeFileSync(
path.join(process.cwd(), "src/lib/styles/index.ts"),
path.join(process.cwd(), "src/lib/pages/styles.ts"),
`export default \`${processedCss.css}\`
// Generated by \`pnpm css\``
)

View File

@@ -1,8 +1,9 @@
/**
* The `@auth/core/adapters` module contains useful helpers that a database adapter
* can incorporate in order to be compatible with Auth.js.
* You can think of an adapter as a way to normalize database implementation details to a common interface
* that Auth.js can use to interact with the database.
* This module contains functions and types that a database adapter
* can use to be compatible with Auth.js.
*
* A database adapter provides a common interface for Auth.js so that it can work with
* _any_ database/ORM adapter without concerning itself with the implementation details of the database/ORM.
*
* Auth.js supports 2 session strtategies to persist the login state of a user.
* The default is to use a cookie + {@link https://authjs.dev/concepts/session-strategies#jwt JWT}
@@ -11,7 +12,7 @@
*
* :::info Note
* Auth.js _currently_ does **not** implement {@link https://authjs.dev/concepts/session-strategies#federated-logout federated logout}.
* So even if the session is deleted from the database, the user will still be logged in to the provider.
* So even if the session is deleted from the database, the user will still be logged in to the provider (but will be logged out of the app).
* See [this discussion](https://github.com/nextauthjs/next-auth/discussions/3938) for more information.
* :::
*
@@ -21,33 +22,52 @@
* npm install @auth/core
* ```
*
* You can then import this submodule from `@auth/core/adapters`.
*
* ## Usage
*
* {@link https://authjs.dev/reference/adapters/overview Built-in adapters} already implement this interface, so you likely won't need to
* {@link https://authjs.dev/reference/adapters/overview Built-in adapters} already implement this interfac, so you likely won't need to
* implement it yourself. If you do, you can use the following example as a
* starting point.
*
* ```ts
* // src/your-adapter.ts
* ```ts title=your-adapter.ts
* import { type Adapter } from "@auth/core/adapters"
*
* export function MyAdapter(options: any): Adapter {
* export function MyAdapter(config: {}): Adapter {
* // implement the adapter methods
* }
* ```
*
* // src/index.ts
* ```ts title=index.ts
* import { MyAdapter } from "./your-adapter"
*
* const response = Auth({
* adapter: MyAdapter({ ...adapter options }),
* ... auth options
* adapter: MyAdapter({ /* ...adapter config *\/ }),
* // ... auth config
* })
* ```
*
* :::caution Note
* Although `@auth/core` is framework/runtime agnostic, an adapter might rely on a client/ORM package,
* that is not yet compatible with your runtime
* (E.g. it might rely on [Node.js-specific APIs](https://nodejs.org/docs/latest/api)) when you are trying to use it elsewhere.
* Related issues should be reported to the corresponding package maintainers.
* :::
*
* ### Testing
* :::tip
* If you are writing your own adapter, there is a test suite [available](https://github.com/nextauthjs/next-auth/tree/main/packages/adapter-test)
* to ensure that your adapter is compatible with Auth.js.
* :::
*
* ## Resources
*
* - [What is a database session strategy?](https://authjs.dev/concepts/session-strategies#database)
*
* @module adapters
*/
import type { Account, Awaitable, User } from "./lib/types"
import type { Account, Awaitable, User } from "./types.js"
// TODO: Discuss if we should expose methods to serialize and deserialize
// the data? Many adapters share this logic, so it could be useful to
@@ -64,7 +84,7 @@ export interface AdapterAccount extends Account {
}
/**
* The session object implementing this interface is
* The session object implementing this interface
* is used to look up the user in the database.
*/
export interface AdapterSession {
@@ -93,87 +113,66 @@ export interface VerificationToken {
}
/**
* Using a custom adapter you can connect to any database backend or even
* several different databases. Custom adapters created and maintained by our
* community can be found in the adapters repository. Feel free to add a custom
* adapter from your project to the repository, or even become a maintainer of a
* certain adapter. Custom adapters can still be created and used in a project
* without being added to the repository.
* Using a custom adapter you can connect to any database backend or even several different databases.
* Custom adapters created and maintained by our community can be found in the adapters repository.
* Feel free to add a custom adapter from your project to the repository,
* or even become a maintainer of a certain adapter.
* Custom adapters can still be created and used in a project without being added to the repository.
*
* ## Useful resources
* ## Resources
*
* @see [Session strategies](https://authjs.dev/concepts/session-strategies#database)
* @see [Using a database adapter](https://authjs.dev/guides/adapters/using-a-database-adapter)
* @see [Creating a database adapter](https://authjs.dev/guides/adapters/creating-a-database-adapter)
* - [Session strategies](https://authjs.dev/concepts/session-strategies#database)
* - [Using a database adapter](https://authjs.dev/guides/adapters/using-a-database-adapter)
* - [Creating a database adapter](https://authjs.dev/guides/adapters/creating-a-database-adapter)
*/
export type Adapter<WithVerificationToken = boolean> = DefaultAdapter &
(WithVerificationToken extends true
? {
createVerificationToken: (
verificationToken: VerificationToken
) => Awaitable<VerificationToken | null | undefined>
/**
* Return verification token from the database and delete it so it
* cannot be used again.
*/
useVerificationToken: (params: {
identifier: string
token: string
}) => Awaitable<VerificationToken | null>
}
: {})
export interface DefaultAdapter {
createUser: (user: Omit<AdapterUser, "id">) => Awaitable<AdapterUser>
getUser: (id: string) => Awaitable<AdapterUser | null>
getUserByEmail: (email: string) => Awaitable<AdapterUser | null>
/**
* Using the provider id and the id of the user for a specific account, get
* the user.
*/
getUserByAccount: (
export interface Adapter {
createUser(user: Omit<AdapterUser, "id">): Awaitable<AdapterUser>
getUser(id: string): Awaitable<AdapterUser | null>
getUserByEmail(email: string): Awaitable<AdapterUser | null>
/** Using the provider id and the id of the user for a specific account, get the user. */
getUserByAccount(
providerAccountId: Pick<AdapterAccount, "provider" | "providerAccountId">
) => Awaitable<AdapterUser | null>
updateUser: (user: Partial<AdapterUser>) => Awaitable<AdapterUser>
/** @todo Implement */
deleteUser?: (
): Awaitable<AdapterUser | null>
updateUser(user: Partial<AdapterUser>): Awaitable<AdapterUser>
/** @todo This method is currently not implemented. Defining it will have no effect */
deleteUser?(
userId: string
) => Promise<void> | Awaitable<AdapterUser | null | undefined>
linkAccount: (
): Promise<void> | Awaitable<AdapterUser | null | undefined>
linkAccount(
account: AdapterAccount
) => Promise<void> | Awaitable<AdapterAccount | null | undefined>
/** @todo Implement */
unlinkAccount?: (
): Promise<void> | Awaitable<AdapterAccount | null | undefined>
/** @todo This method is currently not implemented. Defining it will have no effect */
unlinkAccount?(
providerAccountId: Pick<AdapterAccount, "provider" | "providerAccountId">
) => Promise<void> | Awaitable<AdapterAccount | undefined>
): Promise<void> | Awaitable<AdapterAccount | undefined>
/** Creates a session for the user and returns it. */
createSession: (session: {
createSession(session: {
sessionToken: string
userId: string
expires: Date
}) => Awaitable<AdapterSession>
getSessionAndUser: (
}): Awaitable<AdapterSession>
getSessionAndUser(
sessionToken: string
) => Awaitable<{ session: AdapterSession; user: AdapterUser } | null>
updateSession: (
): Awaitable<{ session: AdapterSession; user: AdapterUser } | null>
updateSession(
session: Partial<AdapterSession> & Pick<AdapterSession, "sessionToken">
) => Awaitable<AdapterSession | null | undefined>
): Awaitable<AdapterSession | null | undefined>
/**
* Deletes a session from the database. It is preferred that this method also
* returns the session that is being deleted for logging purposes.
*/
deleteSession: (
deleteSession(
sessionToken: string
) => Promise<void> | Awaitable<AdapterSession | null | undefined>
createVerificationToken?: (
): Promise<void> | Awaitable<AdapterSession | null | undefined>
createVerificationToken?(
verificationToken: VerificationToken
) => Awaitable<VerificationToken | null | undefined>
): Awaitable<VerificationToken | null | undefined>
/**
* Return verification token from the database and delete it so it cannot be
* used again.
*/
useVerificationToken?: (params: {
useVerificationToken?(params: {
identifier: string
token: string
}) => Awaitable<VerificationToken | null>
}): Awaitable<VerificationToken | null>
}

View File

@@ -0,0 +1,95 @@
/** @internal */
export class AuthError extends Error {
metadata?: Record<string, unknown>
constructor(message: Error | string, metadata?: Record<string, unknown>) {
if (message instanceof Error) {
super(message.message)
this.stack = message.stack
} else super(message)
this.name = this.constructor.name
this.metadata = metadata
Error.captureStackTrace?.(this, this.constructor)
}
}
/**
* @todo
* Thrown when an Email address is already associated with an account
* but the user is trying an OAuth account that is not linked to it.
*/
export class AccountNotLinked extends AuthError {}
/**
* @todo
* One of the database `Adapter` methods failed.
*/
export class AdapterError extends AuthError {}
/** @todo */
export class AuthorizedCallbackError extends AuthError {}
/** @todo */
export class CallbackRouteError extends AuthError {}
/** @todo */
export class ErrorPageLoop extends AuthError {}
/** @todo */
export class EventError extends AuthError {}
/** @todo */
export class InvalidCallbackUrl extends AuthError {}
/** @todo */
export class InvalidEndpoints extends AuthError {}
/** @todo */
export class InvalidState extends AuthError {}
/** @todo */
export class JWTSessionError extends AuthError {}
/** @todo */
export class MissingAdapter extends AuthError {}
/** @todo */
export class MissingAdapterMethods extends AuthError {}
/** @todo */
export class MissingAPIRoute extends AuthError {}
/** @todo */
export class MissingAuthorize extends AuthError {}
/** @todo */
export class MissingSecret extends AuthError {}
/** @todo */
export class OAuthSignInError extends AuthError {}
/** @todo */
export class OAuthCallbackError extends AuthError {}
/** @todo */
export class OAuthCreateUserError extends AuthError {}
/** @todo */
export class OAuthProfileParseError extends AuthError {}
/** @todo */
export class SessionTokenError extends AuthError {}
/** @todo */
export class SignInError extends AuthError {}
/** @todo */
export class SignOutError extends AuthError {}
/** @todo */
export class UnknownAction extends AuthError {}
/** @todo */
export class UnsupportedStrategy extends AuthError {}
/** @todo */
export class UntrustedHost extends AuthError {}

View File

@@ -1,9 +1,19 @@
/**
*
* `@auth/core` is the main entry point for the Auth.js library.
* This is the main entry point to the Auth.js library.
*
* Based on the {@link https://developer.mozilla.org/en-US/docs/Web/API/Request Request}
* and {@link https://developer.mozilla.org/en-US/docs/Web/API/Response Response} Web standard APIs.
* Primarily used to implement [framework](https://authjs.dev/concepts/frameworks)-specific packages,
* but it can also be used directly.
*
* ## Installation
*
* ```bash npm2yarn2pnpm
* npm install @auth/core
* ```
*
* ## Usage
*
* ```ts
* import { Auth } from "@auth/core"
@@ -14,293 +24,113 @@
* console.log(response instanceof Response) // true
* ```
*
* Primarily used to implement [framework](https://authjs.dev/concepts/frameworks)-specific packages,
* but it can also be used directly.
* ## Resources
*
* ## Installation
*
* ```bash npm2yarn2pnpm
* npm install @auth/core
* ```
* - [Gettint started](https://authjs.dev/getting-started/introduction)
* - [Most common use case guides](https://authjs.dev/guides/overview)
*
* @module main
*/
import { init } from "./lib/init.js"
import { assertConfig } from "./lib/assert.js"
import { SessionStore } from "./lib/cookie.js"
import { toInternalRequest, toResponse } from "./lib/web.js"
import { ErrorPageLoop } from "./errors.js"
import { AuthInternal } from "./lib/index.js"
import renderPage from "./lib/pages/index.js"
import * as routes from "./lib/routes/index.js"
import logger, { setLogger } from "./lib/utils/logger.js"
import { logger, setLogger, type LoggerInstance } from "./lib/utils/logger.js"
import { toInternalRequest, toResponse } from "./lib/web.js"
import type { ErrorType } from "./lib/pages/error.js"
import type { Adapter } from "./adapters.js"
import type {
AuthOptions,
RequestInternal,
ResponseInternal,
} from "./lib/types.js"
import { UntrustedHost } from "./lib/errors.js"
// Only thing exported from this file should be `AuthHandler` and `AuthOptions`
// TODO Don't re-export, just add `@auth/core/types` exports in package.json and change references these types
export * from "./lib/types.js"
const configErrorMessage =
"There is a problem with the server configuration. Check the server logs for more information."
async function AuthHandlerInternal<
Body extends string | Record<string, any> | any[]
>(params: {
req: RequestInternal
options: AuthOptions
/** REVIEW: Is this the best way to skip parsing the body in Node.js? */
parsedBody?: any
}): Promise<ResponseInternal<Body>> {
const { options: authOptions, req } = params
const assertionResult = assertConfig({ options: authOptions, req })
if (Array.isArray(assertionResult)) {
assertionResult.forEach(logger.warn)
} else if (assertionResult instanceof Error) {
// Bail out early if there's an error in the user config
logger.error((assertionResult as any).code, assertionResult)
const htmlPages = ["signin", "signout", "error", "verify-request"]
if (!htmlPages.includes(req.action) || req.method !== "GET") {
return {
status: 500,
headers: { "Content-Type": "application/json" },
body: { message: configErrorMessage } as any,
}
}
const { pages, theme } = authOptions
const authOnErrorPage =
pages?.error && req.query?.callbackUrl?.startsWith(pages.error)
if (!pages?.error || authOnErrorPage) {
if (authOnErrorPage) {
logger.error(
"AUTH_ON_ERROR_PAGE_ERROR",
new Error(
`The error page ${pages?.error} should not require authentication`
)
)
}
const render = renderPage({ theme })
return render.error({ error: "configuration" })
}
return {
redirect: `${pages.error}?error=Configuration`,
}
}
const { action, providerId, error, method } = req
const { options, cookies } = await init({
authOptions,
action,
providerId,
url: req.url,
callbackUrl: req.body?.callbackUrl ?? req.query?.callbackUrl,
csrfToken: req.body?.csrfToken,
cookies: req.cookies,
isPost: method === "POST",
})
const sessionStore = new SessionStore(
options.cookies.sessionToken,
req,
options.logger
)
if (method === "GET") {
const render = renderPage({ ...options, query: req.query, cookies })
const { pages } = options
switch (action) {
case "providers":
return (await routes.providers(options.providers)) as any
case "session": {
const session = await routes.session({ options, sessionStore })
if (session.cookies) cookies.push(...session.cookies)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return { ...session, cookies } as any
}
case "csrf":
return {
headers: { "Content-Type": "application/json" },
body: { csrfToken: options.csrfToken } as any,
cookies,
}
case "signin":
if (pages.signIn) {
let signinUrl = `${pages.signIn}${
pages.signIn.includes("?") ? "&" : "?"
}callbackUrl=${encodeURIComponent(options.callbackUrl)}`
if (error)
signinUrl = `${signinUrl}&error=${encodeURIComponent(error)}`
return { redirect: signinUrl, cookies }
}
return render.signin()
case "signout":
if (pages.signOut) return { redirect: pages.signOut, cookies }
return render.signout()
case "callback":
if (options.provider) {
const callback = await routes.callback({
body: req.body,
query: req.query,
headers: req.headers,
cookies: req.cookies,
method,
options,
sessionStore,
})
if (callback.cookies) cookies.push(...callback.cookies)
return { ...callback, cookies }
}
break
case "verify-request":
if (pages.verifyRequest) {
return { redirect: pages.verifyRequest, cookies }
}
return render.verifyRequest()
case "error":
// These error messages are displayed in line on the sign in page
if (
[
"Signin",
"OAuthSignin",
"OAuthCallback",
"OAuthCreateAccount",
"EmailCreateAccount",
"Callback",
"OAuthAccountNotLinked",
"EmailSignin",
"CredentialsSignin",
"SessionRequired",
].includes(error as string)
) {
return { redirect: `${options.url}/signin?error=${error}`, cookies }
}
if (pages.error) {
return {
redirect: `${pages.error}${
pages.error.includes("?") ? "&" : "?"
}error=${error}`,
cookies,
}
}
return render.error({ error: error as ErrorType })
default:
}
} else if (method === "POST") {
switch (action) {
case "signin":
// Verified CSRF Token required for all sign in routes
if (options.csrfTokenVerified && options.provider) {
const signin = await routes.signin({
query: req.query,
body: req.body,
options,
})
if (signin.cookies) cookies.push(...signin.cookies)
return { ...signin, cookies }
}
return { redirect: `${options.url}/signin?csrf=true`, cookies }
case "signout":
// Verified CSRF Token required for signout
if (options.csrfTokenVerified) {
const signout = await routes.signout({ options, sessionStore })
if (signout.cookies) cookies.push(...signout.cookies)
return { ...signout, cookies }
}
return { redirect: `${options.url}/signout?csrf=true`, cookies }
case "callback":
if (options.provider) {
// Verified CSRF Token required for credentials providers only
if (
options.provider.type === "credentials" &&
!options.csrfTokenVerified
) {
return { redirect: `${options.url}/signin?csrf=true`, cookies }
}
const callback = await routes.callback({
body: req.body,
query: req.query,
headers: req.headers,
cookies: req.cookies,
method,
options,
sessionStore,
})
if (callback.cookies) cookies.push(...callback.cookies)
return { ...callback, cookies }
}
break
case "_log":
if (authOptions.logger) {
try {
const { code, level, ...metadata } = req.body ?? {}
logger[level](code, metadata)
} catch (error) {
// If logging itself failed...
logger.error("LOGGER_ERROR", error as Error)
}
}
return {}
default:
}
}
return {
status: 400,
body: `Error: This action with HTTP ${method} is not supported by NextAuth.js` as any,
}
}
CallbacksOptions,
CookiesOptions,
EventCallbacks,
PagesOptions,
SessionOptions,
Theme,
} from "./types.js"
import type { Provider } from "./providers/index.js"
import { JWTOptions } from "./jwt.js"
/**
* The core functionality of Auth.js. It receives a standard
* [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and
* returns a standard
* [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
* Core functionality provided by Auth.js.
*
* Receives a standard {@link Request} and returns a {@link Response}.
*
* @example
* ```ts
* import Auth from "@auth/core"
*
* const request = new Request("https://example.com")
* const resposne = await AuthHandler(request, {
* providers: [...],
* secret: "...",
* trustHost: true,
* })
*```
* @see [Documentation](https://authjs.dev)
*/
export async function AuthHandler(
export async function Auth(
request: Request,
options: AuthOptions
config: AuthConfig
): Promise<Response> {
setLogger(options.logger, options.debug)
setLogger(config.logger, config.debug)
if (!options.trustHost) {
const error = new UntrustedHost(
`Host must be trusted. URL was: ${request.url}`
)
logger.error(error.code, error)
return new Response(JSON.stringify({ message: configErrorMessage }), {
status: 500,
headers: { "Content-Type": "application/json" },
})
}
const req = await toInternalRequest(request)
if (req instanceof Error) {
logger.error((req as any).code, req)
const internalRequest = await toInternalRequest(request)
if (internalRequest instanceof Error) {
logger.error(internalRequest)
return new Response(
`Error: This action with HTTP ${request.method} is not supported.`,
{ status: 400 }
)
}
const internalResponse = await AuthHandlerInternal({ req, options })
const assertionResult = assertConfig(internalRequest, config)
if (Array.isArray(assertionResult)) {
assertionResult.forEach(logger.warn)
} else if (assertionResult instanceof Error) {
// Bail out early if there's an error in the user config
logger.error(assertionResult)
const htmlPages = ["signin", "signout", "error", "verify-request"]
if (
!htmlPages.includes(internalRequest.action) ||
internalRequest.method !== "GET"
) {
return new Response(
JSON.stringify({
message:
"There was a problem with the server configuration. Check the server logs for more information.",
code: assertionResult.name,
}),
{ status: 500, headers: { "Content-Type": "application/json" } }
)
}
const { pages, theme } = config
const authOnErrorPage =
pages?.error &&
internalRequest.url.searchParams
.get("callbackUrl")
?.startsWith(pages.error)
if (!pages?.error || authOnErrorPage) {
if (authOnErrorPage) {
logger.error(
new ErrorPageLoop(
`The error page ${pages?.error} should not require authentication`
)
)
}
const render = renderPage({ theme })
const page = render.error({ error: "Configuration" })
return toResponse(page)
}
return Response.redirect(`${pages.error}?error=Configuration`)
}
const internalResponse = await AuthInternal(internalRequest, config)
const response = await toResponse(internalResponse)
@@ -316,3 +146,212 @@ export async function AuthHandler(
}
return response
}
/**
* Configure the {@link Auth} method.
*
* @example
* ```ts
* import Auth, { type AuthConfig } from "@auth/core"
*
* export const authConfig: AuthConfig = {...}
*
* const request = new Request("https://example.com")
* const resposne = await AuthHandler(request, authConfig)
*
* ```
*
* @see [Initiailzation](https://authjs.dev/reference/configuration/auth-options)
*/
export interface AuthConfig {
/**
* List of authentication providers for signing in
* (e.g. Google, Facebook, Twitter, GitHub, Email, etc) in any order.
* This can be one of the built-in providers or an object with a custom provider.
* * **Default value**: `[]`
* * **Required**: *Yes*
*
* [Documentation](https://next-auth.js.org/configuration/options#providers) | [Providers documentation](https://next-auth.js.org/configuration/providers)
*/
providers: Provider[]
/**
* A random string used to hash tokens, sign cookies and generate cryptographic keys.
* If not specified, it falls back to `AUTH_SECRET` or `NEXTAUTH_SECRET` from environment variables.
* To generate a random string, you can use the following command:
*
* On Unix systems: `openssl rand -hex 32`
* Or go to https://generate-secret.vercel.app/32
*
* @default process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET
*
* [Documentation](https://next-auth.js.org/configuration/options#secret)
*/
secret?: string
/**
* Configure your session like if you want to use JWT or a database,
* how long until an idle session expires, or to throttle write operations in case you are using a database.
* * **Default value**: See the documentation page
* * **Required**: No
*
* [Documentation](https://next-auth.js.org/configuration/options#session)
*/
session?: Partial<SessionOptions>
/**
* JSON Web Tokens are enabled by default if you have not specified an adapter.
* JSON Web Tokens are encrypted (JWE) by default. We recommend you keep this behaviour.
* * **Default value**: See the documentation page
* * **Required**: *No*
*
* [Documentation](https://next-auth.js.org/configuration/options#jwt)
*/
jwt?: Partial<JWTOptions>
/**
* Specify URLs to be used if you want to create custom sign in, sign out and error pages.
* Pages specified will override the corresponding built-in page.
* * **Default value**: `{}`
* * **Required**: *No*
*
* @example
*
* ```ts
* pages: {
* signIn: '/auth/signin',
* signOut: '/auth/signout',
* error: '/auth/error',
* verifyRequest: '/auth/verify-request',
* newUser: '/auth/new-user'
* }
* ```
*
* [Documentation](https://next-auth.js.org/configuration/options#pages) | [Pages documentation](https://next-auth.js.org/configuration/pages)
*/
pages?: Partial<PagesOptions>
/**
* Callbacks are asynchronous functions you can use to control what happens when an action is performed.
* Callbacks are *extremely powerful*, especially in scenarios involving JSON Web Tokens
* as they **allow you to implement access controls without a database** and to **integrate with external databases or APIs**.
* * **Default value**: See the Callbacks documentation
* * **Required**: *No*
*
* [Documentation](https://next-auth.js.org/configuration/options#callbacks) | [Callbacks documentation](https://next-auth.js.org/configuration/callbacks)
*/
callbacks?: Partial<CallbacksOptions>
/**
* Events are asynchronous functions that do not return a response, they are useful for audit logging.
* You can specify a handler for any of these events below - e.g. for debugging or to create an audit log.
* The content of the message object varies depending on the flow
* (e.g. OAuth or Email authentication flow, JWT or database sessions, etc),
* but typically contains a user object and/or contents of the JSON Web Token
* and other information relevant to the event.
* * **Default value**: `{}`
* * **Required**: *No*
*
* [Documentation](https://next-auth.js.org/configuration/options#events) | [Events documentation](https://next-auth.js.org/configuration/events)
*/
events?: Partial<EventCallbacks>
/**
* You can use the adapter option to pass in your database adapter.
*
* * **Required**: *No*
*
* [Documentation](https://next-auth.js.org/configuration/options#adapter) |
* [Adapters Overview](https://next-auth.js.org/adapters/overview)
*/
adapter?: Adapter
/**
* Set debug to true to enable debug messages for authentication and database operations.
* * **Default value**: `false`
* * **Required**: *No*
*
* - ⚠ If you added a custom `logger`, this setting is ignored.
*
* [Documentation](https://next-auth.js.org/configuration/options#debug) | [Logger documentation](https://next-auth.js.org/configuration/options#logger)
*/
debug?: boolean
/**
* Override any of the logger levels (`undefined` levels will use the built-in logger),
* and intercept logs in NextAuth. You can use this option to send NextAuth logs to a third-party logging service.
* * **Default value**: `console`
* * **Required**: *No*
*
* @example
*
* ```ts
* // /pages/api/auth/[...nextauth].js
* import log from "logging-service"
* export default NextAuth({
* logger: {
* error(code, ...message) {
* log.error(code, message)
* },
* warn(code, ...message) {
* log.warn(code, message)
* },
* debug(code, ...message) {
* log.debug(code, message)
* }
* }
* })
* ```
*
* - ⚠ When set, the `debug` option is ignored
*
* [Documentation](https://next-auth.js.org/configuration/options#logger) |
* [Debug documentation](https://next-auth.js.org/configuration/options#debug)
*/
logger?: Partial<LoggerInstance>
/**
* Changes the theme of pages.
* Set to `"light"` if you want to force pages to always be light.
* Set to `"dark"` if you want to force pages to always be dark.
* Set to `"auto"`, (or leave this option out)if you want the pages to follow the preferred system theme.
* * **Default value**: `"auto"`
* * **Required**: *No*
*
* [Documentation](https://next-auth.js.org/configuration/options#theme) | [Pages documentation]("https://next-auth.js.org/configuration/pages")
*/
theme?: Theme
/**
* When set to `true` then all cookies set by NextAuth.js will only be accessible from HTTPS URLs.
* This option defaults to `false` on URLs that start with `http://` (e.g. http://localhost:3000) for developer convenience.
* You can manually set this option to `false` to disable this security feature and allow cookies
* to be accessible from non-secured URLs (this is not recommended).
* * **Default value**: `true` for HTTPS and `false` for HTTP sites
* * **Required**: No
*
* [Documentation](https://next-auth.js.org/configuration/options#usesecurecookies)
*
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
* but **may have complex implications** or side effects.
* You should **try to avoid using advanced options** unless you are very comfortable using them.
*/
useSecureCookies?: boolean
/**
* You can override the default cookie names and options for any of the cookies used by NextAuth.js.
* You can specify one or more cookies with custom properties,
* but if you specify custom options for a cookie you must provide all the options for that cookie.
* If you use this feature, you will likely want to create conditional behavior
* to support setting different cookies policies in development and production builds,
* as you will be opting out of the built-in dynamic policy.
* * **Default value**: `{}`
* * **Required**: No
*
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
* but **may have complex implications** or side effects.
* You should **try to avoid using advanced options** unless you are very comfortable using them.
*
* [Documentation](https://next-auth.js.org/configuration/options#cookies) | [Usage example](https://next-auth.js.org/configuration/options#example)
*/
cookies?: Partial<CookiesOptions>
/**
* If set to `true`, NextAuth.js will use either the `x-forwarded-host` or `host` headers,
* instead of `NEXTAUTH_URL`
* Make sure that reading `x-forwarded-host` on your hosting platform can be trusted.
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
* but **may have complex implications** or side effects.
* You should **try to avoid using advanced options** unless you are very comfortable using them.
*
* @default Boolean(process.env.NEXTAUTH_URL ?? process.env.AUTH_TRUST_HOST ?? process.env.VERCEL)
*/
trustHost?: boolean
}

218
packages/core/src/jwt.ts Normal file
View File

@@ -0,0 +1,218 @@
/**
*
*
* This module contains functions and types
* to encode and decode {@link https://authjs.dev/concepts/session-strategies#jwt JWT}s
* issued and used by Auth.js.
*
* The JWT issued by Auth.js is _encrypted by default_, using the _A256GCM_ algorithm ({@link https://www.rfc-editor.org/rfc/rfc7516 JWE}).
* It uses the `AUTH_SECRET` environment variable to dervice a sufficient encryption key.
*
* :::info Note
* Auth.js JWTs are meant to be used by the same app that issued them.
* If you need JWT authentication for your third-party API, you should rely on your Identity Provider instead.
* :::
*
* ## Installation
*
* ```bash npm2yarn2pnpm
* npm install @auth/core
* ```
*
* You can then import this submodule from `@auth/core/jwt`.
*
* ## Usage
*
* :::warning Warning
* This module *will* be refactored/changed. We do not recommend relying on it right now.
* :::
*
*
* ## Resources
*
* - [What is a JWT session strategy](https://authjs.dev/concepts/session-strategies#jwt)
* - [RFC7519 - JSON Web Token (JWT)](https://www.rfc-editor.org/rfc/rfc7519)
*
* @module jwt
*/
import { hkdf } from "@panva/hkdf"
import { EncryptJWT, jwtDecrypt } from "jose"
import { SessionStore } from "./lib/cookie.js"
import { Awaitable } from "./types.js"
import type { LoggerInstance } from "./lib/utils/logger.js"
const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 // 30 days
const now = () => (Date.now() / 1000) | 0
/** Issues a JWT. By default, the JWT is encrypted using "A256GCM". */
export async function encode(params: JWTEncodeParams) {
const { token = {}, secret, maxAge = DEFAULT_MAX_AGE } = params
const encryptionSecret = await getDerivedEncryptionKey(secret)
return await new EncryptJWT(token)
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
.setIssuedAt()
.setExpirationTime(now() + maxAge)
.setJti(crypto.randomUUID())
.encrypt(encryptionSecret)
}
/** Decodes a Auth.js issued JWT. */
export async function decode(params: JWTDecodeParams): Promise<JWT | null> {
const { token, secret } = params
if (!token) return null
const encryptionSecret = await getDerivedEncryptionKey(secret)
const { payload } = await jwtDecrypt(token, encryptionSecret, {
clockTolerance: 15,
})
return payload
}
export interface GetTokenParams<R extends boolean = false> {
/** The request containing the JWT either in the cookies or in the `Authorization` header. */
req:
| Request
| { cookies: Record<string, string>; headers: Record<string, string> }
/**
* Use secure prefix for cookie name, unless URL in `NEXTAUTH_URL` is http://
* or not set (e.g. development or test instance) case use unprefixed name
*/
secureCookie?: boolean
/** If the JWT is in the cookie, what name `getToken()` should look for. */
cookieName?: string
/**
* `getToken()` will return the raw JWT if this is set to `true`
*
* @default false
*/
raw?: R
/**
* The same `secret` used in the `NextAuth` configuration.
* Defaults to the `AUTH_SECRET` environment variable.
*/
secret?: string
decode?: JWTOptions["decode"]
logger?: LoggerInstance | Console
}
/**
* Takes a Auth.js request (`req`) and returns either the Auth.js issued JWT's payload,
* or the raw JWT string. We look for the JWT in the either the cookies, or the `Authorization` header.
* [Documentation](https://authjs.dev/guides/basics/securing-pages-and-api-routes#using-gettoken)
*/
export async function getToken<R extends boolean = false>(
params: GetTokenParams<R>
): Promise<R extends true ? string : JWT | null> {
const {
req,
secureCookie = process.env.NEXTAUTH_URL?.startsWith("https://") ??
!!process.env.VERCEL,
cookieName = secureCookie
? "__Secure-next-auth.session-token"
: "next-auth.session-token",
raw,
decode: _decode = decode,
logger = console,
secret = process.env.AUTH_SECRET,
} = params
if (!req) throw new Error("Must pass `req` to JWT getToken()")
const sessionStore = new SessionStore(
{ name: cookieName, options: { secure: secureCookie } },
// @ts-expect-error
{ cookies: req.cookies, headers: req.headers },
logger
)
let token = sessionStore.value
const authorizationHeader =
req.headers instanceof Headers
? req.headers.get("authorization")
: req.headers.authorization
if (!token && authorizationHeader?.split(" ")[0] === "Bearer") {
const urlEncodedToken = authorizationHeader.split(" ")[1]
token = decodeURIComponent(urlEncodedToken)
}
// @ts-expect-error
if (!token) return null
// @ts-expect-error
if (raw) return token
try {
// @ts-expect-error
return await _decode({ token, secret })
} catch {
// @ts-expect-error
return null
}
}
async function getDerivedEncryptionKey(secret: string) {
return await hkdf(
"sha256",
secret,
"",
"Auth.js Generated Encryption Key",
32
)
}
export interface DefaultJWT extends Record<string, unknown> {
name?: string | null
email?: string | null
picture?: string | null
sub?: string
}
/**
* Returned by the `jwt` callback and `getToken`, when using JWT sessions
*
* [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) | [`getToken`](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#using-gettoken)
*/
export interface JWT extends Record<string, unknown>, DefaultJWT {}
export interface JWTEncodeParams {
/** The JWT payload. */
token?: JWT
/** The secret used to encode the Auth.js issued JWT. */
secret: string
/**
* The maximum age of the Auth.js issued JWT in seconds.
*
* @default 30 * 24 * 30 * 60 // 30 days
*/
maxAge?: number
}
export interface JWTDecodeParams {
/** The Auth.js issued JWT to be decoded */
token?: string
/** The secret used to decode the Auth.js issued JWT. */
secret: string
}
export interface JWTOptions {
/**
* The secret used to encode/decode the Auth.js issued JWT.
*
* @deprecated Set the `AUTH_SECRET` environment vairable or
* use the top-level `secret` option instead
*/
secret: string
/**
* The maximum age of the Auth.js issued JWT in seconds.
*
* @default 30 * 24 * 30 * 60 // 30 days
*/
maxAge: number
/** Override this method to control the Auth.js issued JWT encoding. */
encode: (params: JWTEncodeParams) => Awaitable<string>
/** Override this method to control the Auth.js issued JWT decoding. */
decode: (params: JWTDecodeParams) => Awaitable<JWT | null>
}

View File

@@ -1,133 +0,0 @@
import { EncryptJWT, jwtDecrypt } from "jose"
import { hkdf } from "@panva/hkdf"
import { SessionStore } from "../lib/cookie.js"
import type {
JWT,
JWTDecodeParams,
JWTEncodeParams,
JWTOptions,
} from "./types.js"
import type { LoggerInstance } from "../index.js"
export * from "./types.js"
const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 // 30 days
const now = () => (Date.now() / 1000) | 0
/** Issues a JWT. By default, the JWT is encrypted using "A256GCM". */
export async function encode(params: JWTEncodeParams) {
const { token = {}, secret, maxAge = DEFAULT_MAX_AGE } = params
const encryptionSecret = await getDerivedEncryptionKey(secret)
return await new EncryptJWT(token)
.setProtectedHeader({ alg: "dir", enc: "A256GCM" })
.setIssuedAt()
.setExpirationTime(now() + maxAge)
.setJti(crypto.randomUUID())
.encrypt(encryptionSecret)
}
/** Decodes a NextAuth.js issued JWT. */
export async function decode(params: JWTDecodeParams): Promise<JWT | null> {
const { token, secret } = params
if (!token) return null
const encryptionSecret = await getDerivedEncryptionKey(secret)
const { payload } = await jwtDecrypt(token, encryptionSecret, {
clockTolerance: 15,
})
return payload
}
export interface GetTokenParams<R extends boolean = false> {
/** The request containing the JWT either in the cookies or in the `Authorization` header. */
req:
| Request
| { cookies: Record<string, string>; headers: Record<string, string> }
/**
* Use secure prefix for cookie name, unless URL in `NEXTAUTH_URL` is http://
* or not set (e.g. development or test instance) case use unprefixed name
*/
secureCookie?: boolean
/** If the JWT is in the cookie, what name `getToken()` should look for. */
cookieName?: string
/**
* `getToken()` will return the raw JWT if this is set to `true`
*
* @default false
*/
raw?: R
/**
* The same `secret` used in the `NextAuth` configuration.
* Defaults to the `NEXTAUTH_SECRET` environment variable.
*/
secret?: string
decode?: JWTOptions["decode"]
logger?: LoggerInstance | Console
}
/**
* Takes a NextAuth.js request (`req`) and returns either the NextAuth.js issued JWT's payload,
* or the raw JWT string. We look for the JWT in the either the cookies, or the `Authorization` header.
* [Documentation](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#using-gettoken)
*/
export async function getToken<R extends boolean = false>(
params: GetTokenParams<R>
): Promise<R extends true ? string : JWT | null> {
const {
req,
secureCookie = process.env.NEXTAUTH_URL?.startsWith("https://") ??
!!process.env.VERCEL,
cookieName = secureCookie
? "__Secure-next-auth.session-token"
: "next-auth.session-token",
raw,
decode: _decode = decode,
logger = console,
secret = process.env.NEXTAUTH_SECRET,
} = params
if (!req) throw new Error("Must pass `req` to JWT getToken()")
const sessionStore = new SessionStore(
{ name: cookieName, options: { secure: secureCookie } },
// @ts-expect-error
{ cookies: req.cookies, headers: req.headers },
logger
)
let token = sessionStore.value
const authorizationHeader =
req.headers instanceof Headers
? req.headers.get("authorization")
: req.headers.authorization
if (!token && authorizationHeader?.split(" ")[0] === "Bearer") {
const urlEncodedToken = authorizationHeader.split(" ")[1]
token = decodeURIComponent(urlEncodedToken)
}
// @ts-expect-error
if (!token) return null
// @ts-expect-error
if (raw) return token
try {
// @ts-expect-error
return await _decode({ token, secret })
} catch {
// @ts-expect-error
return null
}
}
async function getDerivedEncryptionKey(secret: string | Buffer) {
return await hkdf(
"sha256",
secret,
"",
"NextAuth.js Generated Encryption Key",
32
)
}

View File

@@ -1,57 +0,0 @@
import type { Awaitable } from "../index.js"
export interface DefaultJWT extends Record<string, unknown> {
name?: string | null
email?: string | null
picture?: string | null
sub?: string
}
/**
* Returned by the `jwt` callback and `getToken`, when using JWT sessions
*
* [`jwt` callback](https://next-auth.js.org/configuration/callbacks#jwt-callback) | [`getToken`](https://next-auth.js.org/tutorials/securing-pages-and-api-routes#using-gettoken)
*/
export interface JWT extends Record<string, unknown>, DefaultJWT {}
export interface JWTEncodeParams {
/** The JWT payload. */
token?: JWT
/** The secret used to encode the NextAuth.js issued JWT. */
secret: string | Buffer
/**
* The maximum age of the NextAuth.js issued JWT in seconds.
*
* @default 30 * 24 * 30 * 60 // 30 days
*/
maxAge?: number
}
export interface JWTDecodeParams {
/** The NextAuth.js issued JWT to be decoded */
token?: string
/** The secret used to decode the NextAuth.js issued JWT. */
secret: string | Buffer
}
export interface JWTOptions {
/**
* The secret used to encode/decode the NextAuth.js issued JWT.
*
* @deprecated Set the `NEXTAUTH_SECRET` environment vairable or
* use the top-level `secret` option instead
*/
secret: string
/**
* The maximum age of the NextAuth.js issued JWT in seconds.
*
* @default 30 * 24 * 30 * 60 // 30 days
*/
maxAge: number
/** Override this method to control the NextAuth.js issued JWT encoding. */
encode: (params: JWTEncodeParams) => Awaitable<string>
/** Override this method to control the NextAuth.js issued JWT decoding. */
decode: (params: JWTDecodeParams) => Awaitable<JWT | null>
}
export type Secret = string | Buffer

View File

@@ -1,27 +1,25 @@
import { defaultCookies } from "./cookie.js"
import {
InvalidCallbackUrl,
InvalidEndpoints,
MissingAdapter,
MissingAdapterMethods,
MissingAPIRoute,
MissingAuthorize,
MissingSecret,
UnsupportedStrategy,
} from "./errors.js"
import { defaultCookies } from "./cookie.js"
UntrustedHost,
} from "../errors.js"
import type { AuthOptions, RequestInternal } from "../index.js"
import type { AuthConfig, RequestInternal } from "../types.js"
import type { WarningCode } from "./utils/logger.js"
type ConfigError =
| InvalidCallbackUrl
| InvalidEndpoints
| MissingAdapter
| MissingAdapterMethods
| MissingAPIRoute
| MissingAuthorize
| MissingSecret
| InvalidCallbackUrl
| UnsupportedStrategy
| InvalidEndpoints
| UnsupportedStrategy
let warned = false
@@ -39,34 +37,25 @@ function isValidHttpUrl(url: string, baseUrl: string) {
/**
* Verify that the user configured Auth.js correctly.
* Good place to mention deprecations as well.
*
* REVIEW: Make some of these and corresponding docs less Next.js specific?
*/
export function assertConfig(params: {
options: AuthOptions
req: RequestInternal
}): ConfigError | WarningCode[] {
const { options, req } = params
const { url } = req
export function assertConfig(
request: RequestInternal,
options: AuthConfig
): ConfigError | WarningCode[] {
const { url } = request
const warnings: WarningCode[] = []
if (!warned) {
if (!url.origin) warnings.push("NEXTAUTH_URL")
if (options.debug) warnings.push("DEBUG_ENABLED")
if (!warned && options.debug) warnings.push("debug_enabled")
if (!options.trustHost) {
return new UntrustedHost(`Host must be trusted. URL was: ${request.url}`)
}
if (!options.secret) {
return new MissingSecret("Please define a `secret`.")
}
// req.query isn't defined when asserting `unstable_getServerSession` for example
if (!req.query?.nextauth && !req.action) {
return new MissingAPIRoute(
"Cannot find [...nextauth].{js,ts} in `/pages/api/auth`. Make sure the filename is written correctly."
)
}
const callbackUrlParam = req.query?.callbackUrl as string | undefined
const callbackUrlParam = request.query?.callbackUrl as string | undefined
if (callbackUrlParam && !isValidHttpUrl(callbackUrlParam, url.origin)) {
return new InvalidCallbackUrl(
@@ -78,7 +67,9 @@ export function assertConfig(params: {
options.useSecureCookies ?? url.protocol === "https://"
)
const callbackUrlCookie =
req.cookies?.[options.cookies?.callbackUrl?.name ?? defaultCallbackUrl.name]
request.cookies?.[
options.cookies?.callbackUrl?.name ?? defaultCallbackUrl.name
]
if (callbackUrlCookie && !isValidHttpUrl(callbackUrlCookie, url.origin)) {
return new InvalidCallbackUrl(

View File

@@ -1,9 +1,9 @@
import { AccountNotLinkedError } from "./errors.js"
import { AccountNotLinked } from "../errors.js"
import { fromDate } from "./utils/date.js"
import type { Account, InternalOptions, User } from "../index.js"
import type { AdapterSession, AdapterUser } from "../adapters.js"
import type { JWT } from "../jwt/index.js"
import type { Account, InternalOptions, User } from "../types.js"
import type { JWT } from "../jwt.js"
import type { OAuthConfig } from "../providers/index.js"
import type { SessionToken } from "./cookie.js"
@@ -19,13 +19,12 @@ import type { SessionToken } from "./cookie.js"
* done prior to this handler being called to avoid additonal complexity in this
* handler.
*/
export default async function callbackHandler(params: {
sessionToken?: SessionToken
profile: User | AdapterUser | { email: string }
account: Account | null
export async function handleLogin(
sessionToken: SessionToken,
_profile: User | AdapterUser | { email: string },
account: Account | null,
options: InternalOptions
}) {
const { sessionToken, profile: _profile, account, options } = params
) {
// Input validation
if (!account?.providerAccountId || !account.type)
throw new Error("Missing or invalid provider account")
@@ -133,7 +132,7 @@ export default async function callbackHandler(params: {
// If the user is currently signed in, but the new account they are signing in
// with is already associated with another user, then we cannot link them
// and need to return an error.
throw new AccountNotLinkedError(
throw new AccountNotLinked(
"The account is already associated with another user"
)
}
@@ -193,7 +192,7 @@ export default async function callbackHandler(params: {
// We don't want to have two accounts with the same email address, and we don't
// want to link them in case it's not safe to do so, so instead we prompt the user
// to sign in via email to verify their identity and then link the accounts.
throw new AccountNotLinkedError(
throw new AccountNotLinked(
"Another account already exists with the same e-mail address"
)
}

Some files were not shown because too many files have changed in this diff Show More