Compare commits

..

316 Commits

Author SHA1 Message Date
Balázs Orbán
82d16e6ac4 feat: allow to return string in signIn callback (#1019) 2020-12-31 21:55:30 +01:00
Balázs Orbán
bf7efbc252 docs: Remove unnecessary promises (#915) 2020-12-31 12:16:03 +01:00
Florian Michaut
b9862b86b5 feat(db): make Fauna DB collections & indexes configurable (#968)
* Add collections & indexes overrides for Fauna DB

* Fix the name of the verification token index

Co-authored-by: Florian Michaut <florian@coding-days.com>
2020-12-31 10:26:26 +01:00
Ben West
9b579b5fcb Change image to text from varchar (#777)
Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-31 06:25:10 +01:00
Yuma Matsune
abcf845ebf fix(adapter): use findOne for typeorm (#1014) 2020-12-30 21:08:09 +01:00
Balázs Orbán
ee398d1acd fix: treat user.id as optional param (#1010) 2020-12-30 14:23:59 +01:00
Balázs Orbán
c31cbbcd30 chore(release): trigger release on docs type 2020-12-29 23:02:07 +01:00
Balázs Orbán
1728f50952 chore(release): delete old workflow 2020-12-29 22:51:00 +01:00
Junior Vidotti
2eb17cba1a docs(database): add mssql indexes in docs, fix typos (#925)
* added mssql indexes in docs, fixed typo

* docs: fix typo in www/docs/schemas/mssql.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2020-12-29 22:49:38 +01:00
Balazs Orban
15196ee3d1 chore(release): change semantic-release/git to semantic-release/github 2020-12-29 22:42:32 +01:00
Balázs Orbán
aa4439e182 feat: add semantic-release (#920) 2020-12-29 22:00:08 +01:00
Nico Domino
66ec439b4d Update README.md 2020-12-26 01:56:20 +01:00
Nico Domino
a49068643c Update README.md 2020-12-25 20:21:09 +01:00
Paul Kenneth Kent
1a315fe5ac feat: add strava provider (#986)
* Add Strava as a provider

* Add documentation for Strava provider

* Fix lint errors

Co-authored-by: Paul Kenneth Kent <paul@ventureharbour.com>
2020-12-23 19:02:36 +01:00
Nico Domino
652ac7de35 Update README.md
Updated the readme to include the projects logo, fixed some typos, and added license info and contributor image.
2020-12-22 00:34:31 +01:00
Balázs Orbán
28ce71d99e chore: hide comments from pull request template 2020-12-17 18:25:17 +01:00
pkabore
28e2afbd3a docs: Correcting a typo. "available" Line 70 (#965)
* chore: use stale label, instead of wontfix

* chore: add link to issue explaining stalebot

* chore: fix typo in stalebot comment

* chore: run build GitHub Action on canary also

* chore: run build GitHub Actions on canary as well

* chore: add reproduction section to questions

* feat(provider): Add Azure Active Directory B2C (#809)

* add provider: Microsoft

* documentation

* support no tenant setup

* fix code style

* chore: rename Microsoft provider to AzureADB2C

* chore: alphabetical order in providers/index

* Revert "feat(provider): Add Azure Active Directory B2C (#809)" (#919)

This reverts commit 6e6a24a7af.

* chore: add myself to the contributors list 🙈

* Correcting a typo. "available" Line 70

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Vladimir Evdokimov <evdokimov.vladimir@gmail.com>
2020-12-17 18:23:58 +01:00
pkabore
eb828d42f8 docs: We have twice the word "side" (#964)
* chore: use stale label, instead of wontfix

* chore: add link to issue explaining stalebot

* chore: fix typo in stalebot comment

* chore: run build GitHub Action on canary also

* chore: run build GitHub Actions on canary as well

* chore: add reproduction section to questions

* feat(provider): Add Azure Active Directory B2C (#809)

* add provider: Microsoft

* documentation

* support no tenant setup

* fix code style

* chore: rename Microsoft provider to AzureADB2C

* chore: alphabetical order in providers/index

* Revert "feat(provider): Add Azure Active Directory B2C (#809)" (#919)

This reverts commit 6e6a24a7af.

* chore: add myself to the contributors list 🙈

* We have twice the word "side"

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Vladimir Evdokimov <evdokimov.vladimir@gmail.com>
2020-12-17 18:21:31 +01:00
imgregduh
d03504c6ef docs: fix typo Adapater -> Adapter (#960)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Vladimir Evdokimov <evdokimov.vladimir@gmail.com>
2020-12-16 09:18:53 +01:00
dependabot[bot]
8827950f12 chore(deps): Bump ini from 1.3.5 to 1.3.8 in /www (#953)
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.8.
- [Release notes](https://github.com/isaacs/ini/releases)
- [Commits](https://github.com/isaacs/ini/compare/v1.3.5...v1.3.8)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-12-13 02:33:08 +01:00
Jakub Naskręski
4f89d74d78 feat: Display error if no [...nextauth].js found (#678)
* Display error if no [...nextauth].js found

fixes #647

* Log the error and describe it inside errors.md

Co-authored-by: Balázs Orbán <info@balazsorban.com>
2020-12-13 02:28:09 +01:00
Haldun Anil
be159b1b18 docs: fix incorrect references in cypress docs (#932)
* chore: use stale label, instead of wontfix

* chore: add link to issue explaining stalebot

* chore: fix typo in stalebot comment

* chore: run build GitHub Action on canary also

* chore: run build GitHub Actions on canary as well

* chore: add reproduction section to questions

* feat(provider): Add Azure Active Directory B2C (#809)

* add provider: Microsoft

* documentation

* support no tenant setup

* fix code style

* chore: rename Microsoft provider to AzureADB2C

* chore: alphabetical order in providers/index

* Revert "feat(provider): Add Azure Active Directory B2C (#809)" (#919)

This reverts commit 6e6a24a7af.

* chore: add myself to the contributors list 🙈

* docs: fix incorrect references in cypress docs

* chore: add additional docs clarification

Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Vladimir Evdokimov <evdokimov.vladimir@gmail.com>
2020-12-09 17:07:12 +01:00
Luke Lau
19f2664a78 feat: Store user ID in sub claim of default JWT (#784)
This allows us to check if the user is signed in when using JWTs

Part of #625
2020-12-08 18:53:47 +01:00
Balázs Orbán
bd86e7c7c7 chore: reword PR template 2020-12-08 00:23:40 +01:00
Balázs Orbán
7ce37c71d7 chore: create PULL_REQUEST_TEMPLATE.md 2020-12-08 00:12:44 +01:00
Balázs Orbán
3c3a4d2c4f chore: add note about conveting questions to discussions 2020-12-07 17:09:53 +01:00
Balázs Orbán
5fcf80ce81 chore: disallow issues without template 2020-12-07 17:08:51 +01:00
dependabot[bot]
7a4534a6b1 chore(dep): Bump highlight.js from 9.18.1 to 9.18.5 (#880)
Bumps [highlight.js](https://github.com/highlightjs/highlight.js) from 9.18.1 to 9.18.5.
- [Release notes](https://github.com/highlightjs/highlight.js/releases)
- [Changelog](https://github.com/highlightjs/highlight.js/blob/9.18.5/CHANGES.md)
- [Commits](https://github.com/highlightjs/highlight.js/compare/9.18.1...9.18.5)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-07 10:48:01 +01:00
Kristóf Poduszló
ddaa830e10 refactor(db): update Prisma calls to support 2.12+ (#881)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-07 00:44:22 +01:00
Cathy Chen
9dbd372f08 update(provider): Update Slack provider to use V2 OAuth endpoints (#895)
* Update Slack to v2 authorize urls, option for additional authorize params
* acessTokenGetter + documentation
2020-12-07 00:31:32 +01:00
Vladimir Evdokimov
dde908b54a feat(provider): Add Azure Active Directory B2C (#921)
* add provider: Microsoft

* documentation

* support no tenant setup

* fix code style

* chore: rename Microsoft provider to AzureADB2C

* chore: alphabetical order in providers/index

* doc: add provider to FAQ
2020-12-06 22:57:54 +01:00
Joe Bell
831c59dd5c feat: add foursquare (#584) 2020-12-06 20:56:00 +01:00
RobertCraigie
3abb0c8223 feat(provider): Add Bungie (#589)
* Add Bungie provider

* Use absolute URL for images

* Correct image URL and use consistent formatting

Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-06 20:34:25 +01:00
dependabot[bot]
8c56e13577 Bump next from 9.5.3 to 9.5.4 in /test/docker/app (#759)
Bumps [next](https://github.com/vercel/next.js) from 9.5.3 to 9.5.4.
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v9.5.3...v9.5.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-06 20:31:09 +01:00
Joost Jansky
12d7856640 feat(provider): add netlify (#555)
Co-authored-by: styxlab <cws@DE01WP777.scdom.net>
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2020-12-06 20:25:14 +01:00
Joseph Vaughan
4635113133 add(db): Add support for Fauna DB (#708)
* Add support for Fauna DB

* Add integration tests

Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-06 20:19:14 +01:00
Fabrizio Ruggeri
1aea187d5e Include callbackUrl in newUser page (#790)
* Include callbackUrl in newUser page

* Update src/server/routes/callback.js

Co-authored-by: Iain Collins <me@iaincollins.com>

* Update src/server/routes/callback.js

Co-authored-by: Iain Collins <me@iaincollins.com>

Co-authored-by: Iain Collins <me@iaincollins.com>
Co-authored-by: Nico Domino <yo@ndo.dev>
2020-12-06 19:50:41 +01:00
Nico Domino
47b8788249 WIP: Update Docusaurus + Site dependencies (#802)
* update: deps

* fix: broken link

* fix: search upgrade change
2020-12-06 19:47:33 +01:00
Aymeric
06a160aa0c Fix for Reddit Authentication (#866)
* Fixed Reddit Authentication

* updated fix for build test

* updated buffer to avoid deprecation message

* Updated for passing tests
2020-12-06 19:30:16 +01:00
Manish Chiniwalar
93f4dc0622 docs: Update default ports for support Databases (#839)
https://next-auth.js.org/configuration/databases
2020-12-06 19:17:47 +01:00
Balázs Orbán
6088a05204 Merge main into canary (#917)
* chore: use stale label, instead of wontfix

* chore: add link to issue explaining stalebot

* chore: fix typo in stalebot comment

* chore: run build GitHub Action on canary also

* chore: run build GitHub Actions on canary as well

* chore: add reproduction section to questions
2020-12-06 10:24:28 +01:00
Balázs Orbán
d242d72106 fix(provider): handle no profile image for Spotify (#914)
* chore(deps): upgrade "standard"

* style(lint): run lint fix

* fix(provider): optional chain Spotify provider profile img
2020-12-05 18:55:12 +01:00
Alan Ray
766874dbd8 fix: update Okta routes (#763)
the current routing for the Okta provider does not follow the standard
set by Okta, and as such doesn't allow for custom subdomains. this
update amends the routes to allow for customer subdomains, and also
aligns next-auth with Okta's documentation.
2020-12-05 11:33:13 +01:00
Daggy1234
0b7343702f fix: ensure Images are produced for discord (#734) 2020-12-05 11:28:16 +01:00
Josh Padnick
0327b9049a fix: update nodemailer version in response to CVE. (#860)
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-7769 reports a high-severity issue with the current version of nodemailer. This should be merged and released right away if possible.
2020-12-05 11:26:04 +01:00
Pauldic
2ee460de00 docs: fix typo in callbacks.md (#815)
This is a simple typographical error changed accesed to accessed
2020-12-05 11:24:04 +01:00
Joshua K. Martinez
c8de34d003 docs: fix discord example code (#850) 2020-12-05 11:23:07 +01:00
James Perkins
d15572074f docs: update for Now to Vercel (#847)
Vercel archived their now packages a while back, so you can use vercel env pull to pull in the .env
2020-12-05 11:20:48 +01:00
Luke Lau
7b6fd818a5 feat: allow react 17 as a peer dependency (#819)
Co-authored-by: Balázs Orbán <info@balazsorban.com>
2020-12-05 11:18:36 +01:00
Balázs Orbán
e031591468 feat: simplify NextAuth instantiation (#911) 2020-12-05 11:11:08 +01:00
Balázs Orbán
341fae28d4 Revert "feat: simplify NextAuth instantiation" (#910)
This reverts commit b86ffa5dd5.
2020-12-05 10:39:03 +01:00
Balázs Orbán
b86ffa5dd5 feat: simplify NextAuth instantiation (#867) 2020-12-05 10:34:32 +01:00
Damien Guard
5415a9c3ab docs: remove redundant 3rd arg to sessions example (#874)
There is no third argument as per 8115a7c66c/src/server/routes/session.js (L82)
2020-12-05 10:15:28 +01:00
sankara
dc516e8be8 docs: fix typo in options.md (#873) 2020-12-05 10:13:43 +01:00
sAy
29a0d9d295 docs: update API docs about server-side getProviders (#879) 2020-12-05 10:12:17 +01:00
Balázs Orbán
5f5174f6e2 refactor: define _getSession in useEffect scope (#724) 2020-12-05 10:00:30 +01:00
Dennis Morello
424b4ee257 Update apple.md
Fixed a typo
2020-12-05 09:57:29 +01:00
Balázs Orbán
545a7e752e feat: forward auth params from signin to provider (#823) 2020-12-05 09:54:27 +01:00
Balázs Orbán
c564b84182 chore: add stalebot configuration 2020-12-05 09:37:27 +01:00
Siddharth Sharma
0db233d208 Add Sign in With Apple Tutorial (#896)
Co-authored-by: Iain Collins <me@iaincollins.com>
2020-12-02 11:13:53 +00:00
Yana Agun Siswanto
5126f4e342 CONTRIBUTING.md: Fix spelling and other issue (#810)
Co-authored-by: Iain Collins <me@iaincollins.com>
2020-10-30 17:09:42 +00:00
Michael McQuade
e09dfc6a7f Change definitively typed to definitely typed (#813) 2020-10-30 17:08:12 +00:00
Iain Collins
ccfa1d55bb Update errors.md 2020-10-30 14:18:25 +00:00
ndom91
d7dc7b0753 add: ndom91 dev.to tutorial 2020-10-27 15:39:30 +01:00
Alex Vilchis
0407e130c4 Fix grammar (#801) 2020-10-27 10:12:07 +00:00
Kristóf Poduszló
64084d634b fix: capitalization of errors in url params (#795) 2020-10-24 01:55:01 +01:00
Iain Collins
438a737837 Update providers.md 2020-10-20 11:54:19 +01:00
Iain Collins
a482a64f10 Update providers.md 2020-10-19 16:29:09 +01:00
Iain Collins
2227d34725 Update documentation (#786)
* Improved homepage and getting started guide
* Improved experience viewing docs on mobile devices
* Fixed typos
2020-10-19 14:19:09 +01:00
Jesus Castro (Tony)
9c6ef951a1 Typo: retuning should be returning
It ain't much but its honest work
2020-10-08 15:45:41 +01:00
Kristóf Poduszló
01c897f23e Correct typo of 'column' in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
ea65d87d07 Correct tip about adapters in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
8d1e479d12 Correct mistakenly duplicated word in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
435b630849 Correct missing word in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
773c74a756 Correct a typo in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
6867bc92c8 Correct two typos of the same word in the docs 2020-10-07 07:48:48 +01:00
Kristóf Poduszló
eb6a4c46d9 Correct a typo in the docs 2020-10-06 20:50:28 +01:00
Iain Collins
cd3d2a138b Update tutorials and explainers 2020-10-06 13:50:42 +01:00
Iain Collins
0c356456bb Minor style changes 2020-10-06 13:50:42 +01:00
Iain Collins
6d44a34f7d Reduce image size 2020-10-06 13:50:42 +01:00
Iain Collins
7bda639361 Update branding (icons, homepage) 2020-10-06 13:50:42 +01:00
Francis Udeji
40e453076e Remove arrow syntax
Remove arrow syntax from regular function declaration
2020-10-02 17:34:47 +01:00
Daniel Jahodka
e065552784 Fix missing response_type=code in battlenet
Battle net's /oauth/authorize requires response_type query parameter. For authorization, this must be set to code.
2020-09-30 00:34:00 +01:00
Lluis Agusti
a3104a009c docs(readme): mention Typescript support 2020-09-25 17:38:23 +01:00
Iain Collins
e9eb6bc57e Add conditional to integration test workflow 2020-09-25 17:36:33 +01:00
Blocksmith
95e31b46af Update testing-with-cypress.md (#680)
misspelling depency cypress-social-logins
2020-09-24 13:52:50 +01:00
Jimmy Merritello
d5e70323f0 Update documentation for getProviders 2020-09-24 13:51:29 +01:00
S. Suzuki
4e4d1eac28 Update links to Slack documentation 2020-09-24 13:47:19 +01:00
Iain Collins
15316f069e Update FAQ to address automatic account linking (#702) 2020-09-24 13:45:45 +01:00
Wédney Yuri
e6995d21cd Update mongodb.md (#673)
Fix typo: MonogDB => MongoDB

Co-authored-by: Lori Karikari <lori.karikari@gmail.com>
2020-09-14 11:08:27 +02:00
Lance Hasson
433f096a63 jst -> jwt (#668)
Co-authored-by: Lori Karikari <lori.karikari@gmail.com>
2020-09-14 11:06:13 +02:00
Lance Hasson
9f487593fa add missing comma in type object (#669) 2020-09-14 11:04:16 +02:00
Matthieu
65caaa6c4c [providers]: Add Atlassian (#664)
* Atlassian provider

* rollback indentation

* fix alphabetical order

* add missing entry in menu sidebar
2020-09-12 19:49:21 +02:00
Iain Collins
0adfba8c5c Improve Puppeteer configuration (#658)
* Centralises configuration for Puppeteer used in tests to make it easier to maintain.
* Adds support for running tests on ARM, so we can use Raspberry Pi test runners off the cloud to get around block lists.
* Includes improved stealth mode to avoid detection which breaks integration tests.
2020-09-11 01:41:02 +01:00
Ugo Onali
2f0f738e2e Fix typo in Prisma adapter doc (#629)
Co-authored-by: Iain Collins <me@iaincollins.com>
2020-09-08 17:26:40 +01:00
Iain Collins
1777a87be3 Increase slow times for integration tests to 5 seconds
This seems like a reasonable theshold for these  integration tests.
2020-09-08 13:12:19 +01:00
Iain Collins
e94fd3b484 Fix typo in package.json 2020-09-08 12:55:26 +01:00
Iain Collins
3b40335202 Add full end-to-end integration tests
Full end-to-end integration tests for Twitter (OAuth 1) and GitHub (OAuth 2) using Puppeteer and Mocha.

This replaces Cypress tests due to issues with Cypress not being able to run tests against external URLs, which we need for our integration tests.

The integration test runner is hosted outside of GitHub Actions (it cannot be hosted by GitHub or on AWS due to IP access controls placed on sign in by providers like Twitter and GitHub) and so the integration tests may not pass if the test runner is offline. If this happens, tests can be re-run later when the test runner is available.

See Pull Request #641 for details.
2020-09-08 12:41:30 +01:00
John
6d63b74db9 Update faq.md 2020-09-07 11:20:55 +01:00
dependabot[bot]
eb26722833 Bump bl from 2.2.0 to 2.2.1
Bumps [bl](https://github.com/rvagg/bl) from 2.2.0 to 2.2.1.
- [Release notes](https://github.com/rvagg/bl/releases)
- [Commits](https://github.com/rvagg/bl/compare/v2.2.0...v2.2.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-04 11:29:48 +01:00
Iain Collins
4937047d19 Update GitHub workflows 2020-09-03 23:47:40 +01:00
Iain Collins
4305964864 Fix linting errors & ignore Cypress tests for now 2020-09-03 23:47:40 +01:00
Iain Collins
91d93fb8fd Integrate Cypress with Docker and GitHub Actions 2020-09-03 23:47:40 +01:00
Iain Collins
e2e28fcfd0 Update package-lock.json 2020-09-03 23:47:40 +01:00
Iain Collins
66afc69a57 Update workflow to run test app 2020-09-03 23:47:40 +01:00
Iain Collins
3046691119 Pass env vars through to test app
Using env vars for options we want to test means we can stop and restart the app to test different options without needing to rebuild the image.
2020-09-03 23:47:40 +01:00
Iain Collins
88b87a53ff Fix linter errors 2020-09-03 23:47:40 +01:00
Iain Collins
f1ae26efb6 Add Dockerfile to run build inside a container
Adds commands to start/rebuild/stop a Docker image of a sample Next.js app that loads the latest build of NextAuth.js from the current directory.

* `npm run test:app:start`
* `npm run test:app:rebuild`
* `npm run test:app:stop`

It is intended for further development for automated testing.

### About the build process

* The Dockerfile uses a multi-stage build process to optimise build performance, but the nature of the process is slow.
* Build times vary depending on computer speed and internet connection.
* Inital build times are slow (it may take 10 minutes or more).
* Subsequent builds on the same computer should be faster (1 minute or less).
* To ensure the package.json is valid, modules required in the next-auth package.json file are re-downloaded* on every build.
* A Docker compose file is used to allow us to extend the test app to run it again multiple databases.

Subsequent updates may look to improve performance, but it's important checks like checking package.json is valid and running the build in isolation are performed.
2020-09-03 23:47:40 +01:00
Matheus Calegaro
ba83685a86 docs(email): fix typo (#628) 2020-09-03 13:23:49 +01:00
Francis Udeji
d514733f13 Remove arrow syntax from examples on pages docs 2020-09-03 11:45:40 +01:00
Jefferson Bledsoe
15cd608b19 Add initial end-to-end tests (#298)
* Add cypress, testing-library/cypress and server dev helper to package dev dependencies

* Add initial signin test and placeholder cypress files

* Add initial signout tests

* Add initial verify-request test

* Move page-only tests into a 'pages' directory

* Add an invalid email signup workflow test

* Use home-page sign in button for email workflow

* Some tests to check that clicking the button takes the user to the correct OAuth page (warning: fragile!)

* Add a couple of npm scripts to make it easier to run/ developer e2e tests

Co-authored-by: Iain Collins <me@iaincollins.com>
2020-09-03 11:41:11 +01:00
Anish
08d7f5d778 Set Discord to Prompt = None (#605)
* Update discord.js

* Migrating from discordapp.com to discord.com
2020-09-01 10:42:10 +01:00
Francis Udeji
a2ba7e9229 Fix typo in options.md file 2020-09-01 10:40:42 +01:00
Iain Collins
7c71a15699 Fix getUserByProviderAccountId in Prisma adapter
Resolves #559
2020-09-01 10:39:38 +01:00
Mr D
351b804606 Adding 'nextauth' user as sysadmin. 2020-08-31 17:55:03 +01:00
Mr D
8f0501b7fe standardize the behaviour of the Docker images 2020-08-31 17:55:03 +01:00
Josh Pollock
73d21e66dd adjust URL for warnings in logger to match docs. (#593)
Fixes #592
2020-08-29 12:49:39 +02:00
youpy
6310311d52 Fix error when profile image is not set (#612) 2020-08-29 12:45:29 +02:00
Esteban Dalel R
d0caba1933 Update pages.md (#585) 2020-08-29 12:36:13 +02:00
Madusha Prasanjith
2f3291e48f [providers]: Add FusionAuth provider (#599)
* Add FusionAuth provider

* Fix issue with FusionAuth docs.
2020-08-29 12:35:13 +02:00
Ray Ma
43d8e3b894 [providers]: Updating Discord provider domain (#590)
Discord is migrating to discord.com, including their OAuth2 API routes. Support for the old domain, discordapp.com, will be dropped on 7 Nov 2020.

Note that the cdn.discordapp.com domain is unchanged. This is intentional, as the cdn domain will not be migrated due to technical restraints on Discord's side.
2020-08-29 12:32:59 +02:00
Nick Noble
5d4eb5d4e0 Fix some typos (#606) 2020-08-29 12:27:43 +02:00
S. Suzuki
7ccdec22cb Update slack.md (#617)
Fix code
2020-08-29 12:23:42 +02:00
Liam norris
2ea64045cb Documentation typos (#575)
Am I misreading this?  These changes should make the parameter to attribute mapping less ambiguous...
2020-08-13 14:34:13 +01:00
Iain Collins
daf97d298d Create SECURITY.md 2020-08-13 12:19:17 +01:00
Iain Collins
ababc7ecdb Merge branch 'main' of https://github.com/nextauthjs/next-auth into main 2020-08-13 12:00:05 +01:00
Iain Collins
33e72b2ae1 Update issue templates 2020-08-13 12:00:02 +01:00
Nico Domino
bf5716c674 Add: ldap auth tutorial example (#566)
* add: ldap auth tutorial example

* update: tutorials page list

* update: NEXTAUTH_SECRET

* Update tutorials.md

Co-authored-by: Iain Collins <me@iaincollins.com>
2020-08-11 13:33:44 +01:00
Iain Collins
c17a3b94f5 Update typeorm-custom-models.md 2020-08-11 12:38:36 +01:00
Iain Collins
19a9c313e0 Delete node.js.yml 2020-08-11 02:29:15 +01:00
Iain Collins
68043e65e4 Create test-build.yml 2020-08-11 02:28:50 +01:00
dependabot[bot]
a6ec60284d Bump prismjs from 1.20.0 to 1.21.0 in /www (#560)
Bumps [prismjs](https://github.com/PrismJS/prism) from 1.20.0 to 1.21.0.
- [Release notes](https://github.com/PrismJS/prism/releases)
- [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PrismJS/prism/compare/v1.20.0...v1.21.0)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2020-08-11 01:11:54 +01:00
Nico Domino
ff79c4b95b add: warnings page (#567) 2020-08-11 01:11:18 +01:00
Iain Collins
9c4e41a4c6 Update callbacks.md 2020-08-10 16:16:56 +01:00
Bowen
07ef3d59c5 Update pages.md (#534)
Correct typos with getInitialProps

Co-authored-by: Iain Collins <me@iaincollins.com>
2020-08-06 01:07:10 +01:00
Eli José Carrasquero
4fe7162652 Update pages.md 2020-08-06 01:02:49 +01:00
Alex Cory
950a937633 Update callbacks.md
I was getting this error due to it being a string value.
```sh
[next-auth][error][jwt_session_error] JWTClaimInvalid: "auth_time" claim must be a JSON numeric value
    at isTimestamp (/Users/alex/code/trufans/node_modules/jose/lib/jwt/verify.js:24:11)
    at validateTypes (/Users/alex/code/trufans/node_modules/jose/lib/jwt/verify.js:159:3)
    at Object.module.exports [as verify] (/Users/alex/code/trufans/node_modules/jose/lib/jwt/verify.js:236:3)
    at Object.<anonymous> (/Users/alex/code/trufans/node_modules/next-auth/dist/lib/jwt.js:100:30)
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/Users/alex/code/trufans/node_modules/next-auth/dist/lib/jwt.js:22:103)
    at _next (/Users/alex/code/trufans/node_modules/next-auth/dist/lib/jwt.js:24:194)
    at /Users/alex/code/trufans/node_modules/next-auth/dist/lib/jwt.js:24:364
    at new Promise (<anonymous>)
    at Object.<anonymous> (/Users/alex/code/trufans/node_modules/next-auth/dist/lib/jwt.js:24:97) {
  code: 'ERR_JWT_CLAIM_INVALID',
  claim: 'auth_time',
  reason: 'invalid'
}
```
2020-08-06 01:01:57 +01:00
Nick Parks
1cc31def3e Update Google Provider example to be functional
Currently the Google Provider example will always fail due to checking for `email_verified` when the correct response from the server is `verified_email`

next-auth debug output for validation:

```
[next-auth][debug][profile_data] {
  id: 'XXXXXXX',
  email: 'nick@example',
  verified_email: true,
  name: 'Nick Parks',
  given_name: 'Nick',
  family_name: 'XXXX',
  picture: 'XXXX,
  locale: 'en',
  hd: 'example.com'
}
```
2020-08-06 01:00:45 +01:00
dependabot[bot]
92f53c532b Bump elliptic from 6.5.2 to 6.5.3 in /www
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.2 to 6.5.3.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.2...v6.5.3)

Signed-off-by: dependabot[bot] <support@github.com>
2020-08-05 20:49:07 +01:00
Iain Collins
c6d6d9c002 Update documentation for Google 2020-07-31 13:06:22 +01:00
Iain Collins
85b859231c Update documentation 2020-07-31 10:17:07 +01:00
Iain Collins
ea093dc0fc Merge branch 'main' of github.com:iaincollins/next-auth into main 2020-07-31 10:01:04 +01:00
Iain Collins
cd61178f44 Bump version number to 3.1.0 2020-07-31 10:00:56 +01:00
Iain Collins
eb53219cbd Update website and documentation for mssql 2020-07-31 09:39:24 +01:00
Iain Collins
18d70ffbe9 Fix linting 2020-07-31 09:39:24 +01:00
Iain Collins
bdcf823d26 Prevent warning when using mssql conection string 2020-07-31 09:39:24 +01:00
Iain Collins
3aeba2aa09 Allow duplicate NULL email address in MSSQL 2020-07-31 09:39:24 +01:00
Mr D
0793e2c8d8 mssql: back to SnakeCaseNamingStrategy 2020-07-31 09:39:24 +01:00
Mr D
0f01279c91 mssqlTransform 2020-07-31 09:39:24 +01:00
Mr D
8fa9d00958 mssql support 2020-07-31 09:39:24 +01:00
Deeptesh Chagan
ab6ef8a19c re-sync entities on connection if changed in development 2020-07-31 00:26:21 +01:00
Iain Collins
8d68807bfe Remove node-jose dependency
This is an unused dependancy.

`jose` is used instead.
2020-07-30 23:33:29 +01:00
Ben Fox
35fc38c328 More explicit wording 2020-07-30 16:49:18 +01:00
Ben Fox
85eeda5755 Remove comments from config 2020-07-30 16:49:18 +01:00
Ben Fox
2e52c500a1 Add note to local environment setup on hot-reloading server files 2020-07-30 16:49:18 +01:00
Marc
5886f9bea8 Add Provider: Basecamp (#511)
Changes Include:
• Added Basecamp as a provider
• Added Basecamp provider to documentation
• Bumped Version to 3.0.1 in package-lock
2020-07-30 15:12:26 +02:00
Iain Collins
c497dcba26 Update options.md 2020-07-30 09:27:34 +01:00
Ben Silverman
493c45a864 Fix typo in typeorm-custom-models.md
Adapter expects `customModels` property, but doc uses `models`.
2020-07-29 23:10:16 +01:00
Iain Collins
b243b26a3d Update faq.md 2020-07-29 11:11:51 +01:00
Zeb Pykosz
1d0749970a fix(docs): remove arrow from function example 2020-07-29 09:23:02 +01:00
Iain Collins
3474d3e250 Add object type to updateSession save
This isn't technically required (it is working fine currently) but if we specify the type explicitly it should help avoid any problems in future that might be introduced with refactoring.
2020-07-28 09:41:06 +01:00
Iain Collins
a35c3a424c Fix problem updating user in TypeORM adapter
Resolves #493
2020-07-28 09:41:06 +01:00
Brady Caspar
6e65ba87a6 Removing localhost from link 2020-07-27 19:53:34 +01:00
Iain Collins
ae7247f14f Update options.md 2020-07-27 06:28:58 +01:00
Iain Collins
12a5d6b1f4 Fix linter errors 2020-07-27 05:32:01 +01:00
Iain Collins
19da066b04 Bump version number to 3.0.0 2020-07-27 05:22:15 +01:00
Iain Collins
8115a7c66c Add option to get raw JWT from getToken helper 2020-07-27 05:20:34 +01:00
Ben Fox
1ab029c60a Update local environment setup steps to fix npm link problems per issue #472 2020-07-27 05:20:34 +01:00
Iain Collins
d0dbacfc4b Display some error messages on the sign in page
Improves the UX by displaying some error messages on the sign in page
2020-07-27 05:20:34 +01:00
Diego Borges
f6b7e0aad9 Clarify script's intent 2020-07-27 05:20:34 +01:00
Iain Collins
4a23f88180 Add option to reject signIn/authorize callbacks 2020-07-27 05:20:34 +01:00
Iain Collins
f8dbd67a16 Improve homepage 2020-07-27 05:20:34 +01:00
Iain Collins
9406f8b332 Improve callbacks by adding User object to calls 2020-07-27 05:20:34 +01:00
Iain Collins
b0410ed9d4 Improvements to documentation 2020-07-27 05:20:34 +01:00
Iain Collins
8c0d0c4dea Update contributors page 2020-07-27 05:20:34 +01:00
Iain Collins
9446c26419 Improve documentation
* CSS Refactor to make it easier to maintain and UI more consistant.
* Misc small updates to docs
* Split off tutorials into a seperate menu item

I would like to add more tutorials and explainers, including those people have written on other sites.

This is a starting point for that.
2020-07-27 05:20:34 +01:00
Iain Collins
cdfa6008c7 Improve contast on links in docs 2020-07-27 05:20:34 +01:00
Iain Collins
b4bb8bda26 Hotfix for email_verified bug
Not being saved by default on sign in. Discovered in #477
2020-07-27 05:20:34 +01:00
Iain Collins
2c32504cc9 Bump version to 3.0.0-beta.21
Resolves #477 by fixing issue with last build being screwy
2020-07-27 05:20:34 +01:00
Iain Collins
bd188ff410 Improve examples and documentation 2020-07-27 05:20:34 +01:00
Iain Collins
89aedb1285 Fix contrast issues with sidebar menu 2020-07-27 05:20:34 +01:00
Iain Collins
db8c0820b6 Fix typo in docs 2020-07-27 05:20:34 +01:00
Iain Collins
d86464c822 Improve adapter documentation 2020-07-27 05:20:34 +01:00
Iain Collins
fcfeb0ce88 Update database documentation 2020-07-27 05:20:34 +01:00
Iain Collins
01e472912e Update MongoDB test (minor update) 2020-07-27 05:20:34 +01:00
Iain Collins
bbfeac408e Document SQL for MySQL and Postgres
These match up exactly with the models generated by TypeORM in v3 and are suitable for use with Prisma.
2020-07-27 05:20:34 +01:00
Iain Collins
364de1fc6c Update MySQL Model in TypeORM to use TIMESTAMP(6)
An issue with the defaults for MySQL used by TypeORM Adapter has been highlighted during testing parity with the Prisma Adapter.

This change ensures *all* TIMESTAMP columns use TIMESTAMP(6) to store six digits of precision after the number of seconds.

While this is level of precision is not required everywhere it ensures all timestamps in the default models use the same configuration (instead of a mix of values) and is consisitant with the level of precision on timestamps used Postgres.
2020-07-27 05:20:34 +01:00
Iain Collins
52af06cd33 Add Prisma client to optional peer dependencies
This doesn't technically do anything (except for the mongodb peer dependancy, which is invoked when a mongodb is being used) but it provides a way for us to indicate and track the last known good versions of database clients for NextAuth.js.
2020-07-27 05:20:34 +01:00
Iain Collins
8f472c5987 Prisma adapter refactor 2020-07-27 05:20:34 +01:00
Iain Collins
dcbd7a6703 Improve TypeORM adapter (#460)
* Uses `require_optional` and `peerOptionalDependencies` instead of dynamic import to resolve issue some users have experience with using using compliers/bundlers (especially on starter projects) that don't handle dynamic imports well.

This should (hopefully) also make it easier to support older versions of Internet Explorer by avoiding bundlers that choke on dynamic imports unless MongoDB is included as a dependancy (even though it's not code they need to compile).

We use `require_optional` to load `ObjectID` conditionally, if NextAuth.js is using MongoDB. This is also exactly how the MongoDB driver itself loads the ObjectID from the `bson/bson-ext` module.

Should resolve #251
    
* The default name for the TypeORM connection is now 'nextauth' instead of 'default'.

This should help people avoid problems with connection re-use when not using serverless (including in local development), especially if they are doing things with their default connection that differ from whats expected by NextAuth.js (like not using UTF-8 for encoding or UTC timezones).

* Now uses connection manager object from the connection, to allow a custom TypeORM connection name to be specified (resolves #459).
2020-07-27 05:20:34 +01:00
Iain Collins
e6fd4c2edc Improve sidebar apperance 2020-07-27 05:20:34 +01:00
Iain Collins
e19ca19a82 Add tips to provider documentation 2020-07-27 05:20:34 +01:00
Iain Collins
7b1b68e1c4 Fix typos in tutorial code 2020-07-27 05:20:34 +01:00
Iain Collins
56d848c868 Fix return type of sign in callback in docs 2020-07-27 05:20:34 +01:00
Timo Mämecke
100eece7a2 docs: Fix typos and wording in Client API (#455)
While reading through the new v3 docs, I spotted a few typos and some convoluted wording. Hence I directly fixed them.
2020-07-27 05:20:34 +01:00
Ty Lange-Smith
278ecc1e48 Explicitly set expires property for session on updateSession 2020-07-27 05:20:34 +01:00
Fredrik Pettersen
a3d379554b fix(prisma): Explicitly set fields to use when updating user (#449) 2020-07-27 05:20:34 +01:00
Iain Collins
983dd98a66 Fix typo in docs 2020-07-27 05:20:34 +01:00
Iain Collins
ca3f26b8d2 Update configuration docs 2020-07-27 05:20:34 +01:00
Iain Collins
d2a2352e9a Update callback docs
Addresses issue raised in comments on #429
2020-07-27 05:20:34 +01:00
Iain Collins
3043a9525a Update documentation for client methods 2020-07-27 05:20:34 +01:00
Iain Collins
e1c6632b6f Fix typo on homepage 2020-07-27 05:20:34 +01:00
Iain Collins
56e64e322e Move help menu on mobile (again)
So many UX issue with this. Hard to wrangle it given where it is semantically.

Hopefully Docusuarus beta will improve on it in a future release.
2020-07-27 05:20:34 +01:00
Iain Collins
cbd056f225 Fix typo in tutorial 2020-07-27 05:20:34 +01:00
Iain Collins
22ab66f9d8 Cosmetic improvements to docs 2020-07-27 05:20:34 +01:00
Iain Collins
3597733dae Improve FAQ documentation 2020-07-27 05:20:34 +01:00
Iain Collins
cb9ce69ba3 Update JWT questions in FAQ 2020-07-27 05:20:34 +01:00
Iain Collins
c19a79cbca Update database docs 2020-07-27 05:20:34 +01:00
Iain Collins
e97e090b65 Improve heading formatting on docs 2020-07-27 05:20:34 +01:00
Iain Collins
eda4a6d18b Add tutorial showing how to protect pages & routes 2020-07-27 05:20:34 +01:00
Iain Collins
94f66b60d8 Update documentation 2020-07-27 05:20:34 +01:00
Iain Collins
9a85e27c0c Update README 2020-07-27 05:20:34 +01:00
Iain Collins
7fb7e3d1bc Update documentation 2020-07-27 05:20:34 +01:00
Iain Collins
90066fdbec Update homepage copy and package description 2020-07-27 05:20:34 +01:00
Iain Collins
475f0e7b51 Update documentation 2020-07-27 05:20:34 +01:00
Iain Collins
a9131724d6 Update copy on homepage 2020-07-27 05:20:34 +01:00
Iain Collins
55bfb6d9dc Update docs 2020-07-27 05:20:34 +01:00
Iain Collins
af3da3abf8 Fix linting errors 2020-07-27 05:20:34 +01:00
Iain Collins
339d9f2d03 CSS tweaks 2020-07-27 05:20:34 +01:00
Iain Collins
a24fb8b380 Update JWT documentation and FAQs 2020-07-27 05:20:34 +01:00
Iain Collins
65319e3927 Update JWT defaults
* Set encryption: false  by default
 * Use 64 bit input for generated signing key
2020-07-27 05:20:34 +01:00
Iain Collins
19917972ef Review JWT comments; enable zip encoding 2020-07-27 05:20:34 +01:00
Iain Collins
c1b412814a WIP refactor JWT based on feedback 2020-07-27 05:20:34 +01:00
Iain Collins
53ea8407ea Remove default iss check (makes it optional) 2020-07-27 05:20:34 +01:00
Iain Collins
66f46e8cc7 Use URL to ensure secret is unique per instance 2020-07-27 05:20:34 +01:00
Iain Collins
fec69a21be Refactor JWT payload to use claims
Resovles #224
2020-07-27 05:20:34 +01:00
Iain Collins
505ebb8ae1 Clean up cruft in JWT class; add comments 2020-07-27 05:20:34 +01:00
Iain Collins
fb4381d8eb Implement JWE 2020-07-27 05:20:34 +01:00
Iain Collins
4772f5b571 WIP evaluating JWE solutions 2020-07-27 05:20:34 +01:00
Iain Collins
481db425d6 WIP Add JWE
Working implementation (with limited key length and no exp check) using node-jose from Cisco.

I want to compare it panva/jose which has more features before building it out.
2020-07-27 05:20:34 +01:00
Iain Collins
b886729bb8 Update version to 3.0.0-beta.18 2020-07-27 05:20:34 +01:00
Iain Collins
3a21a9c9f1 Enforce HMAC-256 on JWT
Now that we are going to expose the option to disable encryption on tokens we need to enforce the algorithm is valid (e.g. not 'None' or 'RSA') to prevent vultrabilties being exploited by tampering with the token.

Custom encode/decode routines can be specified if someone needs to use another algorithm.
2020-07-27 05:20:34 +01:00
Iain Collins
9e4a6fec59 Update JWT and session docs 2020-07-27 05:20:34 +01:00
Iain Collins
86921022dc Refactor JWT support
* Adds option to disable encryption
* Easy to add custom helper
* Removed getJWT helper
* Added getToken helper
* Helper does not fallback to trying non-prefixed cookie on HTTPS sites
* Supports bearer tokens in HTTP header on helper #397
2020-07-27 05:20:34 +01:00
Iain Collins
f57f11e6ff Bump version to 3.0.0-beta.17 2020-07-27 05:20:34 +01:00
Iain Collins
77ad6bd97e Update FAQ 2020-07-27 05:20:34 +01:00
Iain Collins
78c7041b3f Improve docs site on mobile 2020-07-27 05:20:34 +01:00
Iain Collins
99edead0f2 Add FAQ 2020-07-27 05:20:34 +01:00
Iain Collins
b0b3dbc0fc Add provider icons to homepage 2020-07-27 05:20:34 +01:00
Iain Collins
8b5af54e1c Update documentation 2020-07-27 05:20:34 +01:00
Iain Collins
0b5b04a22f Apply datetime transforms on properties in custom models
It makes sense to change this behaviour now we have a tutorial and have been testing this functionality.

Docs are being updated to reflect this change.
2020-07-27 05:20:34 +01:00
Iain Collins
890be1de0d Update email provider 2020-07-27 05:20:34 +01:00
Iain Collins
40ae747bc1 Add support for passing appContext to getCsrfToken
Requested in #345

getSession() already does this so seems reasonable to support it in getCsrfToken too.
2020-07-27 05:20:34 +01:00
Iain Collins
5a8022e9a2 Update homepage and refactor CSS
Making an attempt to clean up some of crusty CSS I've added.
2020-07-27 05:20:34 +01:00
Iain Collins
3e512b5cf5 Tweak CSS on homepage 2020-07-27 05:20:34 +01:00
Iain Collins
81071d7776 Update adapters documentation 2020-07-27 05:20:34 +01:00
Iain Collins
fc05140c1f Improve homepage 2020-07-27 05:20:34 +01:00
Iain Collins
faec6824ba Disable use of state on Apple provider
It is not supported by Apple ID.
2020-07-27 05:20:34 +01:00
Iain Collins
b91bfef16d Refactor and document state provider option 2020-07-27 05:20:34 +01:00
Iain Collins
ba9dc17e44 Update homepage 2020-07-27 05:20:34 +01:00
Iain Collins
c220bcc57e Update version to 3.0.0-beta.13 2020-07-27 05:20:34 +01:00
Iain Collins
f8a4808aa7 Fix bug with NEXTAUTH_URL parsing 2020-07-27 05:20:34 +01:00
ndo@$(hostname)
495d0a47db fix: marquee icons 2020-07-27 05:20:34 +01:00
Iain Collins
8cda627fe6 Update adapter documentation 2020-07-27 05:20:34 +01:00
Iain Collins
d0a0ccc6bc Update TypeORM tutorial 2020-07-27 05:20:34 +01:00
Iain Collins
999222cd97 Refactor to simplify site URL configuration
Includes some linter fixes
2020-07-27 05:20:34 +01:00
Iain Collins
72eb7fda3f Fix error merging branches for v3
Accidentally squashed a couple of lines in OAuth callback.
2020-07-27 05:20:34 +01:00
Iain Collins
3c94940ae6 Respect existing cookies on a request object
Unproven, but should fix #395 and improve middleware compatibility.
2020-07-27 05:20:34 +01:00
Iain Collins
1a8ed2aec1 Update version to 3.0.0-beta.9 2020-07-27 05:20:34 +01:00
Iain Collins
0e2321dc14 Update pages documentation 2020-07-27 05:20:34 +01:00
Iain Collins
78d1983f9a Update version to 3.0.0-beta.8 2020-07-27 05:20:34 +01:00
Iain Collins
5435df110c Fix linter errors 2020-07-27 05:20:34 +01:00
Iain Collins
32853b8d1e Update events, callbacks & pages to use camelCase
* This is a breaking change in v3
* Includes updated documentation
2020-07-27 05:20:34 +01:00
Iain Collins
9737b4c6ab Only invoke setTimeout client side
This should never be called server side, but just in case someone calls setOptions server side this prevents it from being invoked at all.
2020-07-27 05:20:34 +01:00
Iain Collins
e9bdd5c355 Improve client event handling
Improves how well syncing client state is handled and how well caching is leveraged.

Reduces network load, cpu load and memory footprint.
2020-07-27 05:20:34 +01:00
Iain Collins
9728567296 Improve client state syncing
* clientMaxAge now passive
* clientPollInterval added (works like old clientMaxAge)
* poll intervals uses timer (more efficent)
* updates state on window focus/blur
2020-07-27 05:20:34 +01:00
Iain Collins
ef6579a7ee Refactor redirect handling (WIP)
Passing a redirect function like this is a bit horrible, but is less horrible than before.
2020-07-27 05:20:34 +01:00
Iain Collins
8e810aa765 Fix linting errors and bug in getCsrfToken 2020-07-27 05:20:34 +01:00
Iain Collins
37596edf2b Improve CSRF security for all routes
Includes breaking changes for v3 and updates to documentation.

If using the client, the only required change should be setting the NEXTAUTH_URL environment variable.
2020-07-27 05:20:34 +01:00
tmayr@tmayr.com
229a3e430e Add tutorial on how to use custom typeorm models 2020-07-27 05:20:34 +01:00
Nico Domino
1d80f595c5 Add provider Vercel-style marquee to docs
* add: marquee provider section
* fix: lint
* update: adjust node sizes
* fix: window undefined SSR
* fix: path to imgs

Co-authored-by: Iain Collins <me@iaincollins.com>
2020-07-27 05:20:34 +01:00
Iain Collins
189a2c8e0e Fix for reading private key in Apple provider 2020-07-27 05:20:34 +01:00
Iain Collins
97096fb811 Fix linter errors and add comments 2020-07-27 05:20:34 +01:00
Gerald Nolan
e8b75e40b1 feat: Added UserData to ProfileData after return from Apple to get user name on first sign in 2020-07-27 05:20:34 +01:00
Iain Collins
d41c38e002 Add support for hitting cancel if using token id
When using a provider that uses Token ID option (like Apple) a user hitting cancel with no longer cause the app to crash.

Users who do this will now be taken back to the sign in page.

This was already working for other providers that didn't use this option but wasn't supported for providers that did use it.
2020-07-27 05:20:34 +01:00
Fredrik Pettersen
966bc7b433 docs(prisma): Add note about model names and set email to optional 2020-07-27 05:20:34 +01:00
Fredrik Pettersen
e7b06d3362 fix(prisma): Make sure provider id is a string 2020-07-27 05:20:34 +01:00
Fredrik Pettersen
d5d8eb8d7c feat(adapter): Add opinionated prisma adapter 2020-07-27 05:20:34 +01:00
nyedidikeke
8ec07f0224 Add LinkedIn provider 2020-07-27 03:22:43 +01:00
dan-kwiat
558536db1e docs(options): remove duplicate arrow 2020-07-23 10:30:50 +01:00
Lori Karikari
0c2fe054d1 [Docs] fix small typo 2020-07-20 17:46:48 +02:00
dependabot[bot]
b5a69fd787 Bump lodash from 4.17.15 to 4.17.19 in /www
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-17 12:31:11 +01:00
dependabot[bot]
9b29ed347d Bump lodash from 4.17.15 to 4.17.19
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.19.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.19)

Signed-off-by: dependabot[bot] <support@github.com>
2020-07-17 12:06:12 +01:00
Jibin George
c5c4ff4d51 Fix typo 2020-07-15 13:30:01 +01:00
styxlab
008b1a9f8d fallback if user.name is null (#424)
Co-authored-by: cws <cws@home.fritz.box>
2020-07-12 18:52:58 +02:00
Iain Collins
4a6f153aa6 Update question.md 2020-07-10 16:14:10 +01:00
Iain Collins
9eccc78e3a Update feature_request.md 2020-07-10 16:13:12 +01:00
Iain Collins
09938cc368 Update bug_report.md 2020-07-10 16:12:59 +01:00
Jake Harding
5db05e1031 Use id_str for reading in Twitter user ID 2020-07-09 11:07:18 +01:00
Ryuichi Okumura
f6ba72b4fa Fix wrong syntax in Apple provider example
It fixes a syntax error in Apple provider example code.
2020-07-07 19:38:44 +01:00
Jonathan Dean
bf7e555cfa Fix typo: curly brace should be square bracket 2020-07-07 19:35:36 +01:00
William Duplenne
26abc70a99 Add Spotify provider
Add Spotify to the sidebar
2020-07-07 08:35:55 +01:00
tmayr@tmayr.com
d38cd54dee Fix using merged models var instead of user provided models in props
Merged models were being overwritten by user provided models which
might come incomplete
2020-07-06 20:51:36 +01:00
felipe muner
200690ad6c Update pages.md (#389) 2020-07-05 10:58:09 +02:00
Nico Domino
52b69a6d68 Add: testing with cypress docs (#357)
* add: testing with cypress docs

* update: add tutorials group
2020-07-04 21:47:00 +02:00
Theo Gravity
f319b2af05 Fix reading of req in getSession() 2020-07-04 01:27:03 +01:00
Iain Collins
b80a005733 Update callbacks.md 2020-07-01 17:16:15 +01:00
Arunoda Susiripala
34936aecc0 Pass maxAge to the 'jwt.getJwt' function
With that it can pass that to the `jwt.decode` method. This will be useful, if we are using a custom `maxAge` value.
2020-07-01 10:46:35 +01:00
Tom Astley
b021f26f03 Update client.md (#370)
Fixed small syntax error on line 219 in the signout example. Added a '('
2020-06-30 11:56:47 +02:00
Iain Collins
fcf7197120 Fix indentation in example (trivial) 2020-06-30 10:47:29 +01:00
Iain Collins
bec8d8dff1 Update callbacks.md 2020-06-30 09:30:01 +01:00
Iain Collins
781c63e966 Update pages.md 2020-06-30 08:52:58 +01:00
Iain Collins
2da1883726 Fix typo in email.md 2020-06-30 08:52:18 +01:00
Thibaut Patel
83ffac7cd2 Fix missing closing tag in docs 2020-06-28 21:09:11 +01:00
Iain Collins
6198903cdf Update copy on homepage 2020-06-28 14:49:30 +01:00
Iain Collins
bd98f8188c Update introduction.md 2020-06-28 14:40:29 +01:00
Iain Collins
73ea402b1c Compress images
* Forgot to do this when I added them.
* May add a script to compress them on commit.
* Adding new binary blobs bloats repo over time, we can always purge old assets if it's a problem.
* The social card is slightly too bright to compensate for PNG gamma interpretation not being consistant between browsers (too bright in some looks better than too dark in others). Maybe it should be a JPEG.
2020-06-28 14:03:23 +01:00
Iain Collins
4284684a3b Improve apperance of documentation on mobile 2020-06-28 10:51:51 +01:00
Iain Collins
b5d522410a Update CSS
Additional changes following testing on mobile.
2020-06-28 10:51:51 +01:00
Iain Collins
284cb8e2a7 Improve website CSS on mobile and dark mode 2020-06-28 10:51:51 +01:00
Iain Collins
079aab2315 Improve mobile documentation secondary menu
Still not great, but somewhat better.
2020-06-28 10:51:51 +01:00
Iain Collins
645ee382cf Improve documentation structure / sidebar 2020-06-28 10:51:51 +01:00
Iain Collins
e947a772ce Website cosmetic refresh
Addressing quality issues with assets and layout
2020-06-28 10:51:51 +01:00
Iain Collins
5d63adf7df Update errors.md 2020-06-26 17:22:18 +01:00
Iain Collins
f1a872f861 Update errors.md 2020-06-26 16:39:48 +01:00
Iain Collins
02b1d02f09 Update cognito.md 2020-06-26 12:56:53 +01:00
202 changed files with 26068 additions and 5721 deletions

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
# Exclude directories we don't need from Docker context to improve build time
node_modules
www
src

13
.env.example Normal file
View File

@@ -0,0 +1,13 @@
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_TWITTER_ID=
NEXTAUTH_TWITTER_SECRET=
NEXTAUTH_TWITTER_USERNAME=
NEXTAUTH_TWITTER_PASSWORD=
NEXTAUTH_GITHUB_ID=
NEXTAUTH_GITHUB_SECRET=
NEXTAUTH_GITHUB_USERNAME=
NEXTAUTH_GITHUB_PASSWORD=
NEXTAUTH_GOOGLE_ID=
NEXTAUTH_GOOGLE_SECRET=
NEXTAUTH_GOOGLE_USERNAME=
NEXTAUTH_GOOGLE_PASSWORD=

View File

@@ -1,28 +1,30 @@
---
name: Bug report
about: Report a defect with the software
about: Report a defect with NextAuth.js
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the defect is.
A clear and concise description of the bug in NextAuth.js.
**To Reproduce**
Do not report bugs with your own project here, ask from help by raising a question instead - this helps us a lot with administration overhead.
**Steps to reproduce**
Steps to reproduce the behavior.
Include example code (or link to public repository) which can be used to reproduce the behaviour.
Include a link to public repository which can be used to reproduce the behaviour.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots or error logs**
If applicable, add screenshots or error logs to help explain the problem.
If applicable add screenshots or error logs to help explain the problem.
**Additional context**
Add any other context about the problem here.
**Documentation feedback**
**Feedback**
*Documentation refers to searching through [online documentation](https://next-auth.js.org), code comments and issue history. The example project refers to [next-auth-example](https://github.com/iaincollins/next-auth-example).*
* [ ] Found the documentation helpful

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -1,12 +1,10 @@
---
name: Feature request
about: Suggest an idea for this project
about: Suggest an idea for NextAuth.js
labels: enhancement
assignees: ''
---
*Please stick to one distinct feature request per issue where possible and raise additional feature quests as separate issues. Try to avoid adding feature requests to existing issues in the comments of issues raised by other users.*
**Summary of proposed feature**
A clear and concise description of the feature being proposed.

View File

@@ -1,19 +1,21 @@
---
name: Question
about: Ask for information or support
about: Ask a question about NextAuth.js or for help using it
labels: question
assignees: ''
---
*Please refer to the [documentation](https://next-auth.js.org/getting-started/introduction), the [example project](https://github.com/iaincollins/next-auth-example) and existing issues before creating a new issue.*
<!-- NOTE: Questions will be converted to Discussions. You can find them at https://github.com/nextauthjs/next-auth/discussions! -->
**Your question**
A clear and concise question.
<!-- A clear and concise question. -->
**What are you trying to do**
A description of what you are trying to do.
<!-- A description of what you are trying to do, for context. -->
**Documentation feedback**
**Reproduction**
<!-- If your question is code related, adding a reproduction to your use case can greatly reduce the time it takes us to figure out how to better help you. -->
**Feedback**
*Documentation refers to searching through [online documentation](https://next-auth.js.org), code comments and issue history. The example project refers to [next-auth-example](https://github.com/iaincollins/next-auth-example).*
* [ ] Found the documentation helpful

43
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,43 @@
<!--
Thanks for your interest in the project. Bugs filed and PRs submitted are appreciated!
Please make sure that you are familiar with and follow the Code of Conduct for
this project (found in the CODE_OF_CONDUCT.md file).
Also, please make sure you're familiar with and follow the instructions in the
contributing guidelines (found in the CONTRIBUTING.md file).
Note before creating the Pull Request. Even though the CONTRIBUTONG.md tells otherwise, we ask you to use the `canary` branch as base for your PR. We are tranistioning to a new structure, and the CONTRIBUTONG.md file has not been updated yet. Thank you!
If you're new to contributing to open source projects, you might find this free
video course helpful: http://kcd.im/pull-request
Please fill out the information below to expedite the review and (hopefully)
merge of your pull request!
-->
<!-- What changes are being made? (What feature/bug is being fixed here?) -->
**What**:
<!-- Why are these changes necessary? -->
**Why**:
<!-- How were these changes implemented? -->
**How**:
<!-- Have you done all of these things? -->
**Checklist**:
<!-- add "N/A" to the end of each line that's irrelevant to your changes -->
<!-- to check an item, place an "x" in the box like so: "- [x] Documentation" -->
- [ ] Documentation
- [ ] Tests
- [ ] Ready to be merged
<!-- In your opinion, is this ready to be merged as soon as it's reviewed? -->
<!-- feel free to add additional comments -->

24
.github/stale.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
- priority
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
Hi there! It looks like this issue hasn't had any activity for a while.
It will be closed if no further activity occurs. If you think your issue
is still relevant, feel free to comment on it to keep it open. (Read more at #912)
Thanks!
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
Hi there! It looks like this issue hasn't had any activity for a while.
To keep things tidy, I am going to close this issue for now.
If you think your issue is still relevant, just leave a comment
and I will reopen it. (Read more at #912)
Thanks!

31
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
# Simple check that the build is valid and no linting errors.
# Currently is run as a seperate workflow as it's fast to fail.
name: Build Test
on:
push:
branches:
- main
- canary
pull_request:
branches:
- main
- canary
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build
- run: npm run lint

55
.github/workflows/integration.yml vendored Normal file
View File

@@ -0,0 +1,55 @@
name: Integration Test
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
# Only run tests integration against Pull Requests from branches in
# this repository. We do this as integration tests require access to
# secrets in GitHub and they are not exposed to tests run against
# forks (for security reasons), so integration test against
# Pull Requests from external repos just fail and generate noise.
if: github.event.pull_request.head.repo.full_name == github.repository
# We use self-hosted runners as cloud based runnners (e.g. AWS, GPC)
# fail due to IP Address checks done by providers, which enforce
# CAPTCHA checks on login request from cloud compute IP addresses to
# prevent abuse.
runs-on: self-hosted
# Target time is under 5 minutes to run all tests. If it takes longer than
# 10 minutes should look at running tests in parallel. No individual flow
# should take longer than 5 minutes to build and run.
timeout-minutes: 10
strategy:
matrix:
node-version: [12.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
# Install dependencies
- run: npm ci
# Run tests (build library, build + start test app in Docker, run tests)
- run: npm test
# TODO Tests should exit out if env vars not set (currently hangs)
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
NEXTAUTH_TWITTER_ID: ${{secrets.NEXTAUTH_TWITTER_ID}}
NEXTAUTH_TWITTER_SECRET: ${{secrets.NEXTAUTH_TWITTER_SECRET}}
NEXTAUTH_TWITTER_USERNAME: ${{secrets.NEXTAUTH_TWITTER_USERNAME}}
NEXTAUTH_TWITTER_PASSWORD: ${{secrets.NEXTAUTH_TWITTER_PASSWORD}}
NEXTAUTH_GITHUB_ID: ${{secrets.NEXTAUTH_GITHUB_ID}}
NEXTAUTH_GITHUB_SECRET: ${{secrets.NEXTAUTH_GITHUB_SECRET}}
NEXTAUTH_GITHUB_USERNAME: ${{secrets.NEXTAUTH_GITHUB_USERNAME}}
NEXTAUTH_GITHUB_PASSWORD: ${{secrets.NEXTAUTH_GITHUB_PASSWORD}}

View File

@@ -1,29 +0,0 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [10.x, 12.x, 14.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build --if-present
- run: npm test

View File

@@ -1,36 +0,0 @@
# Publishes module to registry when a new release is created.
#
# The following secrets need to be configured for this workflow:
#
# * NPM_TOKEN - Auth token from npmjs.com
name: Publish to NPM
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- run: npm ci
- run: npm test
publish-npm:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
registry-url: https://registry.npmjs.org/
- run: npm ci
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}

30
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Release
on:
push:
branches:
- main
- canary
jobs:
release:
name: Release
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v1
with:
node-version: 12
- name: Install dependencies
run: npm ci
- name: Lint
run: npm run lint
- name: Build
run: npm run build
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release

42
.gitignore vendored
View File

@@ -1,20 +1,7 @@
.next
.env
.vscode
node_modules
dist
.DS_Store# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
# Misc
.DS_Store
.env
.env.local
.env.development.local
.env.test.local
@@ -24,5 +11,26 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Docusaurus
www/build
# Dependencies
node_modules
# Build dirs
.next
/build
/dist
/www/build
# Generated files
.docusaurus
.cache-loader
.next
# VS
/.vs/slnx.sqlite-journal
/.vs/slnx.sqlite
/.vs
.vscode
# GitHub Actions runner
/actions-runner
/_work

39
.releaserc.json Normal file
View File

@@ -0,0 +1,39 @@
{
"branches": [
"main",
{ "name": "canary", "prerelease": true }
],
"plugins": [
["@semantic-release/commit-analyzer", {
"preset": "conventionalcommits",
"releaseRules": [
{ "breaking": true, "release": "major" },
{ "revert": true, "release": "patch" },
{ "type": "feat", "release": "minor" },
{ "type": "fix", "release": "patch" },
{ "type": "perf", "release": "patch" },
{ "type": "docs", "release": "patch" }
]
}],
["@semantic-release/release-notes-generator", {
"preset": "conventionalcommits",
"presetConfig": {
"types": [
{ "type": "feat", "section": "Features", "hidden": false },
{ "type": "fix", "section": "Bug Fixes", "hidden": false },
{ "type": "perf", "section": "Performance Improvements", "hidden": false },
{ "type": "revert", "section": "Reverts", "hidden": false },
{ "type": "docs", "section": "Documentation", "hidden": false },
{ "type": "style", "section": "Styles", "hidden": false },
{ "type": "chore", "section": "Miscellaneous Chores", "hidden": false },
{ "type": "refactor", "section": "Code Refactoring", "hidden": false },
{ "type": "test", "section": "Tests", "hidden": false },
{ "type": "build", "section": "Build System", "hidden": false },
{ "type": "ci", "section": "Continuous Integration", "hidden": false }
]
}
}],
"@semantic-release/github",
"@semantic-release/npm"
]
}

5
CHANGELOG.md Normal file
View File

@@ -0,0 +1,5 @@
# CHANGELOG
The changelog is automatically updated using
[semantic-release](https://github.com/semantic-release/semantic-release). You
can see it on the [releases page](../../releases).

View File

@@ -2,9 +2,9 @@
Contributions and feedback on your experience of using this software are welcome.
This includes bug reports, feature requests, ideas, pull requests and examples of how you have used this software.
This includes bug reports, feature requests, ideas, pull requests, and examples of how you have used this software.
Please see the [Code of Conduct](CODE_OF_CONDUCT.md) and follow any templates configured in GitHub when reporting bugs, requesting enhancements or contributing code.
Please see the [Code of Conduct](CODE_OF_CONDUCT.md) and follow any templates configured in GitHub when reporting bugs, requesting enhancements, or contributing code.
Please raise any significant new functionality or breaking change an issue for discussion before raising a Pull Request for it.
@@ -13,14 +13,14 @@ Please raise any significant new functionality or breaking change an issue for d
* The latest changes are always in `main`
* Pull Requests should be raised for larger changes
* Pull Requests do not need approval before merging for those with contributor access (it's just helpful to have them to track changes)
* Rebasing in Pull Requests is prefered to keep a clean commit history (see below)
* Rebasing in Pull Requests is preferred to keep a clean commit history (see below)
* Running `npm run lint:fix` before committing can make resolving conflicts easier, but is not required
* Merge commits (and pushing merge commits to `main`) are disabled in this repo; but commits in PR can be squashed so this is not a blocker
* Merge commits (and pushing merge commits to `main`) are disabled in this repo, but commits in PR can be squashed so this is not a blocker
* Pushing directly to main should ideally be reserved for minor updates (e.g. correcting typos) or small single-commit fixes
## Rebasing
*If you don't rebase and end up with merge commits in a PR then it's not a blocker, we can alway squash the commits when merging!*
*If you don't rebase and end up with merge commits in a PR then it's not a blocker, we can always squash the commits when merging!*
If you create a branch and there are conflicting updates in the `main` branch, you can resolve them by rebasing from a check out of your branch:
@@ -33,13 +33,13 @@ If there are any conflicts, you can resolve them and stage the files, then run:
*If there are a lot of changes you may be prompted to step more than once.*
When the rebase is complete (i.e. there are no more conflicts) you should push your changes to your branch before doing anyhing else:
When the rebase is complete (i.e. there are no more conflicts) you should push your changes to your branch before doing anything else:
git push --force-with-lease
You should see that any conflicts in your PR are now resolved. You can review changes to make sure it contains changes you intended to make.
*If you accidentally sync before pushing, it will trigger a merge. Uou can use `git merge --abort` to undo the merge.*
*If you accidentally sync before pushing, it will trigger a merge. You can use `git merge --abort` to undo the merge.*
You can use `npm run lint:fix` to automatically apply Standard JS rules to resolve formatting differences (tabs vs spaces, line endings, etc).
@@ -57,20 +57,21 @@ A quick and dirty guide on how to setup *next-auth* locally to work on it and te
npm i
npm run build
3. Link React between the repo and the version installed in your project:
npm link ../your-application/node_modules/react
*This is an annoying step and not obvious, but is needed because of how React has been written (otherwise React crashes when you try to use the `useSession()` hook in your project).*
4. Finally link your project back to your local copy of next auth:
3. Link your project back to your local copy of next auth:
cd ../your-application
npm link ../next-auth
4. Finally link React between the repo and the version installed in your project:
cd ../next-auth
npm link ../your-application/node_modules/react
*This is an annoying step and not obvious, but is needed because of how React has been written (otherwise React crashes when you try to use the `useSession()` hook in your project).*
That's it!
Notes: You may need to repeat both `npm link` steps if you install / update additional dependancies with `npm i`.
Notes: You may need to repeat both `npm link` steps if you install / update additional dependencies with `npm i`.
If you need an example project to link to, you can use [next-auth-example](https://github.com/iaincollins/next-auth-example).
@@ -83,19 +84,37 @@ You might find it helpful to use the `npm run watch` command in the next-auth pr
If you are working on `next-auth/src/client/index.js` hot reloading will work as normal in your Next.js app.
However if you are working on anything else (e.g. `next-auth/src/server/*` etc) then you will need to *stop and start* your app for changes to apply as **Next.js will not hot reload those changes**.
However, if you are working on anything else (e.g. `next-auth/src/server/*` etc) then you will need to *stop and start* your app for changes to apply as **Next.js will not hot reload those changes by default**. To facilitate this, you can try [this webpack plugin](https://www.npmjs.com/package/webpack-clear-require-cache-plugin). Note that the `next.config.js` syntax in the plugin README may be out of date. It should look like this:
```
const clearRequireCachePlugin = require('webpack-clear-require-cache-plugin')
module.exports = {
webpack: (config, {
buildId, dev, isServer, defaultLoaders, webpack,
}) => {
config.plugins.push(clearRequireCachePlugin([
/\.next\/server\/static\/development\/pages/,
/\.next\/server\/ssr-module-cache.js/,
/next-auth/,
]))
return config
},
}
```
### Databases
Included is a Docker Compose file that starts up MySQL, Postgres and MongoDB databases on localhost.
Included is a Docker Compose file that starts up MySQL, Postgres, and MongoDB databases on localhost.
It will use port 3306, 5432 and 27017 on localhost respectively; it will not work if are running existing databases on localhost.
It will use port 3306, 5432, and 27017 on localhost respectively; it will not work if are running existing databases on localhost.
You can start them with `npm run db:start` and stop them with `npm run db:stop`.
You will need Docker installed to be able to start / stop the databases.
When stop the databases, it will reset their contents.
When stopping the databases, it will reset their contents.
### Testing
@@ -103,6 +122,6 @@ Tests can be run with `npm run test`.
Automated tests are currently crude and limited in functionality, but improvements are in development.
Currently to run tests you need to first have started local test databases (e.g. using `npm run db:start`).
Currently, to run tests you need to first have started local test databases (e.g. using `npm run db:start`).
The databases can take a few seconds to start up, so you might need to give it a minute before running the tests.

30
Dockerfile Normal file
View File

@@ -0,0 +1,30 @@
# Multi stage build to allow us to improve performance
FROM node:10-alpine as base
WORKDIR /usr/src/app
# Install basic dependancies (Next.js, React)
COPY test/docker/app/package*.json ./
RUN npm ci --only=production
FROM node:10-alpine as app
COPY --from=base /usr/src/app ./
# Copy last build of library into the image and install dependences for it.
# This ensures the build is valid and package.json contains everything needed
# to actually run the library.
# Note: You must run `npm run build` first to build a release of the library
RUN mkdir -p node_modules/next-auth
# Copy all entrypoints for the library (if creating a new one, add it here)
COPY index.js providers.js adapters.js client.js jwt.js node_modules/next-auth/
# Copy the dist dir
COPY dist node_modules/next-auth/dist
# Copy the package.json for the library and install it's dependences
COPY package*.json node_modules/next-auth/
RUN cd node_modules/next-auth/ && npm ci --only=production
# Copy test pages across
COPY test/docker/app/pages ./pages
RUN npm run build
CMD [ "npm", "start" ]

View File

@@ -1,4 +1,20 @@
# NextAuth.js
<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>
<p align="center">Authentication for Next.js</p>
<p align="center">
Open Source. Full Stack. Own Your Data.
</p>
<p align="center" style="align: center;">
<img src="https://github.com/nextauthjs/next-auth/workflows/Build%20Test/badge.svg" alt="Build Test" />
<img src="https://github.com/nextauthjs/next-auth/workflows/Integration%20Test/badge.svg" alt="Integration Test" />
<img src="https://img.shields.io/bundlephobia/minzip/next-auth" alt="Bundle Size"/>
<img src="https://img.shields.io/npm/dm/next-auth" alt="Downloads" />
<img src="https://img.shields.io/github/stars/nextauthjs/next-auth" alt="Github Stars" />
<img src="https://img.shields.io/github/v/release/nextauthjs/next-auth?include_prereleases" alt="Github Release" />
</p>
</p>
## Overview
@@ -6,35 +22,64 @@ NextAuth.js is a complete open source authentication solution for [Next.js](http
It is designed from the ground up to support Next.js and Serverless.
[Follow the examples](https://next-auth.js.org/getting-started/example) to see how easy it is to use NextAuth.js for authentication.
## Getting Started
Install: `npm i next-auth`
```
npm install --save next-auth
```
The easiest way to continue getting started, is to follow the [getting started](https://next-auth.js.org/getting-started/example) section in our docs.
We also have a section of [tutorials](https://next-auth.js.org/tutorials) for those looking for more specific examples.
See [next-auth.js.org](https://next-auth.js.org) for more information and documentation.
## Features
### Authentication
### Flexible and easy to use
* Designed to work with any OAuth service, it supports OAuth 1.0, 1.0A and 2.0
* Built-in support for [many popular OAuth sign-in services](https://next-auth.js.org/configuration/providers)
* Built-in support for [many popular sign-in services](https://next-auth.js.org/configuration/providers)
* Supports email / passwordless authentication
* Supports stateless authentication with any backend (Active Directory, LDAP, etc)
* Supports both JSON Web Tokens and database sessions
* Designed for Serverless but runs anywhere (AWS Lambda, Docker, Heroku, etc…)
### Own your own data
NextAuth.js can be used with or without a database.
* An open source solution that allows you to keep control of your data
* Supports Bring Your Own Database (BYOD) and can be used with any database
* Built-in support for for [MySQL, MariaDB, Postgres, MongoDB and SQLite](https://next-auth.js.org/configuration/database)
* Built-in support for [MySQL, MariaDB, Postgres, Microsoft SQL Server, MongoDB and SQLite](https://next-auth.js.org/configuration/databases)
* Works great with databases from popular hosting providers
* Can also be used without a database (e.g. OAuth + JWT)
* Can also be used *without a database* (e.g. OAuth + JWT)
### Secure by default
* Designed to be secure by default and promote best practice for safeguarding user data
* Promotes the use of passwordless sign in mechanisms
* Designed to be secure by default and encourage best practice for safeguarding user data
* Uses Cross Site Request Forgery Tokens on POST routes (sign in, sign out)
* Default cookie policy aims for the most restrictive policy appropriate for each cookie
* When JSON Web Tokens are enabled, they are signed by default (JWS) with HS512
* Use JWT encryption (JWE) by setting the option `encryption: true` (defaults to A256GCM)
* Auto-generates symmetric signing and encryption keys for developer convenience
* Features tab/window syncing and keepalive messages to support short lived sessions
* Attempts to implement the latest guidance published by [Open Web Application Security Project](https://owasp.org/)
Security focused features include CSRF protection, use of signed cookies, cookie prefixes, secure cookies, HTTP only, host only and secure only cookies and promoting passwordless sign-in.
Advanced options allow you to define your own routines to handle controlling what accounts are allowed to sign in, for encoding and decoding JSON Web Tokens and to set custom cookie security policies and session properties, so you can control who is able to sign in and how often sessions have to be re-validated.
### Typescript
You can install the appropriate types via the following command:
```
npm install --save-dev @types/next-auth
```
If you encounter any problems with the types package, please create an issue and add the `typescript` label to it.
Alternatively, you can open a pull request directly with your fixes on the [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/next-auth) repository, where you'll find a `next-auth` subfolder.
## Example
@@ -44,8 +89,7 @@ Security focused features include CSRF protection, use of signed cookies, cookie
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
const options = {
site: 'https://example.com'
export default NextAuth({
providers: [
// OAuth authentication providers
Providers.Apple({
@@ -64,9 +108,7 @@ const options = {
],
// SQL or MongoDB database (or leave empty)
database: process.env.DATABASE_URL
}
export default (req, res) => NextAuth(req, res, options)
})
```
### Add React Component
@@ -79,7 +121,7 @@ import {
signout
} from 'next-auth/client'
export default () => {
export default function myComponent() {
const [ session, loading ] = useSession()
return <p>
@@ -95,14 +137,18 @@ export default () => {
}
```
## Acknowledgement
## Acknowledgements
[NextAuth.js 2.0 is possible thanks to its contributors.](https://next-auth.js.org/contributors)
[NextAuth.js is made possible thanks to all of its contributors.](https://next-auth.js.org/contributors)
## Getting started
[Follow the examples to get started.](https://next-auth.js.org/getting-started/example)
<a href="https://github.com/nextauthjs/next-auth/graphs/contributors">
<img width="500px" src="https://contrib.rocks/image?repo=nextauthjs/next-auth" />
</a>
## Contributing
If you'd like to contribute to you can find useful information in our [Contributing Guide](https://github.com/iaincollins/next-auth/blob/main/CONTRIBUTING.md).
We're open to all community contributions! If you'd like to contribute in any way, please first read our [Contributing Guide](https://github.com/iaincollins/next-auth/blob/main/CONTRIBUTING.md).
## License
ISC

24
SECURITY.md Normal file
View File

@@ -0,0 +1,24 @@
# Security Policy
NextAuth.js practices responsible disclosure.
## Supported Versions
Security updates are only released for the current version.
Old releases are not maintained and do not receive updates.
## Reporting a Vulnerability
We request that you contact us directly to report serious issues that might impact the security of sites using NextAuth.js.
If you contact us regarding a serious issue:
* We will endeavor to get back to you within 72 hours.
* We will aim to publish a fix within 30 days.
* We will disclose the issue (and credit you, with your consent) once a fix to resolve the issue has been released.
* If 90 days has elapsed and we still don't have a fix, we will disclose the issue publically.
Currently, the best way to report an issue is by emailing me@iaincollins.com
For less serious issues (e.g. RFC compliance for unsupported flows or potential issues that may cause a problem future or default behaviour / options) it is appropriate to submit these these publically as bug reports or feature requests or to raise a question to open a discussion around them.

8037
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,9 @@
{
"name": "next-auth",
"version": "2.2.0",
"description": "An authentication library for Next.js",
"repository": "https://github.com/iaincollins/next-auth.git",
"version": "0.0.0-semantically-released",
"description": "Authentication for Next.js",
"homepage": "https://next-auth.js.org",
"repository": "https://github.com/nextauthjs/next-auth.git",
"author": "Iain Collins <me@iaincollins.com>",
"main": "index.js",
"scripts": {
@@ -12,13 +13,19 @@
"watch": "npm run watch:js | npm run watch:css",
"watch:js": "babel --watch src --out-dir dist",
"watch:css": "postcss --watch src/**/*.css --base src --dir dist",
"test": "npm run lint",
"test:db": "npm run test:db:mysql && npm run test:db:postgres && npm run test:db:mongodb",
"test:app:start": "docker-compose -f test/docker/app.yml up -d",
"test:app:rebuild": "npm run build && docker-compose -f test/docker/app.yml up -d --build",
"test:app:stop": "docker-compose -f test/docker/app.yml down",
"test": "npm run test:app:rebuild && npm run test:integration && npm run test:app:stop",
"test:db": "npm run test:db:mysql && npm run test:db:postgres && npm run test:db:mongodb && npm run test:db:mssql && npm run test:db:fauna",
"test:db:mysql": "node test/mysql.js",
"test:db:postgres": "node test/postgres.js",
"test:db:mongodb": "node test/mongodb.js",
"db:start": "docker-compose -f test/docker/docker-compose.yml up -d",
"db:stop": "docker-compose -f test/docker/docker-compose.yml down",
"test:db:mssql": "node test/mssql.js",
"test:db:fauna": "node test/fauna.js",
"test:integration": "mocha test/integration",
"db:start": "docker-compose -f test/docker/databases.yml up -d",
"db:stop": "docker-compose -f test/docker/databases.yml down",
"prepublishOnly": "npm run build",
"publish:beta": "npm publish --tag beta",
"publish:canary": "npm publish --tag canary",
@@ -36,31 +43,58 @@
"license": "ISC",
"dependencies": {
"crypto-js": "^4.0.0",
"faunadb": "^3.0.1",
"futoin-hkdf": "^1.3.2",
"jose": "^1.27.2",
"jsonwebtoken": "^8.5.1",
"jwt-decode": "^2.2.0",
"nodemailer": "^6.4.6",
"nodemailer": "^6.4.16",
"oauth": "^0.9.15",
"preact": "^10.4.1",
"preact-render-to-string": "^5.1.7",
"querystring": "^0.2.0",
"require_optional": "^1.0.1",
"typeorm": "^0.2.24"
},
"peerDependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
"react": "^16.13.1 || ^17",
"react-dom": "^16.13.1 || ^17"
},
"peerOptionalDependencies": {
"mongodb": "^3.5.9",
"mysql": "^2.18.1",
"mssql": "^6.2.1",
"pg": "^8.2.1",
"@prisma/client": "^2.12.0"
},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6",
"@semantic-release/commit-analyzer": "^8.0.1",
"@semantic-release/github": "^7.2.0",
"@semantic-release/npm": "7.0.8",
"@semantic-release/release-notes-generator": "^9.0.1",
"autoprefixer": "^9.7.6",
"babel-preset-preact": "^2.0.0",
"conventional-changelog-conventionalcommits": "4.4.0",
"cssnano": "^4.1.10",
"dotenv": "^8.2.0",
"mocha": "^8.1.3",
"mongodb": "^3.5.9",
"mssql": "^6.2.1",
"mysql": "^2.18.1",
"pg": "^8.2.1",
"postcss-cli": "^7.1.1",
"postcss-nested": "^4.2.1",
"standard": "^14.3.3"
"puppeteer": "^5.2.1",
"puppeteer-extra": "^3.1.15",
"puppeteer-extra-plugin-stealth": "^2.6.1",
"standard": "^16.0.3"
},
"standard": {
"ignore": [
"test/"
]
}
}

View File

@@ -1,4 +1,4 @@
// Serverless target in Next.js does work if you try to read in files at runtime
// Serverless target in Next.js does not work if you try to read in files at runtime
// that are not JavaScript or JSON (e.g. CSS files).
// https://github.com/iaincollins/next-auth/issues/281
//

519
src/adapters/fauna/index.js Normal file
View File

@@ -0,0 +1,519 @@
import { query as q } from 'faunadb'
import { createHash, randomBytes } from 'crypto'
import logger from '../../lib/logger'
const Adapter = (config, options = {}) => {
const {
faunaClient,
collections = {
User: 'user',
Account: 'account',
Session: 'session',
VerificationRequest: 'verification_request'
},
indexes = {
Account: 'account_by_provider_account_id',
User: 'user_by_email',
Session: 'session_by_token',
VerificationRequest: 'verification_request_by_token'
}
} = config
async function getAdapter (appOptions) {
function _debug (debugCode, ...args) {
logger.debug(`fauna_${debugCode}`, ...args)
}
const defaultSessionMaxAge = 30 * 24 * 60 * 60 * 1000
const sessionMaxAge = (appOptions && appOptions.session && appOptions.session.maxAge)
? appOptions.session.maxAge * 1000
: defaultSessionMaxAge
const sessionUpdateAge = (appOptions && appOptions.session && appOptions.session.updateAge)
? appOptions.session.updateAge * 1000
: 0
async function createUser (profile) {
_debug('createUser', profile)
const timestamp = new Date().toISOString()
const FQL = q.Create(
q.Collection(collections.User), {
data: {
name: profile.name,
email: profile.email,
image: profile.image,
emailVerified: profile.emailVerified
? profile.emailVerified
: false,
createdAt: q.Time(timestamp),
updatedAt: q.Time(timestamp)
}
})
try {
const newUser = await faunaClient.query(FQL)
newUser.data.id = newUser.ref.id
return newUser.data
} catch (error) {
console.error('CREATE_USER', error)
return Promise.reject(new Error('CREATE_USER'))
}
}
async function getUser (id) {
_debug('getUser', id)
const FQL = q.Get(
q.Ref(q.Collection(collections.User), id)
)
try {
const user = await faunaClient.query(FQL)
user.data.id = user.ref.id
return user.data
} catch (error) {
console.error('GET_USER', error)
return Promise.reject(new Error('GET_USER'))
}
}
async function getUserByEmail (email) {
_debug('getUserByEmail', email)
if (!email) {
return null
}
const FQL = q.Let(
{
ref: q.Match(q.Index(indexes.User), email)
},
q.If(
q.Exists(q.Var('ref')),
q.Get(q.Var('ref')),
null
)
)
try {
const user = await faunaClient.query(FQL)
if (user == null) {
return null
}
user.data.id = user.ref.id
return user.data
} catch (error) {
console.error('GET_USER_BY_EMAIL', error)
return Promise.reject(new Error('GET_USER_BY_EMAIL'))
}
}
async function getUserByProviderAccountId (providerId, providerAccountId) {
_debug('getUserByProviderAccountId', providerId, providerAccountId)
const FQL = q.Let(
{
ref: q.Match(
q.Index(indexes.Account),
[providerId, providerAccountId]
)
},
q.If(
q.Exists(q.Var('ref')),
q.Get(
q.Ref(
q.Collection(collections.User),
q.Select(['data', 'userId'],
q.Get(q.Var('ref'))
)
)
),
null
)
)
try {
const user = await faunaClient.query(FQL)
if (user == null) {
return null
}
user.data.id = user.ref.id
return user.data
} catch (error) {
console.error('GET_USER_BY_PROVIDER_ACCOUNT_ID', error)
return Promise.reject(new Error('GET_USER_BY_PROVIDER_ACCOUNT_ID'))
}
}
async function updateUser (user) {
_debug('updateUser', user)
const timestamp = new Date().toISOString()
const FQL = q.Update(
q.Ref(q.Collection(collections.User), user.id),
{
data: {
name: user.name,
email: user.email,
image: user.image,
emailVerified: user.emailVerified ? user.emailVerified : false,
updatedAt: q.Time(timestamp)
}
}
)
try {
const user = await faunaClient.query(FQL)
user.data.id = user.ref.id
return user.data
} catch (error) {
console.error('UPDATE_USER_ERROR', error)
return Promise.reject(new Error('UPDATE_USER_ERROR'))
}
}
async function deleteUser (userId) {
_debug('deleteUser', userId)
const FQL = q.Delete(
q.Ref(q.Collection(collections.User), userId)
)
try {
await faunaClient.query(FQL)
} catch (error) {
console.error('DELETE_USER_ERROR', error)
return Promise.reject(new Error('DELETE_USER_ERROR'))
}
}
async function linkAccount (userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires) {
_debug('linkAccount', userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires)
try {
const timestamp = new Date().toISOString()
const account = await faunaClient.query(
q.Create(q.Collection(collections.Account), {
data: {
userId: userId,
providerId: providerId,
providerType: providerType,
providerAccountId: providerAccountId,
refreshToken: refreshToken,
accessToken: accessToken,
accessTokenExpires: accessTokenExpires,
createdAt: q.Time(timestamp),
updatedAt: q.Time(timestamp)
}
})
)
return account.data
} catch (error) {
console.error('LINK_ACCOUNT_ERROR', error)
return Promise.reject(new Error('LINK_ACCOUNT_ERROR'))
}
}
async function unlinkAccount (userId, providerId, providerAccountId) {
_debug('unlinkAccount', userId, providerId, providerAccountId)
const FQL = q.Delete(
q.Select('ref',
q.Get(
q.Match(
q.Index(indexes.Account),
[providerId, providerAccountId]
)
)
)
)
try {
await faunaClient.query(FQL)
} catch (error) {
console.error('UNLINK_ACCOUNT_ERROR', error)
return Promise.reject(new Error('UNLINK_ACCOUNT_ERROR'))
}
}
async function createSession (user) {
_debug('createSession', user)
let expires = null
if (sessionMaxAge) {
const dateExpires = new Date()
dateExpires.setTime(dateExpires.getTime() + sessionMaxAge)
expires = dateExpires.toISOString()
}
const timestamp = new Date().toISOString()
const FQL =
q.Create(q.Collection(collections.Session), {
data: {
userId: user.id,
expires: q.Time(expires),
sessionToken: randomBytes(32).toString('hex'),
accessToken: randomBytes(32).toString('hex'),
createdAt: q.Time(timestamp),
updatedAt: q.Time(timestamp)
}
})
try {
const session = await faunaClient.query(FQL)
session.data.id = session.ref.id
return session.data
} catch (error) {
console.error('CREATE_SESSION_ERROR', error)
return Promise.reject(new Error('CREATE_SESSION_ERROR'))
}
}
async function getSession (sessionToken) {
_debug('getSession', sessionToken)
try {
const session = await faunaClient.query(
q.Get(
q.Match(
q.Index(indexes.Session),
sessionToken
)
)
)
// Check session has not expired (do not return it if it has)
if (session && session.expires && new Date() > session.expires) {
await _deleteSession(sessionToken)
return null
}
session.data.id = session.ref.id
return session.data
} catch (error) {
console.error('GET_SESSION_ERROR', error)
return Promise.reject(new Error('GET_SESSION_ERROR'))
}
}
async function updateSession (session, force) {
_debug('updateSession', session)
try {
const shouldUpdate = sessionMaxAge && (sessionUpdateAge || sessionUpdateAge === 0) && session.expires
if (!shouldUpdate && !force) {
return null
}
// Calculate last updated date, to throttle write updates to database
// Formula: ({expiry date} - sessionMaxAge) + sessionUpdateAge
// e.g. ({expiry date} - 30 days) + 1 hour
//
// Default for sessionMaxAge is 30 days.
// Default for sessionUpdateAge is 1 hour.
const dateSessionIsDueToBeUpdated = new Date(session.expires)
dateSessionIsDueToBeUpdated.setTime(dateSessionIsDueToBeUpdated.getTime() - sessionMaxAge)
dateSessionIsDueToBeUpdated.setTime(dateSessionIsDueToBeUpdated.getTime() + sessionUpdateAge)
// Trigger update of session expiry date and write to database, only
// if the session was last updated more than {sessionUpdateAge} ago
const currentDate = new Date()
if (currentDate < dateSessionIsDueToBeUpdated && !force) {
return null
}
const newExpiryDate = new Date()
newExpiryDate.setTime(newExpiryDate.getTime() + sessionMaxAge)
const updatedSession = await faunaClient.query(
q.Update(
q.Ref(q.Collection(collections.Session), session.id),
{
data: {
expires: q.Time(newExpiryDate.toISOString()),
updatedAt: q.Time(new Date().toISOString())
}
}
)
)
updatedSession.data.id = updatedSession.ref.id
return updatedSession.data
} catch (error) {
console.error('UPDATE_SESSION_ERROR', error)
return Promise.reject(new Error('UPDATE_SESSION_ERROR'))
}
}
async function _deleteSession (sessionToken) {
const FQL = q.Delete(
q.Select('ref',
q.Get(
q.Match(
q.Index(indexes.Session),
sessionToken
)
)
)
)
return faunaClient.query(FQL)
}
async function deleteSession (sessionToken) {
_debug('deleteSession', sessionToken)
try {
return await _deleteSession(sessionToken)
} catch (error) {
console.error('DELETE_SESSION_ERROR', error)
return Promise.reject(new Error('DELETE_SESSION_ERROR'))
}
}
async function createVerificationRequest (identifier, url, token, secret, provider) {
_debug('createVerificationRequest', identifier)
const { baseUrl } = appOptions
const { sendVerificationRequest, maxAge } = provider
// Store hashed token (using secret as salt) so that tokens cannot be exploited
// even if the contents of the database is compromised
// @TODO Use bcrypt function here instead of simple salted hash
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
let expires = null
if (maxAge) {
const dateExpires = new Date()
dateExpires.setTime(dateExpires.getTime() + (maxAge * 1000))
expires = dateExpires.toISOString()
}
const timestamp = new Date().toISOString()
const FQL = q.Create(
q.Collection(collections.VerificationRequest), {
data: {
identifier: identifier,
token: hashedToken,
expires: expires === null ? null : q.Time(expires),
createdAt: q.Time(timestamp),
updatedAt: q.Time(timestamp)
}
}
)
try {
const verificationRequest = await faunaClient.query(FQL)
// With the verificationCallback on a provider, you can send an email, or queue
// an email to be sent, or perform some other action (e.g. send a text message)
await sendVerificationRequest({ identifier, url, token, baseUrl, provider })
return verificationRequest.data
} catch (error) {
console.error('CREATE_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('CREATE_VERIFICATION_REQUEST_ERROR'))
}
}
async function getVerificationRequest (identifier, token, secret, provider) {
_debug('getVerificationRequest', identifier, token)
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
const FQL = q.Let(
{
ref: q.Match(q.Index(indexes.VerificationRequest), hashedToken)
},
q.If(
q.Exists(q.Var('ref')),
{
ref: q.Var('ref'),
request: q.Select('data', q.Get(q.Var('ref')))
},
null
)
)
try {
const { ref, request: verificationRequest } = await faunaClient.query(FQL)
const nowDate = Date.now()
if (verificationRequest && verificationRequest.expires && verificationRequest.expires < nowDate) {
// Delete the expired request so it cannot be used
await faunaClient.query(
q.Delete(ref)
)
return null
}
return verificationRequest
} catch (error) {
console.error('GET_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('GET_VERIFICATION_REQUEST_ERROR'))
}
}
async function deleteVerificationRequest (identifier, token, secret, provider) {
_debug('deleteVerification', identifier, token)
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
const FQL = q.Delete(
q.Select('ref',
q.Get(
q.Match(
q.Index(indexes.VerificationRequest), hashedToken
)
)
)
)
try {
await faunaClient.query(FQL)
} catch (error) {
console.error('DELETE_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('DELETE_VERIFICATION_REQUEST_ERROR'))
}
}
return Promise.resolve({
createUser,
getUser,
getUserByEmail,
getUserByProviderAccountId,
updateUser,
deleteUser,
linkAccount,
unlinkAccount,
createSession,
getSession,
updateSession,
deleteSession,
createVerificationRequest,
getVerificationRequest,
deleteVerificationRequest
})
}
return {
getAdapter
}
}
export default {
Adapter
}

View File

@@ -1,6 +1,10 @@
import TypeORM from './typeorm'
import Prisma from './prisma'
import Fauna from './fauna'
export default {
Default: TypeORM.Adapter,
TypeORM
TypeORM,
Prisma,
Fauna
}

View File

@@ -0,0 +1,336 @@
import { createHash, randomBytes } from 'crypto'
import { CreateUserError } from '../../lib/errors'
import logger from '../../lib/logger'
const Adapter = (config) => {
const {
prisma,
modelMapping = {
User: 'user',
Account: 'account',
Session: 'session',
VerificationRequest: 'verificationRequest'
}
} = config
const { User, Account, Session, VerificationRequest } = modelMapping
function getCompoundId (providerId, providerAccountId) {
return createHash('sha256').update(`${providerId}:${providerAccountId}`).digest('hex')
}
async function getAdapter (appOptions) {
function debug (debugCode, ...args) {
logger.debug(`PRISMA_${debugCode}`, ...args)
}
if (appOptions && (!appOptions.session || !appOptions.session.maxAge)) {
debug('GET_ADAPTER', 'Session expiry not configured (defaulting to 30 days')
}
const defaultSessionMaxAge = 30 * 24 * 60 * 60 * 1000
const sessionMaxAge = (appOptions && appOptions.session && appOptions.session.maxAge)
? appOptions.session.maxAge * 1000
: defaultSessionMaxAge
const sessionUpdateAge = (appOptions && appOptions.session && appOptions.session.updateAge)
? appOptions.session.updateAge * 1000
: 0
async function createUser (profile) {
debug('CREATE_USER', profile)
try {
return prisma[User].create({
data: {
name: profile.name,
email: profile.email,
image: profile.image,
emailVerified: profile.emailVerified ? profile.emailVerified.toISOString() : null
}
})
} catch (error) {
logger.error('CREATE_USER_ERROR', error)
return Promise.reject(new CreateUserError(error))
}
}
async function getUser (id) {
debug('GET_USER', id)
try {
return prisma[User].findUnique({ where: { id } })
} catch (error) {
logger.error('GET_USER_BY_ID_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_ID_ERROR', error))
}
}
async function getUserByEmail (email) {
debug('GET_USER_BY_EMAIL', email)
try {
if (!email) { return Promise.resolve(null) }
return prisma[User].findUnique({ where: { email } })
} catch (error) {
logger.error('GET_USER_BY_EMAIL_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_EMAIL_ERROR', error))
}
}
async function getUserByProviderAccountId (providerId, providerAccountId) {
debug('GET_USER_BY_PROVIDER_ACCOUNT_ID', providerId, providerAccountId)
try {
const account = await prisma[Account].findUnique({ where: { compoundId: getCompoundId(providerId, providerAccountId) } })
if (!account) { return null }
return prisma[User].findUnique({ where: { id: account.userId } })
} catch (error) {
logger.error('GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR', error))
}
}
async function updateUser (user) {
debug('UPDATE_USER', user)
try {
const { id, name, email, image, emailVerified } = user
return prisma[User].update({
where: { id },
data: {
name,
email,
image,
emailVerified: emailVerified ? emailVerified.toISOString() : null
}
})
} catch (error) {
logger.error('UPDATE_USER_ERROR', error)
return Promise.reject(new Error('UPDATE_USER_ERROR', error))
}
}
async function deleteUser (userId) {
debug('DELETE_USER', userId)
try {
return prisma[User].delete({ where: { id: userId } })
} catch (error) {
logger.error('DELETE_USER_ERROR', error)
return Promise.reject(new Error('DELETE_USER_ERROR', error))
}
}
async function linkAccount (userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires) {
debug('LINK_ACCOUNT', userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires)
try {
return prisma[Account].create({
data: {
accessToken,
refreshToken,
compoundId: getCompoundId(providerId, providerAccountId),
providerAccountId: `${providerAccountId}`,
providerId,
providerType,
accessTokenExpires,
userId
}
})
} catch (error) {
logger.error('LINK_ACCOUNT_ERROR', error)
return Promise.reject(new Error('LINK_ACCOUNT_ERROR', error))
}
}
async function unlinkAccount (userId, providerId, providerAccountId) {
debug('UNLINK_ACCOUNT', userId, providerId, providerAccountId)
try {
return prisma[Account].delete({ where: { compoundId: getCompoundId(providerId, providerAccountId) } })
} catch (error) {
logger.error('UNLINK_ACCOUNT_ERROR', error)
return Promise.reject(new Error('UNLINK_ACCOUNT_ERROR', error))
}
}
async function createSession (user) {
debug('CREATE_SESSION', user)
try {
let expires = null
if (sessionMaxAge) {
const dateExpires = new Date()
dateExpires.setTime(dateExpires.getTime() + sessionMaxAge)
expires = dateExpires.toISOString()
}
return prisma[Session].create({
data: {
expires,
userId: user.id,
sessionToken: randomBytes(32).toString('hex'),
accessToken: randomBytes(32).toString('hex')
}
})
} catch (error) {
logger.error('CREATE_SESSION_ERROR', error)
return Promise.reject(new Error('CREATE_SESSION_ERROR', error))
}
}
async function getSession (sessionToken) {
debug('GET_SESSION', sessionToken)
try {
const session = await prisma[Session].findUnique({ where: { sessionToken } })
// Check session has not expired (do not return it if it has)
if (session && session.expires && new Date() > session.expires) {
await prisma[Session].delete({ where: { sessionToken } })
return null
}
return session
} catch (error) {
logger.error('GET_SESSION_ERROR', error)
return Promise.reject(new Error('GET_SESSION_ERROR', error))
}
}
async function updateSession (session, force) {
debug('UPDATE_SESSION', session)
try {
if (sessionMaxAge && (sessionUpdateAge || sessionUpdateAge === 0) && session.expires) {
// Calculate last updated date, to throttle write updates to database
// Formula: ({expiry date} - sessionMaxAge) + sessionUpdateAge
// e.g. ({expiry date} - 30 days) + 1 hour
//
// Default for sessionMaxAge is 30 days.
// Default for sessionUpdateAge is 1 hour.
const dateSessionIsDueToBeUpdated = new Date(session.expires)
dateSessionIsDueToBeUpdated.setTime(dateSessionIsDueToBeUpdated.getTime() - sessionMaxAge)
dateSessionIsDueToBeUpdated.setTime(dateSessionIsDueToBeUpdated.getTime() + sessionUpdateAge)
// Trigger update of session expiry date and write to database, only
// if the session was last updated more than {sessionUpdateAge} ago
if (new Date() > dateSessionIsDueToBeUpdated) {
const newExpiryDate = new Date()
newExpiryDate.setTime(newExpiryDate.getTime() + sessionMaxAge)
session.expires = newExpiryDate
} else if (!force) {
return null
}
} else {
// If session MaxAge, session UpdateAge or session.expires are
// missing then don't even try to save changes, unless force is set.
if (!force) { return null }
}
const { id, expires } = session
return prisma[Session].update({ where: { id }, data: { expires } })
} catch (error) {
logger.error('UPDATE_SESSION_ERROR', error)
return Promise.reject(new Error('UPDATE_SESSION_ERROR', error))
}
}
async function deleteSession (sessionToken) {
debug('DELETE_SESSION', sessionToken)
try {
return prisma[Session].delete({ where: { sessionToken } })
} catch (error) {
logger.error('DELETE_SESSION_ERROR', error)
return Promise.reject(new Error('DELETE_SESSION_ERROR', error))
}
}
async function createVerificationRequest (identifier, url, token, secret, provider) {
debug('CREATE_VERIFICATION_REQUEST', identifier)
try {
const { baseUrl } = appOptions
const { sendVerificationRequest, maxAge } = provider
// Store hashed token (using secret as salt) so that tokens cannot be exploited
// even if the contents of the database is compromised.
// @TODO Use bcrypt function here instead of simple salted hash
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
let expires = null
if (maxAge) {
const dateExpires = new Date()
dateExpires.setTime(dateExpires.getTime() + (maxAge * 1000))
expires = dateExpires.toISOString()
}
// Save to database
const verificationRequest = await prisma[VerificationRequest].create({
data: {
identifier,
token: hashedToken,
expires
}
})
// With the verificationCallback on a provider, you can send an email, or queue
// an email to be sent, or perform some other action (e.g. send a text message)
await sendVerificationRequest({ identifier, url, token, baseUrl, provider })
return verificationRequest
} catch (error) {
logger.error('CREATE_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('CREATE_VERIFICATION_REQUEST_ERROR', error))
}
}
async function getVerificationRequest (identifier, token, secret, provider) {
debug('GET_VERIFICATION_REQUEST', identifier, token)
try {
// Hash token provided with secret before trying to match it with database
// @TODO Use bcrypt instead of salted SHA-256 hash for token
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
const verificationRequest = await prisma[VerificationRequest].findUnique({ where: { token: hashedToken } })
if (verificationRequest && verificationRequest.expires && new Date() > verificationRequest.expires) {
// Delete verification entry so it cannot be used again
await prisma[VerificationRequest].delete({ where: { token: hashedToken } })
return null
}
return verificationRequest
} catch (error) {
logger.error('GET_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('GET_VERIFICATION_REQUEST_ERROR', error))
}
}
async function deleteVerificationRequest (identifier, token, secret, provider) {
debug('DELETE_VERIFICATION', identifier, token)
try {
// Delete verification entry so it cannot be used again
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
await prisma[VerificationRequest].delete({ where: { token: hashedToken } })
} catch (error) {
logger.error('DELETE_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('DELETE_VERIFICATION_REQUEST_ERROR', error))
}
}
return Promise.resolve({
createUser,
getUser,
getUserByEmail,
getUserByProviderAccountId,
updateUser,
deleteUser,
linkAccount,
unlinkAccount,
createSession,
getSession,
updateSession,
deleteSession,
createVerificationRequest,
getVerificationRequest,
deleteVerificationRequest
})
}
return {
getAdapter
}
}
export default {
Adapter
}

View File

@@ -1,11 +1,13 @@
import { createConnection, getConnection, getManager } from 'typeorm'
import { createConnection, getConnection } from 'typeorm'
import { createHash } from 'crypto'
import require_optional from 'require_optional' // eslint-disable-line camelcase
import { CreateUserError } from '../../lib/errors'
import adapterConfig from './lib/config'
import adapterTransform from './lib/transform'
import Models from './models'
import logger from '../../lib/logger'
import { updateConnectionEntities } from './lib/utils'
const Adapter = (typeOrmConfig, options = {}) => {
// Ensure typeOrmConfigObject is normalized to an object
@@ -28,7 +30,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
// anything to do them). This function updates arguments by reference.
adapterTransform(typeOrmConfigObject, models, options)
const config = adapterConfig.loadConfig(typeOrmConfigObject, { models, ...options })
const config = adapterConfig.loadConfig(typeOrmConfigObject, { ...options, models })
// Create objects from models that can be consumed by functions in the adapter
const User = models.User.model
@@ -67,12 +69,18 @@ const Adapter = (typeOrmConfig, options = {}) => {
await _connect()
}
if (process.env.NODE_ENV !== 'production') {
await updateConnectionEntities(connection, config.entities)
}
// Get manager from connection object
// https://github.com/typeorm/typeorm/blob/master/docs/entity-manager-api.md
const { manager } = connection
// Display debug output if debug option enabled
// @TODO Refactor logger so is passed in appOptions
function debugMessage (debugCode, ...args) {
if (appOptions && appOptions.debug) {
logger.debug(`TYPEORM_${debugCode}`, ...args)
}
function debug (debugCode, ...args) {
logger.debug(`TYPEORM_${debugCode}`, ...args)
}
// The models are primarily designed for ANSI SQL database, but some
@@ -86,7 +94,11 @@ const Adapter = (typeOrmConfig, options = {}) => {
let ObjectId
if (config.type === 'mongodb') {
idKey = '_id'
const mongodb = await import('mongodb')
// Using a dynamic import causes problems for some compilers/bundlers
// that don't handle dynamic imports. To try and work around this we are
// using the same method mongodb uses to load Object ID type, which is to
// use the require_optional loader.
const mongodb = require_optional('mongodb')
ObjectId = mongodb.ObjectId
}
@@ -96,7 +108,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
// Use a conditional to default to 30 day session age if not set - it should
// always be set but a meaningful fallback is helpful to facilitate testing.
if (appOptions && (!appOptions.session || !appOptions.session.maxAge)) {
debugMessage('GET_ADAPTER', 'Session expiry not configured (defaulting to 30 days')
debug('GET_ADAPTER', 'Session expiry not configured (defaulting to 30 days')
}
const defaultSessionMaxAge = 30 * 24 * 60 * 60 * 1000
const sessionMaxAge = (appOptions && appOptions.session && appOptions.session.maxAge)
@@ -107,11 +119,11 @@ const Adapter = (typeOrmConfig, options = {}) => {
: 0
async function createUser (profile) {
debugMessage('CREATE_USER', profile)
debug('CREATE_USER', profile)
try {
// Create user account
const user = new User(profile.name, profile.email, profile.image, profile.emailVerified)
return await getManager().save(user)
return await manager.save(user)
} catch (error) {
logger.error('CREATE_USER_ERROR', error)
return Promise.reject(new CreateUserError(error))
@@ -119,7 +131,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function getUser (id) {
debugMessage('GET_USER', id)
debug('GET_USER', id)
// In the very specific case of both using JWT for storing session data
// and using MongoDB to store user data, the ID is a string rather than
@@ -132,7 +144,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
try {
return connection.getRepository(User).findOne({ [idKey]: id })
return manager.findOne(User, { [idKey]: id })
} catch (error) {
logger.error('GET_USER_BY_ID_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_ID_ERROR', error))
@@ -140,10 +152,10 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function getUserByEmail (email) {
debugMessage('GET_USER_BY_EMAIL', email)
debug('GET_USER_BY_EMAIL', email)
try {
if (!email) { return Promise.resolve(null) }
return connection.getRepository(User).findOne({ email })
return manager.findOne(User, { email })
} catch (error) {
logger.error('GET_USER_BY_EMAIL_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_EMAIL_ERROR', error))
@@ -151,11 +163,11 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function getUserByProviderAccountId (providerId, providerAccountId) {
debugMessage('GET_USER_BY_PROVIDER_ACCOUNT_ID', providerId, providerAccountId)
debug('GET_USER_BY_PROVIDER_ACCOUNT_ID', providerId, providerAccountId)
try {
const account = await connection.getRepository(Account).findOne({ providerId, providerAccountId })
const account = await manager.findOne(Account, { providerId, providerAccountId })
if (!account) { return null }
return connection.getRepository(User).findOne({ [idKey]: account.userId })
return manager.findOne(User, { [idKey]: account.userId })
} catch (error) {
logger.error('GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR', error)
return Promise.reject(new Error('GET_USER_BY_PROVIDER_ACCOUNT_ID_ERROR', error))
@@ -163,22 +175,22 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function updateUser (user) {
debugMessage('UPDATE_USER', user)
return getManager().save(user)
debug('UPDATE_USER', user)
return manager.save(User, user)
}
async function deleteUser (userId) {
debugMessage('DELETE_USER', userId)
debug('DELETE_USER', userId)
// @TODO Delete user from DB
return false
}
async function linkAccount (userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires) {
debugMessage('LINK_ACCOUNT', userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires)
debug('LINK_ACCOUNT', userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires)
try {
// Create provider account linked to user
const account = new Account(userId, providerId, providerType, providerAccountId, refreshToken, accessToken, accessTokenExpires)
return getManager().save(account)
return manager.save(account)
} catch (error) {
logger.error('LINK_ACCOUNT_ERROR', error)
return Promise.reject(new Error('LINK_ACCOUNT_ERROR', error))
@@ -186,7 +198,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function unlinkAccount (userId, providerId, providerAccountId) {
debugMessage('UNLINK_ACCOUNT', userId, providerId, providerAccountId)
debug('UNLINK_ACCOUNT', userId, providerId, providerAccountId)
// @TODO Get current user from DB
// @TODO Delete [provider] object from user object
// @TODO Save changes to user object in DB
@@ -194,7 +206,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function createSession (user) {
debugMessage('CREATE_SESSION', user)
debug('CREATE_SESSION', user)
try {
let expires = null
if (sessionMaxAge) {
@@ -205,7 +217,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
const session = new Session(user.id, expires)
return getManager().save(session)
return manager.save(session)
} catch (error) {
logger.error('CREATE_SESSION_ERROR', error)
return Promise.reject(new Error('CREATE_SESSION_ERROR', error))
@@ -213,9 +225,9 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function getSession (sessionToken) {
debugMessage('GET_SESSION', sessionToken)
debug('GET_SESSION', sessionToken)
try {
const session = await connection.getRepository(Session).findOne({ sessionToken })
const session = await manager.findOne(Session, { sessionToken })
// Check session has not expired (do not return it if it has)
if (session && session.expires && new Date() > new Date(session.expires)) {
@@ -231,7 +243,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function updateSession (session, force) {
debugMessage('UPDATE_SESSION', session)
debug('UPDATE_SESSION', session)
try {
if (sessionMaxAge && (sessionUpdateAge || sessionUpdateAge === 0) && session.expires) {
// Calculate last updated date, to throttle write updates to database
@@ -259,7 +271,7 @@ const Adapter = (typeOrmConfig, options = {}) => {
if (!force) { return null }
}
return getManager().save(session)
return manager.save(Session, session)
} catch (error) {
logger.error('UPDATE_SESSION_ERROR', error)
return Promise.reject(new Error('UPDATE_SESSION_ERROR', error))
@@ -267,9 +279,9 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function deleteSession (sessionToken) {
debugMessage('DELETE_SESSION', sessionToken)
debug('DELETE_SESSION', sessionToken)
try {
return await connection.getRepository(Session).delete({ sessionToken })
return await manager.delete(Session, { sessionToken })
} catch (error) {
logger.error('DELETE_SESSION_ERROR', error)
return Promise.reject(new Error('DELETE_SESSION_ERROR', error))
@@ -277,9 +289,9 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function createVerificationRequest (identifier, url, token, secret, provider) {
debugMessage('CREATE_VERIFICATION_REQUEST', identifier)
debug('CREATE_VERIFICATION_REQUEST', identifier)
try {
const { site } = appOptions
const { baseUrl } = appOptions
const { sendVerificationRequest, maxAge } = provider
// Store hashed token (using secret as salt) so that tokens cannot be exploited
@@ -296,11 +308,11 @@ const Adapter = (typeOrmConfig, options = {}) => {
// Save to database
const newVerificationRequest = new VerificationRequest(identifier, hashedToken, expires)
const verificationRequest = await getManager().save(newVerificationRequest)
const verificationRequest = await manager.save(newVerificationRequest)
// With the verificationCallback on a provider, you can send an email, or queue
// an email to be sent, or perform some other action (e.g. send a text message)
await sendVerificationRequest({ identifier, url, token, site, provider })
await sendVerificationRequest({ identifier, url, token, baseUrl, provider })
return verificationRequest
} catch (error) {
@@ -310,16 +322,16 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function getVerificationRequest (identifier, token, secret, provider) {
debugMessage('GET_VERIFICATION_REQUEST', identifier, token)
debug('GET_VERIFICATION_REQUEST', identifier, token)
try {
// Hash token provided with secret before trying to match it with database
// @TODO Use bcrypt instead of salted SHA-256 hash for token
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
const verificationRequest = await connection.getRepository(VerificationRequest).findOne({ identifier, token: hashedToken })
const verificationRequest = await manager.findOne(VerificationRequest, { identifier, token: hashedToken })
if (verificationRequest && verificationRequest.expires && new Date() > new Date(verificationRequest.expires)) {
// Delete verification entry so it cannot be used again
await connection.getRepository(VerificationRequest).delete({ token: hashedToken })
await manager.delete(VerificationRequest, { token: hashedToken })
return null
}
@@ -331,11 +343,11 @@ const Adapter = (typeOrmConfig, options = {}) => {
}
async function deleteVerificationRequest (identifier, token, secret, provider) {
debugMessage('DELETE_VERIFICATION', identifier, token)
debug('DELETE_VERIFICATION', identifier, token)
try {
// Delete verification entry so it cannot be used again
const hashedToken = createHash('sha256').update(`${token}${secret}`).digest('hex')
await connection.getRepository(VerificationRequest).delete({ token: hashedToken })
await manager.delete(VerificationRequest, { token: hashedToken })
} catch (error) {
logger.error('DELETE_VERIFICATION_REQUEST_ERROR', error)
return Promise.reject(new Error('DELETE_VERIFICATION_REQUEST_ERROR', error))

View File

@@ -25,6 +25,7 @@ const parseConnectionString = (configString) => {
config.username = parsedUrl.username
config.password = parsedUrl.password
config.database = parsedUrl.pathname.replace(/^\//, '').replace(/\?(.*)$/, '')
config.options = {}
}
// This option is recommended by mongodb
@@ -32,6 +33,11 @@ const parseConnectionString = (configString) => {
config.useUnifiedTopology = true
}
// Prevents warning about deprecated option (sets default value)
if (config.type === 'mssql') {
config.options.enableArithAbort = true
}
if (parsedUrl.search) {
parsedUrl.search.replace(/^\?/, '').split('&').forEach(keyValuePair => {
let [key, value] = keyValuePair.split('=')
@@ -53,7 +59,7 @@ const parseConnectionString = (configString) => {
const loadConfig = (config, { models, namingStrategy }) => {
const defaultConfig = {
name: 'default',
name: 'nextauth',
autoLoadEntities: true,
entities: [
new EntitySchema(models.User.schema),

View File

@@ -1,51 +1,45 @@
// Perform transforms on SQL models so they can be used with other databases
import { SnakeCaseNamingStrategy, CamelCaseNamingStrategy } from './naming-strategies'
const postgres = (models, options) => {
const postgresTransform = (models, options) => {
// Apply snake case naming strategy for Postgres databases
if (!options.namingStrategy) {
options.namingStrategy = new SnakeCaseNamingStrategy()
}
// Only transforms models that are not custom models
const { models: customModels = {} } = options
// For Postgres we need to use the `timestamp with time zone` type
// aka `timestamptz` to store timestamps correctly in UTC.
if (!customModels.User) {
for (const column in models.User.schema.columns) {
if (models.User.schema.columns[column].type === 'timestamp') {
models.User.schema.columns[column].type = 'timestamptz'
}
}
}
if (!customModels.Account) {
for (const column in models.Account.schema.columns) {
if (models.Account.schema.columns[column].type === 'timestamp') {
models.Account.schema.columns[column].type = 'timestamptz'
}
}
}
if (!customModels.Session) {
for (const column in models.Session.schema.columns) {
if (models.Session.schema.columns[column].type === 'timestamp') {
models.Session.schema.columns[column].type = 'timestamptz'
}
}
}
if (!customModels.VerificationRequest) {
for (const column in models.VerificationRequest.schema.columns) {
if (models.VerificationRequest.schema.columns[column].type === 'timestamp') {
models.VerificationRequest.schema.columns[column].type = 'timestamptz'
for (const model in models) {
for (const column in models[model].schema.columns) {
if (models[model].schema.columns[column].type === 'timestamp') {
models[model].schema.columns[column].type = 'timestamptz'
}
}
}
}
const mongodb = (models, options) => {
const mysqlTransform = (models, options) => {
// Apply snake case naming strategy for MySQL databases
if (!options.namingStrategy) {
options.namingStrategy = new SnakeCaseNamingStrategy()
}
// For MySQL we default milisecond precision of all timestamps to 6 digits.
// This ensures all timestamp fields use the same precision (unless explictly
// configured otherwise) and that values in MySQL match those Postgress.
for (const model in models) {
for (const column in models[model].schema.columns) {
if (models[model].schema.columns[column].type === 'timestamp') {
// If precision explictly set (including to null) don't change it
if (typeof models[model].schema.columns[column].precision === 'undefined') {
models[model].schema.columns[column].precision = 6
}
}
}
}
}
const mongodbTransform = (models, options) => {
// A CamelCase naming strategy is used for all document databases
if (!options.namingStrategy) {
options.namingStrategy = new CamelCaseNamingStrategy()
@@ -65,56 +59,38 @@ const mongodb = (models, options) => {
// see the result of queries like find() is wrong. You will see the same
// Object ID in every property of type Object ID in the result (but the
// database will look fine); so use `type: 'objectId'` for them instead.
// Only transforms models that are not custom models
const { models: customModels = {} } = options
if (!customModels.User) {
delete models.User.schema.columns.id.type
models.User.schema.columns.id.objectId = true
// The options `unique: true` and `nullable: true` don't work the same
// with MongoDB as they do with SQL databases like MySQL and Postgres,
// we also to add sparce to the index. This still doesn't allow multiple
// *null* values, but does allow some records to omit the property.
delete models.User.schema.columns.email.unique
models.User.schema.indices = [
{
name: 'email',
unique: true,
sparse: true,
columns: ['email']
}
]
for (const model in models) {
delete models[model].schema.columns.id.type
models[model].schema.columns.id.objectId = true
}
if (!customModels.Account) {
delete models.Account.schema.columns.id.type
models.Account.schema.columns.id.objectId = true
models.Account.schema.columns.userId.type = 'objectId'
}
// Ensure reference to User ID in other models are Object IDs
// This needs to done for any properties that reference another entity by ID
models.Account.schema.columns.userId.type = 'objectId'
models.Session.schema.columns.userId.type = 'objectId'
if (!customModels.Session) {
delete models.Session.schema.columns.id.type
models.Session.schema.columns.id.objectId = true
models.Session.schema.columns.userId.type = 'objectId'
}
// The options `unique: true` and `nullable: true` don't work the same
// with MongoDB as they do with SQL databases like MySQL and Postgres,
// we need to create a sparse index to only allow unique values, while
// still allowing multiple entires to omit the email address.
delete models.User.schema.columns.email.unique
if (!customModels.VerificationRequest) {
delete models.VerificationRequest.schema.columns.id.type
models.VerificationRequest.schema.columns.id.objectId = true
}
if (!models.User.schema.indices) { models.User.schema.indices = [] }
models.User.schema.indices.push({
name: 'email',
unique: true,
sparse: true,
columns: ['email']
})
}
const sqlite = (models, options) => {
const sqliteTransform = (models, options) => {
// Apply snake case naming strategy for SQLite databases
if (!options.namingStrategy) {
options.namingStrategy = new SnakeCaseNamingStrategy()
}
// Only transforms models that are not custom models
const { models: customModels = {} } = options
// SQLite does not support `timestamp` fields so we remap them to `datetime`
// in all models.
//
@@ -123,51 +99,66 @@ const sqlite = (models, options) => {
//
// NB: SQLite adds 'create' and 'update' fields to allow rows, but that is
// specific to SQLite and so we ignore that behaviour.
if (!customModels.User) {
for (const column in models.User.schema.columns) {
if (models.User.schema.columns[column].type === 'timestamp') {
models.User.schema.columns[column].type = 'datetime'
}
}
}
if (!customModels.Account) {
for (const column in models.Account.schema.columns) {
if (models.Account.schema.columns[column].type === 'timestamp') {
models.Account.schema.columns[column].type = 'datetime'
}
}
}
if (!customModels.Session) {
for (const column in models.Session.schema.columns) {
if (models.Session.schema.columns[column].type === 'timestamp') {
models.Session.schema.columns[column].type = 'datetime'
}
}
}
if (!customModels.VerificationRequest) {
for (const column in models.VerificationRequest.schema.columns) {
if (models.VerificationRequest.schema.columns[column].type === 'timestamp') {
models.VerificationRequest.schema.columns[column].type = 'datetime'
for (const model in models) {
for (const column in models[model].schema.columns) {
if (models[model].schema.columns[column].type === 'timestamp') {
models[model].schema.columns[column].type = 'datetime'
}
}
}
}
const mssqlTransform = (models, options) => {
// Apply snake case naming strategy for SQL Server databases
if (!options.namingStrategy) {
// @TODO Add TitleCase instead as more common MSSQL convention?
options.namingStrategy = new SnakeCaseNamingStrategy()
}
// SQL Server deprecated TIMESTAMP in favor of ROWVERSION.
// But ROWVERSION is not what it was intended in the other adapters.
for (const model in models) {
for (const column in models[model].schema.columns) {
if (models[model].schema.columns[column].type === 'timestamp') {
models[model].schema.columns[column].type = 'datetime'
}
}
}
// Support UNIQUE on on User.email that allows duplicate NULL values
// Note: This is ANSI SQL behaviour for UNIQUE not default in SQL Server
delete models.User.schema.columns.email.unique
if (!models.User.schema.indices) { models.User.schema.indices = [] }
models.User.schema.indices.push({
name: 'email',
columns: ['email'],
unique: true,
where: 'email IS NOT NULL'
})
}
export default (config, models, options) => {
// @TODO Refactor into switch statement
if ((config.type && config.type.startsWith('mongodb')) ||
(config.url && config.url.startsWith('mongodb'))) {
mongodb(models, options)
mongodbTransform(models, options)
} else if ((config.type && config.type.startsWith('postgres')) ||
(config.url && config.url.startsWith('postgres'))) {
postgres(models, options)
postgresTransform(models, options)
} else if ((config.type && config.type.startsWith('mysql')) ||
(config.url && config.url.startsWith('mysql'))) {
mysqlTransform(models, options)
} else if ((config.type && config.type.startsWith('sqlite')) ||
(config.url && config.url.startsWith('sqlite'))) {
sqlite(models, options)
sqliteTransform(models, options)
} else if ((config.type && config.type.startsWith('mssql')) ||
(config.url && config.url.startsWith('mssql'))) {
mssqlTransform(models, options)
} else {
// Apply snake case naming strategy by default for SQL databases
// For all other SQL databases (e.g. MySQL) apply snake case naming
// strategy, but otherwise use the models and schemas as they are.
if (!options.namingStrategy) {
options.namingStrategy = new SnakeCaseNamingStrategy()
}

View File

@@ -0,0 +1,18 @@
const entitiesChanged = (prevEntities, newEntities) => {
if (prevEntities.length !== newEntities.length) return true
for (let i = 0; i < prevEntities.length; i++) {
if (prevEntities[i] !== newEntities[i]) return true
}
return false
}
export const updateConnectionEntities = async (connection, entities) => {
// Check if the entities passed have changed and if so replace them
// and re-sync the typeorm connection.
if (!connection || !entitiesChanged(connection.options.entities, entities)) return
connection.options.entities = entities
connection.buildMetadatas()
if (connection.options.synchronize) {
await connection.synchronize()
}
}

View File

@@ -1,172 +1,286 @@
// fetch() is built in to Next.js 9.4 (you can use a polyfill if using an older version)
/// Note: fetch() is built in to Next.js 9.4
//
// Note about signIn() and signOut() methods:
//
// On signIn() and signOut() we pass 'json: true' to request a response in JSON
// instead of HTTP as redirect URLs on other domains are not returned to
// requests made using the fetch API in the browser, and we need to ask the API
// to return the response as a JSON object (the end point still defaults to
// returning an HTTP response with a redirect for non-JavaScript clients).
//
// We use HTTP POST requests with CSRF Tokens to protect against CSRF attacks.
/* global fetch:false */
import { useState, useEffect, useContext, createContext, createElement } from 'react'
import logger from '../lib/logger'
import parseUrl from '../lib/parse-url'
// This behaviour mirrors the default behaviour for getting the site name that
// happens server side in server/index.js
// 1. An empty value is legitimate when the code is being invoked client side as
// relative URLs are valid in that context and so defaults to empty.
// 2. When invoked server side the value is picked up from an environment
// variable and defaults to 'http://localhost:3000'.
const __NEXTAUTH = {
site: '',
basePath: '/api/auth',
clientMaxAge: 0 // e.g. 0 == disabled, 60 == 60 seconds
baseUrl: parseUrl(process.env.NEXTAUTH_URL || process.env.VERCEL_URL).baseUrl,
basePath: parseUrl(process.env.NEXTAUTH_URL).basePath,
keepAlive: 0, // 0 == disabled (don't send); 60 == send every 60 seconds
clientMaxAge: 0, // 0 == disabled (only use cache); 60 == sync if last checked > 60 seconds ago
// Properties starting with _ are used for tracking internal app state
_clientLastSync: 0, // used for timestamp since last sycned (in seconds)
_clientSyncTimer: null, // stores timer for poll interval
_eventListenersAdded: false, // tracks if event listeners have been added,
_clientSession: undefined, // stores last session response from hook,
// Generate a unique ID to make it possible to identify when a message
// was sent from this tab/window so it can be ignored to avoid event loops.
_clientId: Math.random().toString(36).substring(2) + Date.now().toString(36),
// Used to store to function export by getSession() hook
_getSession: () => {}
}
let __NEXTAUTH_EVENT_LISTENER_ADDED = false
// Add event listners on load
if (typeof window !== 'undefined') {
if (__NEXTAUTH._eventListenersAdded === false) {
__NEXTAUTH._eventListenersAdded = true
// Listen for storage events and update session if event fired from
// another window (but suppress firing another event to avoid a loop)
window.addEventListener('storage', async (event) => {
if (event.key === 'nextauth.message') {
const message = JSON.parse(event.newValue)
if (message.event && message.event === 'session' && message.data) {
// Ignore storage events fired from the same window that created them
if (__NEXTAUTH._clientId === message.clientId) {
return
}
// Fetch new session data but pass 'true' to it not to fire an event to
// avoid an infinite loop.
//
// Note: We could pass session data through and do something like
// `setData(message.data)` but that can cause problems depending
// on how the session object is being used in the client; it is
// more robust to have each window/tab fetch it's own copy of the
// session object rather than share it across instances.
await __NEXTAUTH._getSession({ event: 'storage' })
}
}
})
// Listen for window focus/blur events
window.addEventListener('focus', async (event) => __NEXTAUTH._getSession({ event: 'focus' }))
window.addEventListener('blur', async (event) => __NEXTAUTH._getSession({ event: 'blur' }))
}
}
// Method to set options. The documented way is to use the provider, but this
// method is being left in as an alternative, that will be helpful if/when we
// expose a vanilla JavaScript version that doesn't depend on React.
const setOptions = ({
site,
baseUrl,
basePath,
clientMaxAge
clientMaxAge,
keepAlive
} = {}) => {
if (site) { __NEXTAUTH.site = site }
if (baseUrl) { __NEXTAUTH.baseUrl = baseUrl }
if (basePath) { __NEXTAUTH.basePath = basePath }
if (clientMaxAge) { __NEXTAUTH.clientMaxAge = clientMaxAge }
if (keepAlive) {
__NEXTAUTH.keepAlive = keepAlive
if (typeof window !== 'undefined' && keepAlive > 0) {
// Clear existing timer (if there is one)
if (__NEXTAUTH._clientSyncTimer !== null) { clearTimeout(__NEXTAUTH._clientSyncTimer) }
// Set next timer to trigger in number of seconds
__NEXTAUTH._clientSyncTimer = setTimeout(async () => {
// Only invoke keepalive when a session exists
if (__NEXTAUTH._clientSession) {
await __NEXTAUTH._getSession({ event: 'timer' })
}
}, keepAlive * 1000)
}
}
}
// Universal method (client + server)
const getSession = async ({ req } = {}) => {
const baseUrl = _baseUrl()
const options = req ? { headers: { cookie: req.headers.cookie } } : {}
const session = await _fetchData(`${baseUrl}/session`, options)
_sendMessage({ event: 'session', data: { trigger: 'getSession' } })
const getSession = async ({ req, ctx, triggerEvent = true } = {}) => {
// If passed 'appContext' via getInitialProps() in _app.js then get the req
// object from ctx and use that for the req value to allow getSession() to
// work seemlessly in getInitialProps() on server side pages *and* in _app.js.
if (!req && ctx && ctx.req) { req = ctx.req }
const baseUrl = _apiBaseUrl()
const fetchOptions = req ? { headers: { cookie: req.headers.cookie } } : {}
const session = await _fetchData(`${baseUrl}/session`, fetchOptions)
if (triggerEvent) {
_sendMessage({ event: 'session', data: { trigger: 'getSession' } })
}
return session
}
// Universal method (client + server)
const getProviders = async () => {
const baseUrl = _baseUrl()
return _fetchData(`${baseUrl}/providers`)
const getCsrfToken = async ({ req, ctx } = {}) => {
// If passed 'appContext' via getInitialProps() in _app.js then get the req
// object from ctx and use that for the req value to allow getCsrfToken() to
// work seemlessly in getInitialProps() on server side pages *and* in _app.js.
if (!req && ctx && ctx.req) { req = ctx.req }
const baseUrl = _apiBaseUrl()
const fetchOptions = req ? { headers: { cookie: req.headers.cookie } } : {}
const data = await _fetchData(`${baseUrl}/csrf`, fetchOptions)
return data && data.csrfToken ? data.csrfToken : null
}
// Universal method (client + server)
const getCsrfToken = async () => {
const baseUrl = _baseUrl()
const data = await _fetchData(`${baseUrl}/csrf`)
return data && data.csrfToken ? data.csrfToken : null
// Universal method (client + server); does not require request headers
const getProviders = async () => {
const baseUrl = _apiBaseUrl()
return _fetchData(`${baseUrl}/providers`)
}
// Context to store session data globally
const SessionContext = createContext()
// Client side method
// Hook to access the session data stored in the context
const useSession = (session) => {
// Try to use context if we can
const value = useContext(SessionContext)
// If we have no Provider in the tree we call the actual hook for fetching the session
// If we have no Provider in the tree, call the actual hook
if (value === undefined) {
return useSessionData(session)
return _useSessionHook(session)
}
return value
}
// Internal hook for getting session from the api.
const useSessionData = (session) => {
const clientMaxAge = __NEXTAUTH.clientMaxAge * 1000
const _useSessionHook = (session) => {
const [data, setData] = useState(session)
const [loading, setLoading] = useState(true)
const _getSession = async (sendEvent = true) => {
try {
setData(await getSession())
setLoading(false)
// Send event to trigger other tabs to update (unless sendEvent is false)
if (sendEvent) {
_sendMessage({ event: 'session', data: { trigger: 'useSessionData' } })
}
useEffect(() => {
const _getSession = async ({ event = null } = {}) => {
try {
const triggredByEvent = (event !== null)
const triggeredByStorageEvent = !!((event && event === 'storage'))
if (typeof window !== 'undefined' && __NEXTAUTH_EVENT_LISTENER_ADDED === false) {
__NEXTAUTH_EVENT_LISTENER_ADDED = true
window.addEventListener('storage', async (event) => {
if (event.key === 'nextauth.message') {
const message = JSON.parse(event.newValue)
if (message.event && message.event === 'session' && message.data) {
// Fetch new session data but tell it not to fire an event to
// avoid an infinite loop.
//
// Note: We could pass session data through and do something like
// `setData(message.data)` but that causes problems depending on
// how the session object is being used and may expose session
// data to 3rd party scripts, it's safer to update the session
// this way.
await _getSession(false)
}
const clientMaxAge = __NEXTAUTH.clientMaxAge
const clientLastSync = parseInt(__NEXTAUTH._clientLastSync)
const currentTime = Math.floor(new Date().getTime() / 1000)
const clientSession = __NEXTAUTH._clientSession
// Updates triggered by a storage event *always* trigger an update and we
// always update if we don't have any value for the current session state.
if (triggeredByStorageEvent === false && clientSession !== undefined) {
if (clientMaxAge === 0 && triggredByEvent !== true) {
// If there is no time defined for when a session should be considered
// stale, then it's okay to use the value we have until an event is
// triggered which updates it.
return
} else if (clientMaxAge > 0 && clientSession === null) {
// If the client doesn't have a session then we don't need to call
// the server to check if it does (if they have signed in via another
// tab or window that will come through as a triggeredByStorageEvent
// event and will skip this logic)
return
} else if (clientMaxAge > 0 && currentTime < (clientLastSync + clientMaxAge)) {
// If the session freshness is within clientMaxAge then don't request
// it again on this call (avoids too many invokations).
return
}
})
}
}
// If CLIENT_MAXAGE is greater than zero, trigger auto re-fetching session
if (clientMaxAge > 0) {
setTimeout(async (session) => {
await _getSession()
}, clientMaxAge)
if (clientSession === undefined) { __NEXTAUTH._clientSession = null }
// Update clientLastSync before making response to avoid repeated
// invokations that would otherwise be triggered while we are still
// waiting for a response.
__NEXTAUTH._clientLastSync = Math.floor(new Date().getTime() / 1000)
// If this call was invoked via a storage event (i.e. another window) then
// tell getSession not to trigger an event when it calls to avoid an
// infinate loop.
const triggerEvent = (triggeredByStorageEvent === false)
const newClientSessionData = await getSession({ triggerEvent })
// Save session state internally, just so we can track that we've checked
// if a session exists at least once.
__NEXTAUTH._clientSession = newClientSessionData
setData(newClientSessionData)
setLoading(false)
} catch (error) {
logger.error('CLIENT_USE_SESSION_ERROR', error)
}
} catch (error) {
logger.error('CLIENT_USE_SESSION_ERROR', error)
}
}
useEffect(() => { _getSession() }, [])
__NEXTAUTH._getSession = _getSession
_getSession()
})
return [data, loading]
}
// Client side method
const signin = async (provider, args) => {
const signIn = async (provider, args = {}, authParams = {}) => {
const baseUrl = _apiBaseUrl()
const callbackUrl = (args && args.callbackUrl) ? args.callbackUrl : window.location
if (!provider) {
// Redirect to sign in page if no provider specified
const baseUrl = _baseUrl()
window.location = `${baseUrl}/signin?callbackUrl=${encodeURIComponent(callbackUrl)}`
return
}
const providers = await getProviders()
if (!providers[provider]) {
// Redirect to sign in page if no valid provider specified
if (!provider || !providers[provider]) {
// If Provider not recognized, redirect to sign in page
const baseUrl = _baseUrl()
window.location = `${baseUrl}/signin?callbackUrl=${encodeURIComponent(callbackUrl)}`
} else if (providers[provider].type === 'oauth') {
// If is an OAuth provider, redirect to providers[provider].signinUrl
window.location = `${providers[provider].signinUrl}?callbackUrl=${encodeURIComponent(callbackUrl)}`
} else {
// If is any other provider type, POST to providers[provider].signinUrl (with CSRF Token)
const options = {
let signInUrl = (providers[provider].type === 'credentials')
? `${baseUrl}/callback/${provider}`
: `${baseUrl}/signin/${provider}`
if (authParams) {
signInUrl += `?${new URLSearchParams(authParams).toString()}`
}
// If is any other provider type, POST to provider URL with CSRF Token,
// callback URL and any other parameters supplied.
const fetchOptions = {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: _encodedForm({
...args,
csrfToken: await getCsrfToken(),
callbackUrl: callbackUrl,
...args
json: true
})
}
const res = await fetch(providers[provider].signinUrl, options)
window.location = res.url ? res.url : callbackUrl
const res = await fetch(signInUrl, fetchOptions)
const data = await res.json()
window.location = data.url ? data.url : callbackUrl
}
}
// Client side method
const signout = async (args) => {
const signOut = async (args = {}) => {
const callbackUrl = (args && args.callbackUrl) ? args.callbackUrl : window.location
const baseUrl = _baseUrl()
const options = {
const baseUrl = _apiBaseUrl()
const fetchOptions = {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: _encodedForm({
csrfToken: await getCsrfToken(),
callbackUrl: callbackUrl
callbackUrl: callbackUrl,
json: true
})
}
const res = await fetch(`${baseUrl}/signout`, options)
const res = await fetch(`${baseUrl}/signout`, fetchOptions)
const data = await res.json()
_sendMessage({ event: 'session', data: { trigger: 'signout' } })
window.location = res.url ? res.url : callbackUrl
window.location = data.url ? data.url : callbackUrl
}
// Provider to wrap the app in to make session data available globally
@@ -186,7 +300,18 @@ const _fetchData = async (url, options = {}) => {
}
}
const _baseUrl = () => `${__NEXTAUTH.site}${__NEXTAUTH.basePath}`
const _apiBaseUrl = () => {
if (typeof window === 'undefined') {
// NEXTAUTH_URL should always be set explicitly to support server side calls - log warning if not set
if (!process.env.NEXTAUTH_URL) { logger.warn('NEXTAUTH_URL', 'NEXTAUTH_URL environment variable not set') }
// Return absolute path when called server side
return `${__NEXTAUTH.baseUrl}${__NEXTAUTH.basePath}`
} else {
// Return relative path when called client side
return __NEXTAUTH.basePath
}
}
const _encodedForm = (formData) => {
return Object.keys(formData).map((key) => {
@@ -196,27 +321,29 @@ const _encodedForm = (formData) => {
const _sendMessage = (message) => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('nextauth.message', JSON.stringify(message)) // eslint-disable-line
const timestamp = Math.floor(new Date().getTime() / 1000)
localStorage.setItem('nextauth.message', JSON.stringify({ ...message, clientId: __NEXTAUTH._clientId, timestamp })) // eslint-disable-line
}
}
export default {
// Call config() from _app.js to set options globally in the app.
// You need to set at least the site name to use server side calls.
options: setOptions,
getSession,
getCsrfToken,
getProviders,
useSession,
signIn,
signOut,
Provider,
/* Deprecated / unsupported features below this line */
// Use setOptions() set options globally in the app.
setOptions,
// Some methods are exported with more than one name. This provides
// flexibility over how they can be invoked and compatibility with earlier
// releases (going back to v1 and earlier v2 beta releases).
// e.g. NextAuth.session() or const { getSession } from 'next-auth/client'
// Some methods are exported with more than one name. This provides some
// flexibility over how they can be invoked and backwards compatibility
// with earlier releases.
options: setOptions,
session: getSession,
providers: getProviders,
csrfToken: getCsrfToken,
getSession,
getProviders,
getCsrfToken,
useSession,
Provider,
signin,
signout
signin: signIn,
signout: signOut
}

View File

@@ -1,14 +1,18 @@
:root {
--color-background: #fff;
--color-primary: #444;
--color-control-border: #bbb;
--color-button-hover-background: #f9f9f9;
--color-button-active-background: #f5f5f5;
--color-button-active-background: #f9f9f9;
--color-button-active-border: #aaa;
--border-width: 1px;
--border-radius: .3rem;
--color-error: #c94b4b;
--color-info: #157efb;
--color-seperator: #ccc;
}
body {
background-color: var(--color-background);
margin: 0;
padding: 0;
font-family: -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, sans-serif, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
@@ -39,7 +43,7 @@ input[type] {
width: 100%;
padding: .5rem 1rem;
border: var(--border-width) solid var(--color-control-border);
background: #fff;
background: var(--color-background);
font-size: 1rem;
border-radius: var(--border-radius);
box-shadow: inset 0 .1rem .2rem rgba(0,0,0,.2);
@@ -61,7 +65,7 @@ a.button {
line-height: 1rem;
&:link,
&:visited {
background-color: #fff;
background-color: var(--color-background);
color: var(--color-primary);
}
}
@@ -72,21 +76,20 @@ a.button {
padding: .75rem 1rem;
border: var(--border-width) solid var(--color-control-border);
color: var(--color-primary);
background-color: #fff;
background-color: var(--color-background);
font-size: 1rem;
border-radius: var(--border-radius);
transition: all .1s ease-in-out;
box-shadow: 0 0.15rem 0.3rem rgba(0,0,0,.15), inset 0 .1rem .2rem #fff, inset 0 -.1rem .1rem rgba(0,0,0,.05);
box-shadow: 0 0.15rem 0.3rem rgba(0,0,0,.15), inset 0 .1rem .2rem var(--color-background), inset 0 -.1rem .1rem rgba(0,0,0,.05);
font-weight: 500;
position: relative;
&:hover {
background-color: var(--color-button-hover-background);
cursor: pointer;
}
&:active {
box-shadow: 0 0.15rem 0.3rem rgba(0,0,0,.15), inset 0 .1rem .2rem #fff, inset 0 -.1rem .1rem rgba(0,0,0,.1);
box-shadow: 0 0.15rem 0.3rem rgba(0,0,0,.15), inset 0 .1rem .2rem var(--color-background), inset 0 -.1rem .1rem rgba(0,0,0,.1);
background-color: var(--color-button-active-background);
border-color: var(--color-button-active-border);
cursor: pointer;
@@ -143,19 +146,34 @@ a.site {
hr {
display: block;
border: 0;
border-top: 1px solid #ccc;
border-top: 1px solid var(--color-seperator);
margin: 1.5em auto 0 auto;
overflow: visible;
&::before {
content: "or";
background: #fff;
background: var(--color-background);
color: #888;
padding: 0 .4rem;
position: relative;
top: -.6rem;
}
}
.error {
background: #f5f5f5;
font-weight: 500;
border-radius: 0.3rem;
background: var(--color-info);
color: #fff;
p {
text-align: left;
padding: 0.5rem 1rem;
font-size: 0.9rem;
line-height: 1.2rem;
}
}
> div,
form {
display: block;

View File

@@ -1,44 +1,157 @@
import jwt from 'jsonwebtoken'
import CryptoJS from 'crypto-js'
import jose from 'jose'
import hkdf from 'futoin-hkdf'
import logger from './logger'
const encode = async ({ secret, key = secret, token = {}, maxAge }) => {
// If maxAge is set remove any existing created/expiry dates and replace them
if (maxAge) {
if (token.iat) { delete token.iat }
if (token.exp) { delete token.exp }
// Set default algorithm to use for auto-generated signing key
const DEFAULT_SIGNATURE_ALGORITHM = 'HS512'
// Set default algorithm for auto-generated symmetric encryption key
const DEFAULT_ENCRYPTION_ALGORITHM = 'A256GCM'
// Use encryption or not by default
const DEFAULT_ENCRYPTION_ENABLED = false
const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60 // 30 days
const encode = async ({
token = {},
maxAge = DEFAULT_MAX_AGE,
secret,
signingKey,
signingOptions = {
expiresIn: `${maxAge}s`
},
encryptionKey,
encryptionOptions = {
alg: 'dir',
enc: DEFAULT_ENCRYPTION_ALGORITHM,
zip: 'DEF'
},
encryption = DEFAULT_ENCRYPTION_ENABLED
} = {}) => {
// Signing Key
const _signingKey = (signingKey)
? jose.JWK.asKey(JSON.parse(signingKey))
: getDerivedSigningKey(secret)
// Sign token
const signedToken = jose.JWT.sign(token, _signingKey, signingOptions)
if (encryption) {
// Encryption Key
const _encryptionKey = (encryptionKey)
? jose.JWK.asKey(JSON.parse(encryptionKey))
: getDerivedEncryptionKey(secret)
// Encrypt token
return jose.JWE.encrypt(signedToken, _encryptionKey, encryptionOptions)
} else {
return signedToken
}
const signedToken = jwt.sign(token, secret, { expiresIn: maxAge })
const encryptedToken = CryptoJS.AES.encrypt(signedToken, key).toString()
return encryptedToken
}
const decode = async ({ secret, key = secret, token, maxAge }) => {
const decode = async ({
secret,
token,
maxAge = DEFAULT_MAX_AGE,
signingKey,
verificationKey = signingKey, // Optional (defaults to encryptionKey)
verificationOptions = {
maxTokenAge: `${maxAge}s`,
algorithms: [DEFAULT_SIGNATURE_ALGORITHM]
},
encryptionKey,
decryptionKey = encryptionKey, // Optional (defaults to encryptionKey)
decryptionOptions = {
algorithms: [DEFAULT_ENCRYPTION_ALGORITHM]
},
encryption = DEFAULT_ENCRYPTION_ENABLED
} = {}) => {
if (!token) return null
const decryptedBytes = CryptoJS.AES.decrypt(token, key)
const decryptedToken = decryptedBytes.toString(CryptoJS.enc.Utf8)
const verifiedToken = jwt.verify(decryptedToken, secret, { maxAge })
return verifiedToken
let tokenToVerify = token
if (encryption) {
// Encryption Key
const _encryptionKey = (decryptionKey)
? jose.JWK.asKey(JSON.parse(decryptionKey))
: getDerivedEncryptionKey(secret)
// Decrypt token
const decryptedToken = jose.JWE.decrypt(token, _encryptionKey, decryptionOptions)
tokenToVerify = decryptedToken.toString('utf8')
}
// Signing Key
const _signingKey = (verificationKey)
? jose.JWK.asKey(JSON.parse(verificationKey))
: getDerivedSigningKey(secret)
// Verify token
return jose.JWT.verify(tokenToVerify, _signingKey, verificationOptions)
}
// This is a simple helper method to make it easier to use JWT from an API route
const getJwt = async ({ req, secret, cookieName }) => {
if (!req || !secret) throw new Error('Must pass { req, secret } to getJWT()')
const getToken = async (args) => {
const {
req,
// Use secure prefix for cookie name, unless URL is NEXTAUTH_URL is http://
// or not set (e.g. development or test instance) case use unprefixed name
secureCookie = !(!process.env.NEXTAUTH_URL || process.env.NEXTAUTH_URL.startsWith('http://')),
cookieName = (secureCookie) ? '__Secure-next-auth.session-token' : 'next-auth.session-token',
raw = false
} = args
if (!req) throw new Error('Must pass `req` to JWT getToken()')
const secureCookieName = '__Secure-next-auth.session-token'
const insecureCookieName = 'next-auth.session-token'
const cookieValue = cookieName ? req.cookies[cookieName] : req.cookies[secureCookieName] || req.cookies[insecureCookieName]
// Try to get token from cookie
let token = req.cookies[cookieName]
if (!cookieValue) { return null }
// If cookie not found in cookie look for bearer token in authorization header.
// This allows clients that pass through tokens in headers rather than as
// cookies to use this helper function.
if (!token && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
const urlEncodedToken = req.headers.authorization.split(' ')[1]
token = decodeURIComponent(urlEncodedToken)
}
if (raw) {
return token
}
try {
return await decode({ secret, token: cookieValue })
return await decode({ token, ...args })
} catch (error) {
return null
}
}
// Generate warning (but only once at startup) when auto-generated keys are used
let DERIVED_SIGNING_KEY_WARNING = false
let DERIVED_ENCRYPTION_KEY_WARNING = false
const getDerivedSigningKey = (secret) => {
if (!DERIVED_SIGNING_KEY_WARNING) {
logger.warn('JWT_AUTO_GENERATED_SIGNING_KEY')
DERIVED_SIGNING_KEY_WARNING = true
}
const buffer = hkdf(secret, 64, { info: 'NextAuth.js Generated Signing Key', hash: 'SHA-256' })
const key = jose.JWK.asKey(buffer, { alg: DEFAULT_SIGNATURE_ALGORITHM, use: 'sig', kid: 'nextauth-auto-generated-signing-key' })
return key
}
const getDerivedEncryptionKey = (secret) => {
if (!DERIVED_ENCRYPTION_KEY_WARNING) {
logger.warn('JWT_AUTO_GENERATED_ENCRYPTION_KEY')
DERIVED_ENCRYPTION_KEY_WARNING = true
}
const buffer = hkdf(secret, 32, { info: 'NextAuth.js Generated Encryption Key', hash: 'SHA-256' })
const key = jose.JWK.asKey(buffer, { alg: DEFAULT_ENCRYPTION_ALGORITHM, use: 'enc', kid: 'nextauth-auto-generated-encryption-key' })
return key
}
export default {
encode,
decode,
getJwt
getToken
}

View File

@@ -1,19 +1,28 @@
const logger = {
error: (errorCode, ...text) => {
if (console) {
!text
? console.error(errorCode)
: console.error(
`[next-auth][error][${errorCode}]`,
text,
`\nhttps://next-auth.js.org/errors#${errorCode.toLowerCase()}`
)
}
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
console.error(
`[next-auth][error][${errorCode.toLowerCase()}]`,
text,
`\nhttps://next-auth.js.org/errors#${errorCode.toLowerCase()}`
)
},
warn: (warnCode, ...text) => {
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
console.warn(
`[next-auth][warn][${warnCode.toLowerCase()}]`,
text,
`\nhttps://next-auth.js.org/warnings#${warnCode.toLowerCase()}`
)
},
debug: (debugCode, ...text) => {
if (!console) { return }
if (text && text.length <= 1) { text = text[0] || '' }
if (process && process.env && process.env._NEXTAUTH_DEBUG) {
console.log(
`[next-auth][debug][${debugCode}]`,
`[next-auth][debug][${debugCode.toLowerCase()}]`,
text
)
}

27
src/lib/parse-url.js Normal file
View File

@@ -0,0 +1,27 @@
// Simple universal (client/server) function to split host and path
// We use this rather than a library because we need to use the same logic both
// client and server side and we only need to parse out the host and path, while
// supporting a default value, so a simple split is sufficent.
export default (url) => {
// Default values
const defaultHost = 'http://localhost:3000'
const defaultPath = '/api/auth'
if (!url) { url = `${defaultHost}${defaultPath}` }
// Default to HTTPS if no protocol explictly specified
const protocol = url.match(/^http?:\/\//) ? 'http' : 'https'
// Normalize URLs by stripping protocol and no trailing slash
url = url.replace(/^https?:\/\//, '').replace(/\/$/, '')
// Simple split based on first /
const [_host, ..._path] = url.split('/')
const baseUrl = _host ? `${protocol}://${_host}` : defaultHost
const basePath = _path.length > 0 ? `/${_path.join('/')}` : defaultPath
return {
baseUrl,
basePath
}
}

View File

@@ -12,10 +12,12 @@ export default (options) => {
authorizationUrl: 'https://appleid.apple.com/auth/authorize?response_type=code&id_token&response_mode=form_post',
profileUrl: null,
idToken: true,
state: false, // Apple doesn't support state verfication
profile: (profile) => {
// The name of the user will only return on first login
return {
id: profile.sub,
name: profile.name == null ? profile.sub : profile.name,
name: profile.user != null ? profile.user.name.firstName + ' ' + profile.user.name.lastName : null,
email: profile.email
}
},
@@ -35,7 +37,9 @@ export default (options) => {
aud: 'https://appleid.apple.com',
sub: appleId
},
privateKey,
// Automatically convert \\n into \n if found in private key. If the key
// is passed in an environment variable \n can get escaped as \\n
privateKey.replace(/\\n/g, '\n'),
{
algorithm: 'ES256',
keyid: keyId

View File

@@ -0,0 +1,24 @@
export default (options) => {
return {
id: 'atlassian',
name: 'Atlassian',
type: 'oauth',
version: '2.0',
params: {
grant_type: 'authorization_code'
},
accessTokenUrl: 'https://auth.atlassian.com/oauth/token',
authorizationUrl:
'https://auth.atlassian.com/authorize?audience=api.atlassian.com&response_type=code&prompt=consent',
profileUrl: 'https://api.atlassian.com/me',
profile: (profile) => {
return {
id: profile.account_id,
name: profile.name,
email: profile.email,
image: profile.picture
}
},
...options
}
}

View File

@@ -0,0 +1,24 @@
export default (options) => {
const tenant = options.tenantId ? options.tenantId : 'common'
return {
id: 'azure-ad-b2c',
name: 'Azure Active Directory B2C',
type: 'oauth',
version: '2.0',
params: {
grant_type: 'authorization_code'
},
accessTokenUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`,
authorizationUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/authorize?response_type=code&response_mode=query`,
profileUrl: 'https://graph.microsoft.com/v1.0/me/',
profile: (profile) => {
return {
id: profile.id,
name: profile.displayName,
email: profile.userPrincipalName
}
},
...options
}
}

20
src/providers/basecamp.js Normal file
View File

@@ -0,0 +1,20 @@
export default (options) => {
return {
id: 'basecamp',
name: 'Basecamp',
type: 'oauth',
version: '2.0',
accessTokenUrl: 'https://launchpad.37signals.com/authorization/token?type=web_server',
authorizationUrl: 'https://launchpad.37signals.com/authorization/new?type=web_server',
profileUrl: 'https://launchpad.37signals.com/authorization.json',
profile: (profile) => {
return {
id: profile.identity.id,
name: `${profile.identity.first_name} ${profile.identity.last_name}`,
email: profile.identity.email_address,
image: null
}
},
...options
}
}

View File

@@ -13,8 +13,8 @@ export default (options) => {
: `https://${region}.battle.net/oauth/token`,
authorizationUrl:
region === 'CN'
? 'https://www.battlenet.com.cn/oauth/authorize'
: `https://${region}.battle.net/oauth/authorize`,
? 'https://www.battlenet.com.cn/oauth/authorize?response_type=code'
: `https://${region}.battle.net/oauth/authorize?response_type=code`,
profileUrl: 'https://us.battle.net/oauth/userinfo',
profile: (profile) => {
return {

44
src/providers/bungie.js Normal file
View File

@@ -0,0 +1,44 @@
export default (options) => {
return {
id: 'bungie',
name: 'Bungie',
type: 'oauth',
version: '2.0',
scope: '',
params: { reauth: 'true', grant_type: 'authorization_code' },
accessTokenUrl: 'https://www.bungie.net/platform/app/oauth/token/',
requestTokenUrl: 'https://www.bungie.net/platform/app/oauth/token/',
authorizationUrl: 'https://www.bungie.net/en/OAuth/Authorize?response_type=code',
profileUrl: 'https://www.bungie.net/platform/User/GetBungieAccount/{membershipId}/254/',
prepareProfileRequest: ({ provider, url, headers, results }) => {
if (!results.membership_id) {
// internal error
// @TODO: handle better
throw new Error('Expected membership_id to be passed.')
}
if (!provider.apiKey) {
throw new Error('The Bungie provider requires the apiKey option to be present.')
}
headers['X-API-Key'] = provider.apiKey
url = url.replace('{membershipId}', results.membership_id)
return url
},
profile: (profile) => {
const { bungieNetUser: user } = profile.Response
return {
id: user.membershipId,
name: user.displayName,
image: `https://www.bungie.net${user.profilePicturePath.startsWith('/') ? '' : '/'}${user.profilePicturePath}`,
email: null
}
},
apiKey: null,
clientId: null,
clientSecret: null,
...options
}
}

View File

@@ -6,15 +6,21 @@ export default (options) => {
version: '2.0',
scope: 'identify email',
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://discordapp.com/api/oauth2/token',
authorizationUrl:
'https://discordapp.com/api/oauth2/authorize?response_type=code&prompt=consent',
profileUrl: 'https://discordapp.com/api/users/@me',
accessTokenUrl: 'https://discord.com/api/oauth2/token',
authorizationUrl: 'https://discord.com/api/oauth2/authorize?response_type=code&prompt=none',
profileUrl: 'https://discord.com/api/users/@me',
profile: (profile) => {
if (profile.avatar === null) {
const defaultAvatarNumber = parseInt(profile.discriminator) % 5
profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`
} else {
const format = profile.premium_type === 1 || profile.premium_type === 2 ? 'gif' : 'png'
profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`
}
return {
id: profile.id,
name: profile.username,
image: `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.png`,
image: profile.image_url,
email: profile.email
}
},

View File

@@ -22,10 +22,11 @@ export default (options) => {
}
}
const sendVerificationRequest = ({ identifier: email, url, token, site, provider }) => {
const sendVerificationRequest = ({ identifier: email, url, baseUrl, provider }) => {
return new Promise((resolve, reject) => {
const { server, from } = provider
site = site.replace(/^https?:\/\//, '') // Strip protocol from site
// Strip protocol from URL and use domain as site name
const site = baseUrl.replace(/^https?:\/\//, '')
nodemailer
.createTransport(server)

View File

@@ -0,0 +1,22 @@
export default ({ apiVersion, ...options }) => {
return {
id: 'foursquare',
name: 'Foursquare',
type: 'oauth',
version: '2.0',
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://foursquare.com/oauth2/access_token',
authorizationUrl:
'https://foursquare.com/oauth2/authenticate?response_type=code',
profileUrl: `https://api.foursquare.com/v2/users/self?v=${apiVersion}`,
profile: (profile) => {
return {
id: profile.id,
name: `${profile.firstName} ${profile.lastName}`,
image: `${profile.prefix}original${profile.suffix}`,
email: profile.contact.email
}
},
...options
}
}

View File

@@ -0,0 +1,27 @@
export default (options) => {
let authorizationUrl = `https://${options.domain}/oauth2/authorize?response_type=code`
if (options.tenantId) {
authorizationUrl += `&tenantId=${options.tenantId}`
}
return {
id: 'fusionauth',
name: 'FusionAuth',
type: 'oauth',
version: '2.0',
scope: 'openid',
params: { grant_type: 'authorization_code' },
accessTokenUrl: `https://${options.domain}/oauth2/token`,
authorizationUrl,
profileUrl: `https://${options.domain}/oauth2/userinfo`,
profile: (profile) => {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture
}
},
...options
}
}

View File

@@ -11,7 +11,7 @@ export default (options) => {
profile: (profile) => {
return {
id: profile.id,
name: profile.name,
name: profile.name || profile.login,
email: profile.email,
image: profile.avatar_url
}

View File

@@ -1,40 +1,60 @@
import Auth0 from './auth0'
import Apple from './apple'
import Box from './box'
import Credentials from './credentials'
import Atlassian from './atlassian'
import Auth0 from './auth0'
import AzureADB2C from './azure-ad-b2c'
import Basecamp from './basecamp'
import BattleNet from './battlenet'
import Box from './box'
import Bungie from './bungie'
import Credentials from './credentials'
import Cognito from './cognito'
import Discord from './discord'
import Email from './email'
import Facebook from './facebook'
import Foursquare from './foursquare'
import FusionAuth from './fusionauth'
import GitHub from './github'
import GitLab from './gitlab'
import Google from './google'
import IdentityServer4 from './identity-server4'
import LinkedIn from './linkedin'
import Mixer from './mixer'
import Netlify from './netlify'
import Okta from './okta'
import Slack from './slack'
import Spotify from './spotify'
import Strava from './strava'
import Twitch from './twitch'
import Twitter from './twitter'
import Yandex from './yandex'
export default {
Atlassian,
Auth0,
Apple,
Box,
Credentials,
AzureADB2C,
Basecamp,
BattleNet,
Box,
Bungie,
Credentials,
Cognito,
Discord,
Email,
Facebook,
Foursquare,
FusionAuth,
GitHub,
GitLab,
Google,
IdentityServer4,
LinkedIn,
Mixer,
Netlify,
Okta,
Slack,
Spotify,
Strava,
Twitter,
Twitch,
Yandex

26
src/providers/linkedin.js Normal file
View File

@@ -0,0 +1,26 @@
export default (options) => {
return {
id: 'linkedin',
name: 'LinkedIn',
type: 'oauth',
version: '2.0',
scope: 'r_liteprofile',
params: {
grant_type: 'authorization_code',
client_id: options.clientId,
client_secret: options.clientSecret
},
accessTokenUrl: 'https://www.linkedin.com/oauth/v2/accessToken',
authorizationUrl: 'https://www.linkedin.com/oauth/v2/authorization?response_type=code',
profileUrl: 'https://api.linkedin.com/v2/me?projection=(id,localizedFirstName,localizedLastName)',
profile: (profile) => {
return {
id: profile.id,
name: profile.localizedFirstName + ' ' + profile.localizedLastName,
email: null,
image: null
}
},
...options
}
}

21
src/providers/netlify.js Normal file
View File

@@ -0,0 +1,21 @@
export default (options) => {
return {
id: 'netlify',
name: 'Netlify',
type: 'oauth',
version: '2.0',
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://api.netlify.com/oauth/token',
authorizationUrl: 'https://app.netlify.com/authorize?response_type=code',
profileUrl: 'https://api.netlify.com/api/v1/user',
profile: (profile) => {
return {
id: profile.id,
name: profile.full_name,
email: profile.email,
image: profile.avatar_url
}
},
...options
}
}

View File

@@ -11,9 +11,9 @@ export default (options) => {
client_secret: options.clientSecret
},
// These will be different depending on the Org.
accessTokenUrl: `https://${options.domain}/oauth2/v1/token`,
authorizationUrl: `https://${options.domain}/oauth2/v1/authorize/?response_type=code`,
profileUrl: `https://${options.domain}/oauth2/v1/userinfo/`,
accessTokenUrl: `https://${options.domain}/v1/token`,
authorizationUrl: `https://${options.domain}/v1/authorize/?response_type=code`,
profileUrl: `https://${options.domain}/v1/userinfo/`,
profile: (profile) => {
return { ...profile, id: profile.sub }
},

View File

@@ -4,10 +4,12 @@ export default (options) => {
name: 'Slack',
type: 'oauth',
version: '2.0',
scope: 'identity.basic identity.email identity.avatar',
scope: [],
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://slack.com/api/oauth.access',
authorizationUrl: 'https://slack.com/oauth/authorize?response_type=code',
accessTokenUrl: 'https://slack.com/api/oauth.v2.access',
accessTokenGetter: (json) => json.authed_user.access_token,
authorizationUrl: 'https://slack.com/oauth/v2/authorize',
additionalAuthorizeParams: { user_scope: 'identity.basic,identity.email,identity.avatar' },
profileUrl: 'https://slack.com/api/users.identity',
profile: (profile) => {
const { user } = profile

23
src/providers/spotify.js Normal file
View File

@@ -0,0 +1,23 @@
export default (options) => {
return {
id: 'spotify',
name: 'Spotify',
type: 'oauth',
version: '2.0',
scope: 'user-read-email',
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://accounts.spotify.com/api/token',
authorizationUrl:
'https://accounts.spotify.com/authorize?response_type=code',
profileUrl: 'https://api.spotify.com/v1/me',
profile: (profile) => {
return {
id: profile.id,
name: profile.display_name,
email: profile.email,
image: profile.images?.[0]?.url
}
},
...options
}
}

22
src/providers/strava.js Normal file
View File

@@ -0,0 +1,22 @@
export default (options) => {
return {
id: 'strava',
name: 'Strava',
type: 'oauth',
version: '2.0',
scope: 'read',
params: { grant_type: 'authorization_code' },
accessTokenUrl: 'https://www.strava.com/api/v3/oauth/token',
authorizationUrl:
'https://www.strava.com/api/v3/oauth/authorize?response_type=code',
profileUrl: 'https://www.strava.com/api/v3/athlete',
profile: (profile) => {
return {
id: profile.id,
name: profile.firstname,
image: profile.profile
}
},
...options
}
}

View File

@@ -8,10 +8,11 @@ export default (options) => {
accessTokenUrl: 'https://api.twitter.com/oauth/access_token',
requestTokenUrl: 'https://api.twitter.com/oauth/request_token',
authorizationUrl: 'https://api.twitter.com/oauth/authenticate',
profileUrl: 'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true',
profileUrl:
'https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true',
profile: (profile) => {
return {
id: profile.id,
id: profile.id_str,
name: profile.name,
email: profile.email,
image: profile.profile_image_url_https.replace(/_normal\.jpg$/, '.jpg')

View File

@@ -1,5 +1,6 @@
import { createHash, randomBytes } from 'crypto'
import jwt from '../lib/jwt'
import parseUrl from '../lib/parse-url'
import cookie from './lib/cookie'
import callbackUrlHandler from './lib/callback-url-handler'
import parseProviders from './lib/providers'
@@ -12,11 +13,15 @@ import callback from './routes/callback'
import session from './routes/session'
import pages from './pages'
import adapters from '../adapters'
import logger from '../lib/logger'
const DEFAULT_SITE = 'http://localhost:3000'
const DEFAULT_BASE_PATH = '/api/auth'
// To work properly in production with OAuth providers the NEXTAUTH_URL
// environment variable must be set.
if (!process.env.NEXTAUTH_URL) {
logger.warn('NEXTAUTH_URL', 'NEXTAUTH_URL environment variable not set')
}
export default async (req, res, userSuppliedOptions) => {
async function NextAuth (req, res, userSuppliedOptions) {
// To the best of my knowledge, we need to return a promise here
// to avoid early termination of calls to the serverless function
// (and then return that promise when we are done) - eslint
@@ -27,6 +32,18 @@ export default async (req, res, userSuppliedOptions) => {
// safe to return and that no more data will be sent.
const done = resolve
if (!req.query.nextauth) {
const error = 'Cannot find [...nextauth].js in pages/api/auth. Make sure the filename is written correctly.'
logger.error('MISSING_NEXTAUTH_API_ROUTE_ERROR', error)
res
.status(500)
.end(
`Error: ${error}`
)
return done()
}
const { url, query, body } = req
const {
nextauth,
@@ -39,10 +56,10 @@ export default async (req, res, userSuppliedOptions) => {
csrfToken: csrfTokenFromPost
} = body
// Allow site name, path prefix to be overriden
const site = userSuppliedOptions.site || DEFAULT_SITE
const basePath = userSuppliedOptions.basePath || DEFAULT_BASE_PATH
const baseUrl = `${site}${basePath}`
// @todo refactor all existing references to site, baseUrl and basePath
const parsedUrl = parseUrl(process.env.NEXTAUTH_URL || process.env.VERCEL_URL)
const baseUrl = parsedUrl.baseUrl
const basePath = parsedUrl.basePath
// Parse database / adapter
let adapter
@@ -58,7 +75,7 @@ export default async (req, res, userSuppliedOptions) => {
// If no secret option is specified then it creates one on the fly
// based on options passed here. A options contains unique data, such as
// oAuth provider secrets and database credentials it should be sufficent.
const secret = userSuppliedOptions.secret || createHash('sha256').update(JSON.stringify(userSuppliedOptions)).digest('hex')
const secret = userSuppliedOptions.secret || createHash('sha256').update(JSON.stringify({ baseUrl, basePath, ...userSuppliedOptions })).digest('hex')
// Use secure cookies if the site uses HTTPS
// This being conditional allows cookies to work non-HTTPS development URLs
@@ -105,7 +122,7 @@ export default async (req, res, userSuppliedOptions) => {
}
// Session options
const sessionOption = {
const sessionOptions = {
jwt: false,
maxAge: 30 * 24 * 60 * 60, // Sessions expire after 30 days of being idle
updateAge: 24 * 60 * 60, // Sessions updated only if session is greater than this value (0 = always, 24*60*60 = every 24 hours)
@@ -114,8 +131,8 @@ export default async (req, res, userSuppliedOptions) => {
// JWT options
const jwtOptions = {
secret,
key: secret,
secret, // Use application secret if no keys specified
maxAge: sessionOptions.maxAge, // maxAge is dereived from session maxAge,
encode: jwt.encode,
decode: jwt.decode,
...userSuppliedOptions.jwt
@@ -123,17 +140,17 @@ export default async (req, res, userSuppliedOptions) => {
// If no adapter specified, force use of JSON Web Tokens (stateless)
if (!adapter) {
sessionOption.jwt = true
sessionOptions.jwt = true
}
// Event messages
const eventsOption = {
const eventsOptions = {
...events,
...userSuppliedOptions.events
}
// Callback functions
const callbacksOption = {
const callbacksOptions = {
...callbacks,
...userSuppliedOptions.callbacks
}
@@ -171,6 +188,20 @@ export default async (req, res, userSuppliedOptions) => {
cookie.set(res, cookies.csrfToken.name, newCsrfTokenCookie, cookies.csrfToken.options)
}
// Helper method for handling redirects, this is passed to all routes
// @TODO Refactor into a lib instead of passing as an option
// e.g. and call as redirect(req, res, url)
const redirect = (redirectUrl) => {
const reponseAsJson = !!((req.body && req.body.json === 'true'))
if (reponseAsJson) {
res.json({ url: redirectUrl })
} else {
res.status(302).setHeader('Location', redirectUrl)
res.end()
}
return done()
}
// User provided options are overriden by other options,
// except for the options with special handling above
const options = {
@@ -182,21 +213,20 @@ export default async (req, res, userSuppliedOptions) => {
// These computed settings can values in userSuppliedOptions but override them
// and are request-specific.
adapter,
site,
basePath,
baseUrl,
basePath,
action,
provider,
cookies,
secret,
csrfToken,
csrfTokenVerified,
providers: parseProviders(userSuppliedOptions.providers, baseUrl),
session: sessionOption,
providers: parseProviders(userSuppliedOptions.providers, baseUrl, basePath),
session: sessionOptions,
jwt: jwtOptions,
events: eventsOption,
callbacks: callbacksOption,
callbackUrl: site
events: eventsOptions,
callbacks: callbacksOptions,
callbackUrl: baseUrl,
redirect
}
// If debug enabled, set ENV VAR so that logger logs debug messages
@@ -205,12 +235,6 @@ export default async (req, res, userSuppliedOptions) => {
// Get / Set callback URL based on query param / cookie + validation
options.callbackUrl = await callbackUrlHandler(req, res, options)
const redirect = (redirectUrl) => {
res.status(302).setHeader('Location', redirectUrl)
res.end()
return done()
}
if (req.method === 'GET') {
switch (action) {
case 'providers':
@@ -223,18 +247,18 @@ export default async (req, res, userSuppliedOptions) => {
res.json({ csrfToken })
return done()
case 'signin':
if (provider && options.providers[provider]) {
signin(req, res, options, done)
} else {
if (options.pages.signin) { return redirect(`${options.pages.signin}${options.pages.signin.includes('?') ? '&' : '?'}callbackUrl=${options.callbackUrl}`) }
pages.render(req, res, 'signin', { site, providers: Object.values(options.providers), callbackUrl: options.callbackUrl, csrfToken }, done)
if (options.pages.signIn) {
let redirectUrl = `${options.pages.signIn}${options.pages.signIn.includes('?') ? '&' : '?'}callbackUrl=${options.callbackUrl}`
if (req.query.error) { redirectUrl = `${redirectUrl}&error=${req.query.error}` }
return redirect(redirectUrl)
}
pages.render(req, res, 'signin', { baseUrl, basePath, providers: Object.values(options.providers), callbackUrl: options.callbackUrl, csrfToken }, done)
break
case 'signout':
if (options.pages.signout) { return redirect(`${options.pages.signout}${options.pages.signout.includes('?') ? '&' : '?'}callbackUrl=${options.callbackUrl}`) }
if (options.pages.signOut) { return redirect(`${options.pages.signOut}${options.pages.signOut.includes('?') ? '&' : '?'}error=${error}`) }
pages.render(req, res, 'signout', { site, baseUrl, csrfToken, callbackUrl: options.callbackUrl }, done)
pages.render(req, res, 'signout', { baseUrl, basePath, csrfToken, callbackUrl: options.callbackUrl }, done)
break
case 'callback':
if (provider && options.providers[provider]) {
@@ -247,12 +271,12 @@ export default async (req, res, userSuppliedOptions) => {
case 'verify-request':
if (options.pages.verifyRequest) { return redirect(options.pages.verifyRequest) }
pages.render(req, res, 'verify-request', { site }, done)
pages.render(req, res, 'verify-request', { baseUrl }, done)
break
case 'error':
if (options.pages.error) { return redirect(`${options.pages.error}${options.pages.error.includes('?') ? '&' : '?'}error=${error}`) }
pages.render(req, res, 'error', { site, error, baseUrl }, done)
pages.render(req, res, 'error', { baseUrl, basePath, error }, done)
break
default:
res.status(404).end()
@@ -261,17 +285,30 @@ export default async (req, res, userSuppliedOptions) => {
} else if (req.method === 'POST') {
switch (action) {
case 'signin':
// Signin POST requests are used for email sign in
// Verified CSRF Token required for all sign in routes
if (!csrfTokenVerified) {
return redirect(`${baseUrl}${basePath}/signin?csrf=true`)
}
if (provider && options.providers[provider]) {
signin(req, res, options, done)
break
}
break
case 'signout':
// Verified CSRF Token required for signout
if (!csrfTokenVerified) {
return redirect(`${baseUrl}${basePath}/signout?csrf=true`)
}
signout(req, res, options, done)
break
case 'callback':
if (provider && options.providers[provider]) {
// Verified CSRF Token required for credentials providers only
if (options.providers[provider].type === 'credentials' && !csrfTokenVerified) {
return redirect(`${baseUrl}${basePath}/signin?csrf=true`)
}
callback(req, res, options, done)
} else {
res.status(400).end(`Error: HTTP POST is not supported for ${url}`)
@@ -288,3 +325,11 @@ export default async (req, res, userSuppliedOptions) => {
}
})
}
export default async (...args) => {
if (args.length === 1) {
return (req, res) => NextAuth(req, res, args[0])
}
return NextAuth(...args)
}

View File

@@ -20,7 +20,6 @@ export default async (sessionToken, profile, providerAccount, options) => {
const { adapter, jwt, events } = options
const useJwtSession = options.session.jwt
const sessionMaxAge = options.session.maxAge
// If no adapter is configured then we don't have a database and cannot
// persist data; in this mode we just return a dummy session object.
@@ -52,9 +51,9 @@ export default async (sessionToken, profile, providerAccount, options) => {
if (sessionToken) {
if (useJwtSession) {
try {
session = await jwt.decode({ secret: jwt.secret, token: sessionToken, maxAge: sessionMaxAge })
if (session && session.user) {
user = await getUser(session.user.id)
session = await jwt.decode({ ...jwt, token: sessionToken })
if (session && session.sub) {
user = await getUser(session.sub)
isSignedIn = !!user
}
} catch (e) {
@@ -86,12 +85,12 @@ export default async (sessionToken, profile, providerAccount, options) => {
// Update emailVerified property on the user object
const currentDate = new Date()
userByEmail.emailVerified = currentDate
user = await updateUser(userByEmail)
user = await updateUser({ ...userByEmail, emailVerified: currentDate })
await dispatchEvent(events.updateUser, user)
} else {
// Create user account if there isn't one for the email address already
user = await createUser({ ...profile, emailVerified: true })
const currentDate = new Date()
user = await createUser({ ...profile, emailVerified: currentDate })
await dispatchEvent(events.createUser, user)
isNewUser = true
}

View File

@@ -3,21 +3,21 @@ import cookie from '../lib/cookie'
export default async (req, res, options) => {
const { query } = req
const { body } = req
const { cookies, site, defaultCallbackUrl, callbacks } = options
const { cookies, baseUrl, defaultCallbackUrl, callbacks } = options
// Handle preserving and validating callback URLs
// If no defaultCallbackUrl option specified, default to the homepage for the site
let callbackUrl = defaultCallbackUrl || site
let callbackUrl = defaultCallbackUrl || baseUrl
// Try reading callbackUrlParamValue from request body (form submission) then from query param (get request)
const callbackUrlParamValue = body.callbackUrl || query.callbackUrl || null
const callbackUrlCookieValue = req.cookies[cookies.callbackUrl.name] || null
if (callbackUrlParamValue) {
// If callbackUrl form field or query parameter is passed try to use it if allowed
callbackUrl = await callbacks.redirect(callbackUrlParamValue, site)
callbackUrl = await callbacks.redirect(callbackUrlParamValue, baseUrl)
} else if (callbackUrlCookieValue) {
// If no callbackUrl specified, try using the value from the cookie if allowed
callbackUrl = await callbacks.redirect(callbackUrlCookieValue, site)
callbackUrl = await callbacks.redirect(callbackUrlCookieValue, baseUrl)
}
// Save callback URL in a cookie so that can be used for subsequent requests in signin/signout/callback flow

View File

@@ -1,5 +1,5 @@
/**
* Use the signin callback to control if a user is allowed to sign in or not.
* Use the signIn callback to control if a user is allowed to sign in or not.
*
* This is triggered before sign in flow completes, so the user profile may be
* a user object (with an ID) or it may be just their name and email address,
@@ -12,10 +12,11 @@
* @param {object} profile User profile (e.g. user id, name, email)
* @param {object} account Account used to sign in (e.g. OAuth account)
* @param {object} metadata Provider specific metadata (e.g. OAuth Profile)
* @return {boolean|object} Return `true` (or a modified JWT) to allow sign in
* @return {boolean|string} Return `true` to allow sign in
* Return `false` to deny access
* Return `string` to redirect to (eg.: "/unauthorized")
*/
const signin = async (profile, account, metadata) => {
const signIn = async (profile, account, metadata) => {
const isAllowedToSignIn = true
if (isAllowedToSignIn) {
return Promise.resolve(true)
@@ -68,7 +69,7 @@ const jwt = async (token, oAuthProfile) => {
}
export default {
signin,
signIn,
redirect,
session,
jwt

View File

@@ -15,7 +15,9 @@ const set = (res, name, value, options = {}) => {
}
// Preserve any existing cookies that have already been set in the same session
const setCookieHeader = res.getHeader('Set-Cookie') || []
let setCookieHeader = res.getHeader('Set-Cookie') || []
// If not an array (i.e. a string with a single cookie) convert it into an array
if (!Array.isArray(setCookieHeader)) { setCookieHeader = [setCookieHeader] }
setCookieHeader.push(_serialize(name, String(stringValue), options))
res.setHeader('Set-Cookie', setCookieHeader)
}

View File

@@ -1,9 +1,9 @@
const signin = async (message) => {
const signIn = async (message) => {
// Event triggered on successful sign in
}
const signout = async (message) => {
// Event triggered on signout
const signOut = async (message) => {
// Event triggered on sign out
}
const createUser = async (message) => {
@@ -28,8 +28,8 @@ const error = async (message) => {
}
export default {
signin,
signout,
signIn,
signOut,
createUser,
updateUser,
linkAccount,

View File

@@ -1,6 +1,8 @@
import oAuthClient from './client'
import { createHash } from 'crypto'
import querystring from 'querystring'
import jwtDecode from 'jwt-decode'
import oAuthClient from './client'
import logger from '../../../lib/logger'
// @TODO Refactor monkey patching in _getOAuthAccessToken() and _get()
@@ -10,18 +12,37 @@ import logger from '../../../lib/logger'
// come up, as the node-oauth package does not seem to be actively maintained.
// @TODO Refactor to use promises and not callbacks
// @TODO Refactor to use jsonwebtoken instead of jwt-decode & remove dependancy
export default async (req, provider, callback) => {
let { oauth_token, oauth_verifier, code } = req.query // eslint-disable-line camelcase
export default async (req, provider, csrfToken, callback) => {
// The "user" object is specific to apple provider and is provided on first sign in
// e.g. {"name":{"firstName":"Johnny","lastName":"Appleseed"},"email":"johnny.appleseed@nextauth.com"}
let { oauth_token, oauth_verifier, code, user, state } = req.query // eslint-disable-line camelcase
const client = oAuthClient(provider)
if (provider.version && provider.version.startsWith('2.')) {
// For OAuth 2.0 flows, check state returned and matches expected value
// (a hash of the NextAuth.js CSRF token).
//
// This check can be disabled for providers that do not support it by
// setting `state: false` as a option on the provider (defaults to true).
if (!Object.prototype.hasOwnProperty.call(provider, 'state') || provider.state === true) {
const expectedState = createHash('sha256').update(csrfToken).digest('hex')
if (state !== expectedState) {
return callback(new Error('Invalid state returned from oAuth provider'))
}
}
if (req.method === 'POST') {
// Get the CODE from Body
const body = JSON.parse(JSON.stringify(req.body))
code = body.code
try {
const body = JSON.parse(JSON.stringify(req.body))
if (body.error) { throw new Error(body.error) }
code = body.code
user = body.user != null ? JSON.parse(body.user) : null
} catch (e) {
logger.error('OAUTH_CALLBACK_HANDLER_ERROR', e, req.body, provider.id, code)
return callback()
}
}
// Pass authToken in header by default (unless 'useAuthTokenHeader: false' is set)
@@ -38,12 +59,22 @@ export default async (req, provider, callback) => {
code,
provider,
(error, accessToken, refreshToken, results) => {
// @TODO Handle error
if (error || results.error) {
logger.error('OAUTH_GET_ACCESS_TOKEN_ERROR', error, results, provider.id, code)
return callback(error || results.error)
}
if (provider.idToken) {
// If we don't have an ID Token most likely the user hit a cancel
// button when signing in (or the provider is misconfigured).
//
// Unfortunately, we can't tell which, so we can't treat it as an
// error, so instead we just returning nothing, which will cause the
// user to be redirected back to the sign in page.
if (!results || !results.id_token) {
return callback()
}
// Support services that use OpenID ID Tokens to encode profile data
_decodeToken(
provider,
@@ -51,7 +82,7 @@ export default async (req, provider, callback) => {
refreshToken,
results.id_token,
async (error, profileData) => {
const { profile, account, OAuthProfile } = await _getProfile(error, profileData, accessToken, refreshToken, provider)
const { profile, account, OAuthProfile } = await _getProfile(error, profileData, accessToken, refreshToken, provider, user)
callback(error, profile, account, OAuthProfile)
}
)
@@ -62,6 +93,7 @@ export default async (req, provider, callback) => {
client.get(
provider,
accessToken,
results,
async (error, profileData) => {
const { profile, account, OAuthProfile } = await _getProfile(error, profileData, accessToken, refreshToken, provider)
callback(error, profile, account, OAuthProfile)
@@ -96,7 +128,11 @@ export default async (req, provider, callback) => {
}
}
async function _getProfile (error, profileData, accessToken, refreshToken, provider) {
/**
* //6/30/2020 @geraldnolan added userData parameter to attach additional data to the profileData object
* Returns profile, raw profile and auth provider details
*/
async function _getProfile (error, profileData, accessToken, refreshToken, provider, userData) {
// @TODO Handle error
if (error) {
logger.error('OAUTH_GET_PROFILE_ERROR', error)
@@ -107,6 +143,13 @@ async function _getProfile (error, profileData, accessToken, refreshToken, provi
// Convert profileData into an object if it's a string
if (typeof profileData === 'string' || profileData instanceof String) { profileData = JSON.parse(profileData) }
// If a user object is supplied (e.g. Apple provider) add it to the profile object
if (userData != null) {
profileData.user = userData
}
logger.debug('PROFILE_DATA', profileData)
profile = await provider.profile(profileData)
} catch (exception) {
// If we didn't get a response either there was a problem with the provider
@@ -168,10 +211,12 @@ async function _getOAuthAccessToken (code, provider, callback) {
if (!params.redirect_uri) { params.redirect_uri = provider.callbackUrl }
if (!headers['Content-Type']) { headers['Content-Type'] = 'application/x-www-form-urlencoded' }
// Added as a fix to accomodate change in Twitch oAuth API
if (!headers['Client-ID']) { headers['Client-ID'] = provider.clientId }
// Added as a fix for Reddit Authentication
if (provider.id === 'reddit') {
headers.Authorization = 'Basic ' + Buffer.from((provider.clientId + ':' + provider.clientSecret)).toString('base64')
}
// Okta errors when this is set. Maybe there are other Providers that also wont like this.
if (setGetAccessTokenAuthHeader) {
if (!headers.Authorization) { headers.Authorization = `Bearer ${code}` }
@@ -202,16 +247,21 @@ async function _getOAuthAccessToken (code, provider, callback) {
// Clients of these services suffer a minor performance cost.
results = querystring.parse(data)
}
const accessToken = results.access_token
const accessToken = provider.accessTokenGetter ? provider.accessTokenGetter(results) : results.access_token
const refreshToken = results.refresh_token
callback(null, accessToken, refreshToken, results)
}
)
}
// Ported from https://github.com/ciaranj/node-oauth/blob/a7f8a1e21c362eb4ed2039431fb9ac2ae749f26a/lib/oauth2.js
function _get (provider, accessToken, callback) {
const url = provider.profileUrl
/**
* Ported from https://github.com/ciaranj/node-oauth/blob/a7f8a1e21c362eb4ed2039431fb9ac2ae749f26a/lib/oauth2.js
*
* 18/08/2020 @robertcraigie added results parameter to pass data to an optional request preparer.
* e.g. see providers/bungie
*/
function _get (provider, accessToken, results, callback) {
let url = provider.profileUrl
const headers = provider.headers || {}
if (this._useAuthorizationHeaderForGET) {
@@ -222,6 +272,11 @@ function _get (provider, accessToken, callback) {
accessToken = null
}
const prepareRequest = provider.prepareProfileRequest
if (prepareRequest) {
url = prepareRequest({ provider, url, headers, results }) || url
}
this._request('GET', url, headers, null, accessToken, callback)
}

View File

@@ -1,12 +1,12 @@
export default (_providers, baseUrl) => {
export default (_providers, baseUrl, basePath) => {
const providers = {}
_providers.forEach(provider => {
const providerId = provider.id
providers[providerId] = {
...provider,
signinUrl: `${baseUrl}/signin/${providerId}`,
callbackUrl: `${baseUrl}/callback/${providerId}`
signinUrl: `${baseUrl}${basePath}/signin/${providerId}`,
callbackUrl: `${baseUrl}${basePath}/callback/${providerId}`
}
})

View File

@@ -2,7 +2,7 @@ import { randomBytes } from 'crypto'
export default async (email, provider, options) => {
try {
const { baseUrl, adapter } = options
const { baseUrl, basePath, adapter } = options
const { createVerificationRequest } = await adapter.getAdapter(options)
@@ -13,7 +13,7 @@ export default async (email, provider, options) => {
const token = randomBytes(32).toString('hex')
// Send email with link containing token (the unhashed version)
const url = `${baseUrl}/callback/${encodeURIComponent(provider.id)}?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}`
const url = `${baseUrl}${basePath}/callback/${encodeURIComponent(provider.id)}?email=${encodeURIComponent(email)}&token=${encodeURIComponent(token)}`
// @TODO Create invite (send secret so can be hashed)
await createVerificationRequest(email, url, token, secret, provider, options)

View File

@@ -1,16 +1,19 @@
import oAuthClient from '../oauth/client'
import crypto from 'crypto'
import { createHash } from 'crypto'
import logger from '../../../lib/logger'
export default (provider, callback) => {
export default (provider, csrfToken, callback, authParams) => {
const { callbackUrl } = provider
const client = oAuthClient(provider)
if (provider.version && provider.version.startsWith('2.')) {
// Handle oAuth v2.x
let url = client.getAuthorizeUrl({
...authParams,
redirect_uri: provider.callbackUrl,
scope: provider.scope,
state: crypto.randomBytes(64).toString('hex')
// A hash of the NextAuth.js CSRF token is used as the state
state: createHash('sha256').update(csrfToken).digest('hex'),
...provider.additionalAuthorizeParams
})
// If the authorizationUrl specified in the config has query parameters on it

View File

@@ -1,12 +1,12 @@
import { h } from 'preact' // eslint-disable-line no-unused-vars
import render from 'preact-render-to-string'
export default ({ site, error, baseUrl, res }) => {
const signinPageUrl = `${baseUrl}/signin` // @TODO Make sign in URL configurable
export default ({ baseUrl, basePath, error, res }) => {
const signinPageUrl = `${baseUrl}${basePath}/signin`
let statusCode = 200
let heading = <h1>Error</h1>
let message = <p><a className='site' href={site}>{site.replace(/^https?:\/\//, '')}</a></p>
let message = <p><a className='site' href={baseUrl}>{baseUrl.replace(/^https?:\/\//, '')}</a></p>
switch (error) {
case 'Signin':
@@ -15,79 +15,43 @@ export default ({ site, error, baseUrl, res }) => {
case 'OAuthCreateAccount':
case 'EmailCreateAccount':
case 'Callback':
heading = <h1>Sign in failed</h1>
message =
<div>
<div className='message'>
<p>Try signing with a different account.</p>
</div>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
break
case 'OAuthAccountNotLinked':
statusCode = 403
heading = <h1>Sign in failed</h1>
message =
<div>
<div className='message'>
<p>An account associated with your email address already exists.</p>
<p>Sign in with the same account you used originally to confirm your identity.</p>
</div>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
// @TODO Add this text when account linking is complete
// <p>Once you are signed in, you can link your accounts.</p>
// @TODO Display email sign in option if an email provider is configured
break
case 'EmailSignin':
heading = <h1>Sign in failed</h1>
message =
<div>
<div className='message'>
<p>Unable to send email.</p>
</div>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
break
case 'CredentialsSignin':
statusCode = 403
heading = <h1>Sign in failed</h1>
message =
<div>
<div className='message'>
<p>Check the details you provided are correct.</p>
</div>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
break
// These messages are displayed in line on the sign in page
res.status(302).setHeader('Location', `${signinPageUrl}?error=${error}`)
res.end()
return false
case 'Configuration':
statusCode = 500
heading = <h1>Server error</h1>
message =
message = (
<div>
<div className='message'>
<p>There is a problem with the server configuration.</p>
<p>Check the server logs for more information.</p>
</div>
</div>
)
break
case 'AccessDenied':
statusCode = 403
heading = <h1>Access Denied</h1>
message =
message = (
<div>
<div className='message'>
<p>You do not have permission to sign in.</p>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
</div>
)
break
case 'Verification':
// @TODO Check if user is signed in already with the same email address.
// If they are, no need to display this message, can just direct to callbackUrl
statusCode = 403
heading = <h1>Unable to sign in</h1>
message =
message = (
<div>
<div className='message'>
<p>The sign in link is no longer valid.</p>
@@ -95,6 +59,7 @@ export default ({ site, error, baseUrl, res }) => {
</div>
<p><a className='button' href={signinPageUrl}>Sign in</a></p>
</div>
)
break
default:
}

View File

@@ -18,6 +18,7 @@ function render (req, res, page, props, done) {
break
case 'error':
html = error({ ...props, res })
if (html === false) return done()
break
default:
html = error(props)

View File

@@ -2,8 +2,7 @@ import { h } from 'preact' // eslint-disable-line no-unused-vars
import render from 'preact-render-to-string'
export default ({ req, csrfToken, providers, callbackUrl }) => {
const withCallbackUrl = callbackUrl ? `?callbackUrl=${callbackUrl}` : ''
const { email } = req.query
const { email, error } = req.query
// We only want to render providers
const providersToRender = providers.filter(provider => {
@@ -19,12 +18,46 @@ export default ({ req, csrfToken, providers, callbackUrl }) => {
}
})
let errorMessage
if (error) {
switch (error) {
case 'Signin':
case 'OAuthSignin':
case 'OAuthCallback':
case 'OAuthCreateAccount':
case 'EmailCreateAccount':
case 'Callback':
errorMessage = <p>Try signing with a different account.</p>
break
case 'OAuthAccountNotLinked':
errorMessage = <p>To confirm your identity, sign in with the same account you used originally.</p>
break
case 'EmailSignin':
errorMessage = <p>Check your email address.</p>
break
case 'CredentialsSignin':
errorMessage = <p>Sign in failed. Check the details you provided are correct.</p>
break
default:
errorMessage = <p>Unable to sign in.</p>
break
}
}
return render(
<div className='signin'>
{errorMessage &&
<div className='error'>
{errorMessage}
</div>}
{providersToRender.map((provider, i) =>
<div key={provider.id} className='provider'>
{provider.type === 'oauth' &&
<a className='button' data-provider={provider.id} href={`${provider.signinUrl}${withCallbackUrl}`}>Sign in with {provider.name}</a>}
<form action={provider.signinUrl} method='POST'>
<input type='hidden' name='csrfToken' value={csrfToken} />
{callbackUrl && <input type='hidden' name='callbackUrl' value={callbackUrl} />}
<button type='submit' className='button'>Sign in with {provider.name}</button>
</form>}
{(provider.type === 'email' || provider.type === 'credentials') && (i > 0) &&
providersToRender[i - 1].type !== 'email' && providersToRender[i - 1].type !== 'credentials' &&
<hr />}

View File

@@ -1,11 +1,11 @@
import { h } from 'preact' // eslint-disable-line no-unused-vars
import render from 'preact-render-to-string'
export default ({ baseUrl, csrfToken }) => {
export default ({ baseUrl, basePath, csrfToken }) => {
return render(
<div className='signout'>
<h1>Are you sure you want to sign out?</h1>
<form action={`${baseUrl}/signout`} method='POST'>
<form action={`${baseUrl}${basePath}/signout`} method='POST'>
<input type='hidden' name='csrfToken' value={csrfToken} />
<button type='submit'>Sign out</button>
</form>

View File

@@ -1,12 +1,12 @@
import { h } from 'preact' // eslint-disable-line no-unused-vars
import render from 'preact-render-to-string'
export default ({ site }) => {
export default ({ baseUrl }) => {
return render(
<div className='verify-request'>
<h1>Check your email</h1>
<p>A sign in link has been sent to your email address.</p>
<p><a className='site' href={site}>{site.replace(/^https?:\/\//, '')}</a></p>
<p><a className='site' href={baseUrl}>{baseUrl.replace(/^https?:\/\//, '')}</a></p>
</div>
)
}

View File

@@ -10,15 +10,17 @@ export default async (req, res, options, done) => {
provider: providerName,
providers,
adapter,
site,
secret,
baseUrl,
basePath,
secret,
cookies,
callbackUrl,
pages,
jwt,
events,
callbacks
callbacks,
csrfToken,
redirect
} = options
const provider = providers[providerName]
const { type } = provider
@@ -30,13 +32,11 @@ export default async (req, res, options, done) => {
if (type === 'oauth') {
try {
oAuthCallback(req, provider, async (error, profile, account, OAuthProfile) => {
oAuthCallback(req, provider, csrfToken, async (error, profile, account, OAuthProfile) => {
try {
if (error) {
logger.error('CALLBACK_OAUTH_ERROR', error)
res.status(302).setHeader('Location', `${baseUrl}/error?error=oAuthCallback`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=OAuthCallback`)
}
// Make it easier to debug when adding a new provider
@@ -51,29 +51,52 @@ export default async (req, res, options, done) => {
// should at least be visible to developers what happened if it is an
// error with the provider.
if (!profile) {
res.status(302).setHeader('Location', `${baseUrl}/signin`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/signin`)
}
// Check if user is allowed to sign in
const signinCallbackResponse = await callbacks.signin(profile, account, OAuthProfile)
// Attempt to get Profile from OAuth provider details before invoking
// signIn callback - but if no user object is returned, that is fine
// (that just means it's a new user signing in for the first time).
let userOrProfile = profile
if (adapter) {
const { getUserByProviderAccountId } = await adapter.getAdapter(options)
const userFromProviderAccountId = await getUserByProviderAccountId(account.provider, account.id)
if (userFromProviderAccountId) {
userOrProfile = userFromProviderAccountId
}
}
if (signinCallbackResponse === false) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=AccessDenied`)
res.end()
return done()
try {
const signInCallbackResponse = await callbacks.signIn(userOrProfile, account, OAuthProfile)
if (signInCallbackResponse === false) {
return redirect(`${baseUrl}${basePath}/error?error=AccessDenied`)
} else if (typeof signInCallbackResponse === 'string') {
return redirect(signInCallbackResponse)
}
} catch (error) {
if (error instanceof Error) {
return redirect(`${baseUrl}${basePath}/error?error=${encodeURIComponent(error)}`)
}
// TODO: Remove in a future major release
logger.warn('SIGNIN_CALLBACK_REJECT_REDIRECT')
return redirect(error)
}
// Sign user in
const { user, session, isNewUser } = await callbackHandler(sessionToken, profile, account, options)
if (useJwtSession) {
const defaultJwtPayload = { user, account, isNewUser }
const jwtPayload = await callbacks.jwt(defaultJwtPayload, OAuthProfile)
const defaultJwtPayload = {
name: user.name,
email: user.email,
picture: user.image,
sub: user.id?.toString()
}
const jwtPayload = await callbacks.jwt(defaultJwtPayload, user, account, OAuthProfile, isNewUser)
// Sign and encrypt token
const newEncodedJwt = await jwt.encode({ secret: jwt.secret, token: jwtPayload, maxAge: sessionMaxAge })
const newEncodedJwt = await jwt.encode({ ...jwt, token: jwtPayload })
// Set cookie expiry date
const cookieExpires = new Date()
@@ -85,48 +108,38 @@ export default async (req, res, options, done) => {
cookie.set(res, cookies.sessionToken.name, session.sessionToken, { expires: session.expires || null, ...cookies.sessionToken.options })
}
await dispatchEvent(events.signin, { user, account, isNewUser })
await dispatchEvent(events.signIn, { user, account, isNewUser })
// Handle first logins on new accounts
// e.g. option to send users to a new account landing page on initial login
// Note that the callback URL is preserved, so the journey can still be resumed
if (isNewUser && pages.newUser) {
res.status(302).setHeader('Location', pages.newUser)
res.end()
return done()
return redirect(`${pages.newUser}${pages.newUser.includes('?') ? '&' : '?'}callbackUrl=${encodeURIComponent(callbackUrl)}`)
}
// Callback URL is already verified at this point, so safe to use if specified
res.status(302).setHeader('Location', callbackUrl || site)
res.end()
return done()
return redirect(callbackUrl || baseUrl)
} catch (error) {
if (error.name === 'AccountNotLinkedError') {
// If the email on the account is already linked, but nto with this oAuth account
res.status(302).setHeader('Location', `${baseUrl}/error?error=OAuthAccountNotLinked`)
return redirect(`${baseUrl}${basePath}/error?error=OAuthAccountNotLinked`)
} else if (error.name === 'CreateUserError') {
res.status(302).setHeader('Location', `${baseUrl}/error?error=OAuthCreateAccount`)
return redirect(`${baseUrl}${basePath}/error?error=OAuthCreateAccount`)
} else {
logger.error('OAUTH_CALLBACK_HANDLER_ERROR', error)
res.status(302).setHeader('Location', `${baseUrl}/error?error=Callback`)
return redirect(`${baseUrl}${basePath}/error?error=Callback`)
}
res.end()
return done()
}
})
} catch (error) {
logger.error('OAUTH_CALLBACK_ERROR', error)
res.status(302).setHeader('Location', `${baseUrl}/error?error=Callback`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Callback`)
}
} else if (type === 'email') {
try {
if (!adapter) {
logger.error('EMAIL_REQUIRES_ADAPTER_ERROR')
res.status(302).setHeader('Location', `${baseUrl}/error?error=Configuration`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Configuration`)
}
const { getVerificationRequest, deleteVerificationRequest, getUserByEmail } = await adapter.getAdapter(options)
@@ -136,9 +149,7 @@ export default async (req, res, options, done) => {
// Verify email and verification token exist in database
const invite = await getVerificationRequest(email, verificationToken, secret, provider)
if (!invite) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=Verification`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Verification`)
}
// If verification token is valid, delete verification request token from
@@ -150,23 +161,36 @@ export default async (req, res, options, done) => {
const account = { id: provider.id, type: 'email', providerAccountId: email }
// Check if user is allowed to sign in
const signinCallbackResponse = await callbacks.signin(profile, account, null)
if (signinCallbackResponse === false) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=AccessDenied`)
res.end()
return done()
try {
const signInCallbackResponse = await callbacks.signIn(profile, account, { email })
if (signInCallbackResponse === false) {
return redirect(`${baseUrl}${basePath}/error?error=AccessDenied`)
} else if (typeof signInCallbackResponse === 'string') {
return redirect(signInCallbackResponse)
}
} catch (error) {
if (error instanceof Error) {
return redirect(`${baseUrl}${basePath}/error?error=${encodeURIComponent(error)}`)
}
// TODO: Remove in a future major release
logger.warn('SIGNIN_CALLBACK_REJECT_REDIRECT')
return redirect(error)
}
// Sign user in
const { user, session, isNewUser } = await callbackHandler(sessionToken, profile, account, options)
if (useJwtSession) {
const defaultJwtPayload = { user, account, isNewUser }
const jwtPayload = await callbacks.jwt(defaultJwtPayload)
const defaultJwtPayload = {
name: user.name,
email: user.email,
picture: user.image,
sub: user.id?.toString()
}
const jwtPayload = await callbacks.jwt(defaultJwtPayload, user, account, profile, isNewUser)
// Sign and encrypt token
const newEncodedJwt = await jwt.encode({ secret: jwt.secret, token: jwtPayload, maxAge: sessionMaxAge })
const newEncodedJwt = await jwt.encode({ ...jwt, token: jwtPayload })
// Set cookie expiry date
const cookieExpires = new Date()
@@ -178,86 +202,81 @@ export default async (req, res, options, done) => {
cookie.set(res, cookies.sessionToken.name, session.sessionToken, { expires: session.expires || null, ...cookies.sessionToken.options })
}
await dispatchEvent(events.signin, { user, account, isNewUser })
await dispatchEvent(events.signIn, { user, account, isNewUser })
// Handle first logins on new accounts
// e.g. option to send users to a new account landing page on initial login
// Note that the callback URL is preserved, so the journey can still be resumed
if (isNewUser && pages.newUser) {
res.status(302).setHeader('Location', pages.newUser)
res.end()
return done()
return redirect(`${pages.newUser}${pages.newUser.includes('?') ? '&' : '?'}callbackUrl=${encodeURIComponent(callbackUrl)}`)
}
// Callback URL is already verified at this point, so safe to use if specified
if (callbackUrl) {
res.status(302).setHeader('Location', callbackUrl)
res.end()
return redirect(callbackUrl)
} else {
res.status(302).setHeader('Location', site)
res.end()
return redirect(baseUrl)
}
return done()
} catch (error) {
if (error.name === 'CreateUserError') {
res.status(302).setHeader('Location', `${baseUrl}/error?error=EmailCreateAccount`)
return redirect(`${baseUrl}${basePath}/error?error=EmailCreateAccount`)
} else {
res.status(302).setHeader('Location', `${baseUrl}/error?error=Callback`)
logger.error('CALLBACK_EMAIL_ERROR', error)
return redirect(`${baseUrl}${basePath}/error?error=Callback`)
}
res.end()
return done()
}
} else if (type === 'credentials' && req.method === 'POST') {
if (!useJwtSession) {
logger.error('CALLBACK_CREDENTIALS_JWT_ERROR', 'Signin in with credentials is only supported if JSON Web Tokens are enabled')
res.status(302).setHeader('Location', `${baseUrl}/error?error=Configuration`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Configuration`)
}
if (!provider.authorize) {
logger.error('CALLBACK_CREDENTIALS_HANDLER_ERROR', 'Must define an authorize() handler to use credentials authentication provider')
res.status(302).setHeader('Location', `${baseUrl}/error?error=Configuration`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Configuration`)
}
const credentials = req.body
// If promise is rejected / throws error then display Configuration error
let userObjectReturnedFromAuthorizeHandler
try {
userObjectReturnedFromAuthorizeHandler = await provider.authorize(credentials)
if (!userObjectReturnedFromAuthorizeHandler) {
return redirect(`${baseUrl}${basePath}/error?error=CredentialsSignin&provider=${encodeURIComponent(provider.id)}`)
}
} catch (error) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=Configuration`)
res.end()
return done()
if (error instanceof Error) {
return redirect(`${baseUrl}${basePath}/error?error=${encodeURIComponent(error)}`)
} else {
return redirect(error)
}
}
const user = userObjectReturnedFromAuthorizeHandler
const account = { id: provider.id, type: 'credentials' }
// If no user is returned, credentials are not valid
if (!user) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=CredentialsSignin&provider=${encodeURIComponent(provider.id)}`)
res.end()
return done()
try {
const signInCallbackResponse = await callbacks.signIn(user, account, credentials)
if (signInCallbackResponse === false) {
return redirect(`${baseUrl}${basePath}/error?error=AccessDenied`)
}
} catch (error) {
if (error instanceof Error) {
return redirect(`${baseUrl}${basePath}/error?error=${encodeURIComponent(error)}`)
} else {
return redirect(error)
}
}
const signinCallbackResponse = await callbacks.signin(user, account, credentials)
if (signinCallbackResponse === false) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=AccessDenied`)
res.end()
return done()
const defaultJwtPayload = {
name: user.name,
email: user.email,
picture: user.image
}
const defaultJwtPayload = { user, account }
const jwtPayload = await callbacks.jwt(defaultJwtPayload)
const jwtPayload = await callbacks.jwt(defaultJwtPayload, user, account, userObjectReturnedFromAuthorizeHandler, false)
// Sign and encrypt token
const newEncodedJwt = await jwt.encode({ secret: jwt.secret, token: jwtPayload, maxAge: sessionMaxAge })
const newEncodedJwt = await jwt.encode({ ...jwt, token: jwtPayload })
// Set cookie expiry date
const cookieExpires = new Date()
@@ -265,17 +284,9 @@ export default async (req, res, options, done) => {
cookie.set(res, cookies.sessionToken.name, newEncodedJwt, { expires: cookieExpires.toISOString(), ...cookies.sessionToken.options })
await dispatchEvent(events.signin, { user, account })
await dispatchEvent(events.signIn, { user, account })
if (callbackUrl) {
res.status(302).setHeader('Location', callbackUrl)
res.end()
} else {
res.status(302).setHeader('Location', site)
res.end()
}
return done()
return redirect(callbackUrl || baseUrl)
} else {
res.status(500).end(`Error: Callback for provider type ${type} not supported`)
return done()

View File

@@ -5,7 +5,7 @@ export default (req, res, options, done) => {
const { providers } = options
const result = {}
Object.entries(providers).map(([provider, providerConfig]) => {
Object.entries(providers).forEach(([provider, providerConfig]) => {
result[provider] = {
id: provider,
name: providerConfig.name,

View File

@@ -19,7 +19,7 @@ export default async (req, res, options, done) => {
if (useJwtSession) {
try {
// Decrypt and verify token
const decodedJwt = await jwt.decode({ secret: jwt.secret, token: sessionToken, maxAge: sessionMaxAge })
const decodedJwt = await jwt.decode({ ...jwt, token: sessionToken })
// Generate new session expiry date
const sessionExpiresDate = new Date()
@@ -30,9 +30,9 @@ export default async (req, res, options, done) => {
// as needed for presentation purposes (e.g. "you are logged in as…").
const defaultSessionPayload = {
user: {
name: decodedJwt.user && decodedJwt.user.name ? decodedJwt.user.name : null,
email: decodedJwt.user && decodedJwt.user.email ? decodedJwt.user.email : null,
image: decodedJwt.user && decodedJwt.user.image ? decodedJwt.user.image : null
name: decodedJwt.name || null,
email: decodedJwt.email || null,
image: decodedJwt.picture || null
},
expires: sessionExpires
}
@@ -45,7 +45,7 @@ export default async (req, res, options, done) => {
response = sessionPayload
// Refresh JWT expiry by re-signing it, with an updated expiry date
const newEncodedJwt = await jwt.encode({ secret: jwt.secret, token: jwtPayload, maxAge: sessionMaxAge })
const newEncodedJwt = await jwt.encode({ ...jwt, token: jwtPayload })
// Set cookie, to also update expiry date on cookie
cookie.set(res, cookies.sessionToken.name, newEncodedJwt, { expires: sessionExpires, ...cookies.sessionToken.options })
@@ -79,7 +79,7 @@ export default async (req, res, options, done) => {
}
// Pass Session through to the session callback
const sessionPayload = await callbacks.session(defaultSessionPayload)
const sessionPayload = await callbacks.session(defaultSessionPayload, user)
// Return session payload as response
response = sessionPayload

View File

@@ -8,9 +8,11 @@ export default async (req, res, options, done) => {
provider: providerName,
providers,
baseUrl,
csrfTokenVerified,
basePath,
adapter,
callbacks
callbacks,
csrfToken,
redirect
} = options
const provider = providers[providerName]
const { type } = provider
@@ -20,29 +22,22 @@ export default async (req, res, options, done) => {
return done()
}
if (type === 'oauth') {
oAuthSignin(provider, (error, oAuthSigninUrl) => {
if (type === 'oauth' && req.method === 'POST') {
const authParams = { ...req.query }
delete authParams.nextauth // This is probably not intended to be sent to the provider, remove
oAuthSignin(provider, csrfToken, (error, oAuthSigninUrl) => {
if (error) {
logger.error('SIGNIN_OAUTH_ERROR', error)
res
.status(302)
.setHeader('Location', `${baseUrl}/error?error=oAuthSignin`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=OAuthSignin`)
}
res.status(302).setHeader('Location', oAuthSigninUrl)
res.end()
return done()
})
return redirect(oAuthSigninUrl)
}, authParams)
} else if (type === 'email' && req.method === 'POST') {
if (!adapter) {
logger.error('EMAIL_REQUIRES_ADAPTER_ERROR')
res
.status(302)
.setHeader('Location', `${baseUrl}/error?error=Configuration`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=Configuration`)
}
const { getUserByEmail } = await adapter.getAdapter(options)
@@ -58,54 +53,30 @@ export default async (req, res, options, done) => {
const account = { id: provider.id, type: 'email', providerAccountId: email }
// Check if user is allowed to sign in
const signinCallbackResponse = await callbacks.signin(profile, account)
if (signinCallbackResponse === false) {
res.status(302).setHeader('Location', `${baseUrl}/error?error=AccessDenied`)
res.end()
return done()
}
// If CSRF token not verified, send the user to sign in page, which will
// display a new form with a valid token so that submitting it should work.
//
// Note: Adds ?csrf=true query string param to URL for debugging/tracking
if (!csrfTokenVerified) {
res
.status(302)
.setHeader(
'Location',
`${baseUrl}/signin?email=${encodeURIComponent(email)}&csrf=true`
)
res.end()
return done()
try {
const signinCallbackResponse = await callbacks.signIn(profile, account, { email, verificationRequest: true })
if (signinCallbackResponse === false) {
return redirect(`${baseUrl}${basePath}/error?error=AccessDenied`)
}
} catch (error) {
if (error instanceof Error) {
return redirect(`${baseUrl}${basePath}/error?error=${encodeURIComponent(error)}`)
} else {
return redirect(error)
}
}
try {
await emailSignin(email, provider, options)
} catch (error) {
logger.error('SIGNIN_EMAIL_ERROR', error)
res
.status(302)
.setHeader('Location', `${baseUrl}/error?error=EmailSignin`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/error?error=EmailSignin`)
}
res
.status(302)
.setHeader(
'Location',
`${baseUrl}/verify-request?provider=${encodeURIComponent(
provider.id
)}&type=${encodeURIComponent(provider.type)}`
)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/verify-request?provider=${encodeURIComponent(
provider.id
)}&type=${encodeURIComponent(provider.type)}`)
} else {
// If provider not supported, redirect to sign in page
res.status(302).setHeader('Location', `${baseUrl}/signin`)
res.end()
return done()
return redirect(`${baseUrl}${basePath}/signin`)
}
}

View File

@@ -4,28 +4,15 @@ import logger from '../../lib/logger'
import dispatchEvent from '../lib/dispatch-event'
export default async (req, res, options, done) => {
const { adapter, cookies, events, jwt, callbackUrl, csrfTokenVerified, baseUrl } = options
const sessionMaxAge = options.session.maxAge
const { adapter, cookies, events, jwt, callbackUrl, redirect } = options
const useJwtSession = options.session.jwt
const sessionToken = req.cookies[cookies.sessionToken.name]
if (!csrfTokenVerified) {
// If a csrfToken was not verified with this request, send the user to
// the signout page, as they should have a valid one now and clicking
// the signout button should work.
//
// Note: Adds ?csrf=true query string param to URL for debugging/tracking.
// @TODO Add support for custom signin URLs
res.status(302).setHeader('Location', `${baseUrl}/signout?csrf=true`)
res.end()
return done()
}
if (useJwtSession) {
// Dispatch signout event
try {
const decodedJwt = await jwt.decode({ secret: jwt.secret, token: sessionToken, maxAge: sessionMaxAge })
await dispatchEvent(events.signout, decodedJwt)
const decodedJwt = await jwt.decode({ ...jwt, token: sessionToken })
await dispatchEvent(events.signOut, decodedJwt)
} catch (error) {
// Do nothing if decoding the JWT fails
}
@@ -36,7 +23,7 @@ export default async (req, res, options, done) => {
try {
// Dispatch signout event
const session = await getSession(sessionToken)
await dispatchEvent(events.signout, session)
await dispatchEvent(events.signOut, session)
} catch (error) {
// Do nothing if looking up the session fails
}
@@ -56,7 +43,5 @@ export default async (req, res, options, done) => {
maxAge: 0
})
res.status(302).setHeader('Location', callbackUrl)
res.end()
return done()
return redirect(callbackUrl)
}

53
test/docker/app.yml Normal file
View File

@@ -0,0 +1,53 @@
# Start test app with local databases inside the container.
#
# Note: Uses Docker Compose v2 as v3 doesn't currently support extends.
# https://docs.docker.com/compose/compose-file/compose-file-v2/
version: '2.3'
services:
app:
build:
context: ../../
dockerfile: Dockerfile
environment:
# Set env vars in your current terminal or in .env in the root directory
- NEXTAUTH_URL=${NEXTAUTH_URL}
- NEXTAUTH_DATABASE_URL=${NEXTAUTH_DATABASE_URL}
- NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
- NEXTAUTH_JWT_SESSIONS=${NEXTAUTH_JWT_SESSIONS}
- NEXTAUTH_AUTH0_ID=${NEXTAUTH_AUTH0_ID}
- NEXTAUTH_AUTH0_SECRET=${NEXTAUTH_AUTH0_SECRET}
- NEXTAUTH_AUTH0_DOMAIN=${NEXTAUTH_AUTH0_DOMAIN}
- NEXTAUTH_FACEBOOK_ID=${NEXTAUTH_FACEBOOK_ID}
- NEXTAUTH_FACEBOOK_SECRET=${NEXTAUTH_FACEBOOK_SECRET}
- NEXTAUTH_GITHUB_ID=${NEXTAUTH_GITHUB_ID}
- NEXTAUTH_GITHUB_SECRET=${NEXTAUTH_GITHUB_SECRET}
- NEXTAUTH_GOOGLE_ID=${NEXTAUTH_GOOGLE_ID}
- NEXTAUTH_GOOGLE_SECRET=${NEXTAUTH_GOOGLE_SECRET}
- NEXTAUTH_TWITTER_ID=${NEXTAUTH_TWITTER_ID}
- NEXTAUTH_TWITTER_SECRET=${NEXTAUTH_TWITTER_SECRET}
- NEXTAUTH_EMAIL_SERVER=${NEXTAUTH_EMAIL_SERVER}
- NEXTAUTH_EMAIL_FROM=${NEXTAUTH_EMAIL_FROM}
ports:
- "3000:3000"
# mongo:
# extends:
# file: databases/mongo.yml
# service: mongo
# mssql:
# extends:
# file: databases/mssql.yml
# service: mssql
# mysql:
# extends:
# file: databases/mysql.yml
# service: mysql
# postgres:
# extends:
# file: databases/postgres.yml
# service: postgres

5918
test/docker/app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
{
"name": "next-auth-test",
"version": "0.0.1",
"description": "Test application for NextAuth.js",
"main": "",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"author": "Iain Collins <me@iaincollins.com>",
"license": "ISC",
"dependencies": {
"next": "^9.5.4",
"react": "^16.13.1",
"react-dom": "^16.13.1"
}
}

View File

@@ -0,0 +1,26 @@
import { Provider } from 'next-auth/client'
export default function App ({ Component, pageProps }) {
return (
<Provider
options={{
// Client Max Age controls how often the useSession in the client should
// contact the server to sync the session state. Value in seconds.
// e.g.
// * 0 - Disabled (always use cache value)
// * 60 - Sync session state with server if it's older than 60 seconds
clientMaxAge: 0,
// Keep Alive tells windows / tabs that are signed in to keep sending
// a keep alive request (which extends the current session expiry) to
// prevent sessions in open windows from expiring. Value in seconds.
//
// Note: If a session has expired when keep alive is triggered, all open
// windows / tabs will be updated to reflect the user is signed out.
keepAlive: 0
}}
session={pageProps.session}
>
<Component {...pageProps} />
</Provider>
)
}

View File

@@ -0,0 +1,118 @@
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
const options = {
// https://next-auth.js.org/configuration/providers
providers: [
Providers.Email({
server: process.env.NEXTAUTH_EMAIL_SERVER,
from: process.env.NEXTAUTH_EMAIL_FROM
}),
Providers.Apple({
clientId: process.env.NEXTAUTH_APPLE_ID,
clientSecret: {
appleId: process.env.NEXTAUTH_APPLE_ID,
teamId: process.env.NEXTAUTH_APPLE_TEAM_ID,
privateKey: process.env.NEXTAUTH_APPLE_PRIVATE_KEY,
keyId: process.env.NEXTAUTH_APPLE_KEY_ID
}
}),
Providers.Auth0({
clientId: process.env.NEXTAUTH_AUTH0_ID,
clientSecret: process.env.NEXTAUTH_AUTH0_SECRET,
domain: process.env.NEXTAUTH_AUTH0_DOMAIN
}),
Providers.Facebook({
clientId: process.env.NEXTAUTH_FACEBOOK_ID,
clientSecret: process.env.NEXTAUTH_FACEBOOK_SECRET
}),
Providers.GitHub({
clientId: process.env.NEXTAUTH_GITHUB_ID,
clientSecret: process.env.NEXTAUTH_GITHUB_SECRET
}),
Providers.Google({
clientId: process.env.NEXTAUTH_GOOGLE_ID,
clientSecret: process.env.NEXTAUTH_GOOGLE_SECRET
}),
Providers.Twitter({
clientId: process.env.NEXTAUTH_TWITTER_ID,
clientSecret: process.env.NEXTAUTH_TWITTER_SECRET
})
],
// Database optional. MySQL, Maria DB, Postgres and MongoDB are supported.
// https://next-auth.js.org/configuration/database
//
// Notes:
// * You must to install an appropriate node_module for your database
// * The Email provider requires a database (OAuth providers do not)
database: process.env.NEXTAUTH_DATABASE_URL,
// The secret should be set to a reasonably long random string.
// It is used to sign cookies and to sign and encrypt JSON Web Tokens, unless
// a seperate secret is defined explicitly for encrypting the JWT.
secret: process.env.NEXTAUTH_SECRET,
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
jwt: true
// Seconds - How long until an idle session expires and is no longer valid.
// maxAge: 30 * 24 * 60 * 60, // 30 days
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
// updateAge: 24 * 60 * 60, // 24 hours
},
// JSON Web tokens are only used for sessions if the `jwt: true` session
// option is set - or by default if no database is specified.
// https://next-auth.js.org/configuration/options#jwt
jwt: {
// A secret to use for key generation (you should set this explicitly)
// secret: 'INp8IvdIyeMcoGAgFGoA61DdBglwwSqnXJZkgz8PSnw',
// Set to true to use encryption (default: false)
// encryption: true,
// You can define your own encode/decode functions for signing and encryption
// if you want to override the default behaviour.
// encode: async ({ secret, token, maxAge }) => {},
// decode: async ({ secret, token, maxAge }) => {},
},
// You can define custom pages to override the built-in pages.
// The routes shown here are the default URLs that will be used when a custom
// pages is not specified for that route.
// https://next-auth.js.org/configuration/pages
pages: {
// signIn: '/api/auth/signin', // Displays signin buttons
// signOut: '/api/auth/signout', // Displays form with sign out button
// error: '/api/auth/error', // Error code passed in query string as ?error=
// verifyRequest: '/api/auth/verify-request', // Used for check email page
// newUser: null // If set, new users will be directed here on first sign in
},
// Callbacks are asynchronous functions you can use to control what happens
// when an action is performed.
// https://next-auth.js.org/configuration/callbacks
callbacks: {
// signIn: async (user, account, profile) => { return Promise.resolve(true) },
// redirect: async (url, baseUrl) => { return Promise.resolve(baseUrl) },
// session: async (session, user) => { return Promise.resolve(session) },
// jwt: async (token, user, account, profile, isNewUser) => { return Promise.resolve(token) }
},
// Events are useful for logging
// https://next-auth.js.org/configuration/events
events: { },
// Enable debug messages in the console if you are having problems
debug: false
}
export default (req, res) => NextAuth(req, res, options)

View File

@@ -0,0 +1,3 @@
export default (req, res) => {
res.send(JSON.stringify(process.env, null, 2))
}

View File

@@ -0,0 +1,8 @@
import jwt from 'next-auth/jwt'
const secret = process.env.SECRET
export default async (req, res) => {
const token = await jwt.getToken({ req, secret })
res.send(JSON.stringify(token, null, 2))
}

View File

@@ -0,0 +1,11 @@
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
if (session) {
res.send({ content: 'Protected content.' })
} else {
res.send({ content: 'Unprotected content.' })
}
}

View File

@@ -0,0 +1,6 @@
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
res.send(JSON.stringify(session, null, 2))
}

View File

@@ -0,0 +1,5 @@
import Package from 'next-auth/package.json'
export default (req, res) => {
res.send(Package.version)
}

View File

@@ -0,0 +1,7 @@
export default function IndexPage () {
return (
<div id='nextauth-test-app'>
<h1>NextAuth.js Test App</h1>
</div>
)
}

View File

@@ -0,0 +1,13 @@
import { useSession } from 'next-auth/client'
export default function TestPage () {
const [ session, loading ] = useSession()
return (
<div id='nextauth-test-page'>
<h1>NextAuth.js Test Page</h1>
{session && <p id="nextauth-signed-in">Signed in</p>}
{!session && !loading && <p id="nextauth-signed-out">Signed out</p>}
</div>
)
}

43
test/docker/databases.yml Normal file
View File

@@ -0,0 +1,43 @@
# Start Mongo, MSSQL, MySQL and Postgres databases on the current host running
# on their respective default ports. This is intended for developer convenience
# to make it easier to develop and test features manually.
#
# Note: Uses Docker Compose v2 as v3 doesn't currently support extends.
version: '2'
services:
mongo:
extends:
file: databases/mongo.yml
service: mongo
ports:
- "27017:27017"
mssql:
extends:
file: databases/mssql.yml
service: mssql
ports:
- "1433:1433"
mysql:
extends:
file: databases/mysql.yml
service: mysql
ports:
- "3306:3306"
postgres:
extends:
file: databases/postgres.yml
service: postgres
ports:
- "5432:5432"
fauna:
extends:
file: databases/fauna.yml
service: fauna
ports:
- 8443:8443

View File

@@ -0,0 +1,7 @@
version: '2'
services:
fauna:
image: fauna/faunadb
restart: always

View File

@@ -9,5 +9,3 @@ services:
MONGODB_USERNAME: nextauth
MONGODB_PASSWORD: password
MONGODB_DATABASE: nextauth
ports:
- "27017:27017"

View File

@@ -0,0 +1,13 @@
version: "2"
services:
mssql:
image: mcr.microsoft.com/mssql/server:2017-latest
restart: always
environment:
SA_PASSWORD: Pa55w0rd # minimum password complexity
ACCEPT_EULA: Y
# WARN: command overrides, default image start sequence, start.sh starts 'sql-server'
command: '/var/setup/start.sh'
volumes:
- ./mssql:/var/setup # mount setup files

View File

@@ -0,0 +1,7 @@
#!/usr/bin/env sh
# see https://github.com/Microsoft/mssql-docker
# no way to know when sql server is ready
until /opt/mssql-tools/bin/sqlcmd -S 127.0.01 -U sa -P Pa55w0rd -d master -i /var/setup/setup.sql
do sleep 1;
done
echo "NEXT_AUTH: setup completed"

View File

@@ -0,0 +1,29 @@
USE master;
/* did you tear down the container ? */
if not exists (select name
from sys.syslogins
where name = 'nextauth')
CREATE LOGIN nextauth
WITH PASSWORD = 'password',
CHECK_POLICY = OFF;
GO
/* did you tear down the container ? */
if not exists (select name
from sys.databases
where name = 'nextauth' )
CREATE database nextauth
GO
/* did you tear down the container ? */
if not exists(select [name]
from sys.sysusers
where name= 'nextauth')
CREATE USER nextauth
WITH DEFAULT_SCHEMA =[dbo];
GO
/*
* Adding user as sysadmin,
* So you can easily drop/create/re-create/alter the database
* You will need to login to 'master' to do that
*/
exec sp_addsrvrolemember @loginame = N'nextauth', @rolename = N'sysadmin'

View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
# launch setup on the background & start server
# otherise sqlservr won't start
/var/setup/setup.sh & /opt/mssql/bin/sqlservr

View File

@@ -10,6 +10,4 @@ services:
MYSQL_USER: nextauth
MYSQL_PASSWORD: password
MYSQL_DATABASE: nextauth
MYSQL_RANDOM_ROOT_PASSWORD: 'yes'
ports:
- "3306:3306"
MYSQL_RANDOM_ROOT_PASSWORD: 'yes'

View File

@@ -8,6 +8,4 @@ services:
environment:
POSTGRES_USER: nextauth
POSTGRES_PASSWORD: password
POSTGRES_DB: nextauth
ports:
- "5432:5432"
POSTGRES_DB: nextauth

View File

@@ -1,21 +0,0 @@
# Start Mongo, MySQL and Postgres databases
# Though other databases will be supported, these are the initial targets.
# Uses Docker Compose v2 as v3 doesn't support extends
version: '2'
services:
mongo:
extends:
file: mongo.yml
service: mongo
mysql:
extends:
file: mysql.yml
service: mysql
postgres:
extends:
file: postgres.yml
service: postgres

200
test/fauna.js Normal file
View File

@@ -0,0 +1,200 @@
/* eslint-disable */
const Adapters = require('../adapters');
const assert = require('assert');
const fauna = require('faunadb');
const q = fauna.query;
const adminClient = new fauna.Client({
secret: 'secret',
domain: 'localhost',
port: '8443',
scheme: 'http'
});
// Authenticated client against the new DB used for tests
let client = null;
const InitialiseDb = async () => {
await adminClient.query(
q.CreateDatabase({name: 'nextauth'})
);
const key = await adminClient.query(
q.CreateKey({
database: q.Database('nextauth'),
role: 'server'
})
);
client = new fauna.Client({
secret: key.secret,
domain: 'localhost',
port: '8443',
scheme: 'http'
});
await client.query(q.CreateCollection({name: 'account'}));
await client.query(q.CreateCollection({name: 'session'}));
await client.query(q.CreateCollection({name: 'user'}));
await client.query(q.CreateCollection({name: 'verification_request'}));
await client.query(q.CreateIndex({
name: 'account_by_provider_account_id',
source: q.Collection('account'),
unique: true,
terms: [
{ field: ['data', 'providerId'] },
{ field: ['data', 'providerAccountId'] }
]
}));
await client.query(q.CreateIndex({
name: 'session_by_token',
source: q.Collection('session'),
unique: true,
terms: [
{ field: ['data', 'sessionToken'] }
]
}));
await client.query(q.CreateIndex({
name: 'user_by_email',
source: q.Collection('user'),
unique: true,
terms: [
{ field: ['data', 'email'] }
]
}));
await client.query(q.CreateIndex({
name: 'verification_request_by_token',
source: q.Collection('verification_request'),
unique: true,
terms: [
{ field: ['data', 'token'] }
]
}));
}
const RunTests = async (adapter) => {
// createUser
const newUserResult = await adapter.createUser({
name: 'test user',
email: 'user@name.test',
image: 'https://www.gravatar.com/avatar/0'
});
assert.strictEqual(newUserResult.name, 'test user');
assert(newUserResult.createdAt !== null);
const userId = newUserResult.id;
// getUser
const user = await adapter.getUser(newUserResult.id);
assert.strictEqual(user.id, userId);
// getUserByEmail
const userByEmaiil = await adapter.getUserByEmail('user@name.test');
assert.strictEqual(userByEmaiil.id, userId);
// updateUser
const update = {
...user,
name: 'updated name'
};
const updatedUser = await adapter.updateUser(update);
assert.strictEqual(updatedUser.name, 'updated name');
assert.strictEqual(updatedUser.id, userId);
// linkAccount
const account = await adapter.linkAccount(
userId,
'github',
'oauth',
756832,
undefined,
'b7e3b00f2c596abc445f11abc445f1104c1b2b',
null
);
assert.strictEqual(account.userId, userId);
assert.strictEqual(account.providerId, 'github');
assert(account.createdAt !== null);
// getUserByProviderAccountId
const userByProviderAccountId = await adapter.getUserByProviderAccountId('github', 756832);
assert.strictEqual(userByProviderAccountId.email, user.email);
// createSession
const newSession = await adapter.createSession(user);
assert(newSession.sessionToken !== null);
assert(newSession.createdAt !== null);
assert(newSession.expires !== null);
// getSession
const session = await adapter.getSession(newSession.sessionToken);
assert.strictEqual(session.sessionToken, newSession.sessionToken);
// updateSession
const updatedSession = await adapter.updateSession(session);
assert(updatedSession.expires !== session.expires);
// deleteSession
await adapter.deleteSession(session.sessionToken);
// unlinkAccount
await adapter.unlinkAccount(userId, 'github', 756832);
// deleteUser
await adapter.deleteUser(userId);
// createVerificationRequest
let requestSent = false;
const newVerificationRequest = await adapter.createVerificationRequest(
'user@test.test',
'http://localhost/callback/email?email=test@test.test&token=123',
'123',
'abc',
{
sendVerificationRequest: ({}) => {
requestSent = true;
}
}
);
assert.strictEqual(newVerificationRequest.identifier, 'user@test.test');
assert(newVerificationRequest.token !== null && newVerificationRequest.token !== '');
assert(requestSent === true);
// getVerificationRequest
const verificationRequest = await adapter.getVerificationRequest('user@test.test', '123', 'abc');
assert.strictEqual(verificationRequest.identifier, 'user@test.test');
assert.strictEqual(verificationRequest.token, newVerificationRequest.token);
// deleteVerificationRequest
await adapter.deleteVerificationRequest('user@test.test', '123', 'abc');
}
;(async () => {
let error = false;
try {
// Initialise collections and create indexes
await InitialiseDb();
const adapterFactory = Adapters.Fauna.Adapter({faunaClient: client});
const adapter = await adapterFactory.getAdapter({baseUrl: 'http://localhost'});
await RunTests(adapter);
console.log('FaunaDB loaded ok');
} catch (error) {
console.error('FaunaDB error', error);
error = true;
} finally {
// Clean up the DB
await adminClient.query(
q.Delete(q.Database('nextauth'))
);
}
const retCode = error ? 1 : 0;
process.exit(retCode);
})();

141
test/fixtures/schemas/mssql.json vendored Normal file
View File

@@ -0,0 +1,141 @@
{
"users": {
"id": {
"type": "int",
"nullable": false
},
"name": {
"type": "varchar",
"nullable": true,
"default": null
},
"email": {
"type": "varchar",
"nullable": true,
"default": null
},
"email_verified": {
"type": "datetime",
"nullable": true,
"default": null
},
"image": {
"type": "varchar",
"nullable": true,
"default": null
},
"created_at": {
"type": "datetime",
"nullable": false
},
"updated_at": {
"type": "datetime",
"nullable": false
}
},
"accounts": {
"id": {
"type": "int",
"nullable": false
},
"compound_id": {
"type": "varchar",
"nullable": false
},
"user_id": {
"type": "int",
"nullable": false
},
"provider_type": {
"type": "varchar",
"nullable": false
},
"provider_id": {
"type": "varchar",
"nullable": false
},
"provider_account_id": {
"type": "varchar",
"nullable": false
},
"refresh_token": {
"type": "text",
"nullable": true,
"default": null
},
"access_token": {
"type": "text",
"nullable": true,
"default": null
},
"access_token_expires": {
"type": "datetime",
"nullable": true,
"default": null
},
"created_at": {
"type": "datetime",
"nullable": false
},
"updated_at": {
"type": "datetime",
"nullable": false
}
},
"sessions": {
"id": {
"type": "int",
"nullable": false
},
"user_id": {
"type": "int",
"nullable": false
},
"expires": {
"type": "datetime",
"nullable": false
},
"session_token": {
"type": "varchar",
"nullable": false
},
"access_token": {
"type": "varchar",
"nullable": false
},
"created_at": {
"type": "datetime",
"nullable": false
},
"updated_at": {
"type": "datetime",
"nullable": false
}
},
"verification_requests": {
"id": {
"type": "int",
"nullable": false
},
"identifier": {
"type": "varchar",
"nullable": false
},
"token": {
"type": "varchar",
"nullable": false
},
"expires": {
"type": "datetime",
"nullable": false
},
"created_at": {
"type": "datetime",
"nullable": false
},
"updated_at": {
"type": "datetime",
"nullable": false
}
}
}

View File

@@ -15,7 +15,7 @@
"default": null
},
"email_verified": {
"type": "timestamp",
"type": "timestamp(6)",
"nullable": true,
"default": null
},
@@ -69,7 +69,7 @@
"default": null
},
"access_token_expires": {
"type": "timestamp",
"type": "timestamp(6)",
"nullable": true,
"default": null
},
@@ -92,7 +92,7 @@
"nullable": false
},
"expires": {
"type": "timestamp",
"type": "timestamp(6)",
"nullable": false
},
"session_token": {
@@ -126,7 +126,7 @@
"nullable": false
},
"expires": {
"type": "timestamp",
"type": "timestamp(6)",
"nullable": false
},
"created_at": {

47
test/fixtures/sql/mssql.sql vendored Normal file
View File

@@ -0,0 +1,47 @@
-- FIXME Missing indexes!
CREATE TABLE accounts
(
id int IDENTITY(1,1) NOT NULL,
compound_id varchar(255) NOT NULL,
user_id int NOT NULL,
provider_type varchar(255) NOT NULL,
provider_id varchar(255) NOT NULL,
provider_account_id varchar(255) NOT NULL,
refresh_token text NULL,
access_token text NULL,
access_token_expires datetime NULL,
created_at datetime NOT NULL DEFAULT getdate(),
updated_at datetime NOT NULL DEFAULT getdate()
);
CREATE TABLE sessions
(
id int IDENTITY(1,1) NOT NULL,
user_id int NOT NULL,
expires datetime NOT NULL,
session_token varchar(255) NOT NULL,
access_token varchar(255) NOT NULL,
created_at datetime NOT NULL DEFAULT getdate(),
updated_at datetime NOT NULL DEFAULT getdate()
);
CREATE TABLE users
(
id int IDENTITY(1,1) NOT NULL,
name varchar(255) NULL,
email varchar(255) NULL,
email_verified datetime NULL,
image varchar(255) NULL,
created_at datetime NOT NULL DEFAULT getdate(),
updated_at datetime NOT NULL DEFAULT getdate()
);
CREATE TABLE verification_requests
(
id int IDENTITY(1,1) NOT NULL,
identifier varchar(255) NOT NULL,
token varchar(255) NOT NULL,
expires datetime NOT NULL,
created_at datetime NOT NULL DEFAULT getdate(),
updated_at datetime NOT NULL DEFAULT getdate()
);

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