-
Notifications
You must be signed in to change notification settings - Fork 67
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update auth helpers READMEs to include full EdgeDB Auth setup #1085
Open
beerose
wants to merge
7
commits into
master
Choose a base branch
from
auth-helpers-docs
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ed49597
Update auth helpers READMEs to include full EdgeDB Auth setup
beerose c0c4749
sql -> esdl
beerose 0d3de7c
replace note with CAUTION
beerose d7e7d32
add ngrok and cloudflare tunnel urls examples
beerose c9cd2e2
Update packages/auth-express/readme.md
beerose 7ba1a06
revert
beerose 3a3a855
Merge branch 'auth-helpers-docs' of https://github.com/edgedb/edgedb-…
beerose File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,7 +17,6 @@ npm install @edgedb/auth-express | |
**Prerequisites**: | ||
- Node v18+ | ||
- **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. | ||
- Before adding EdgeDB auth to your Express app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers (you can do this in CLI or EdgeDB UI). Refer to the auth extension docs for details on how to do this. | ||
- We depend on the following middleware being installed in your Express app: | ||
- `body-parser`: both JSON and urlencoded | ||
- `cookie-parser` | ||
|
@@ -39,7 +38,95 @@ This library provides a few affordances for adding EdgeDB Auth to your existing | |
- Middleware to attach sessions to requests. | ||
- Some additional utility functions for handling various auth related concerns. | ||
|
||
## Configuring the `ExpressAuth` class | ||
### EdgeDB Auth Setup | ||
|
||
Before adding EdgeDB auth to your Express server, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers. | ||
|
||
1. Enable the EdgeDB Auth extension in your schema: | ||
|
||
Add the following to your EdgeDB schema: | ||
|
||
```esdl | ||
using extension auth; | ||
``` | ||
|
||
Once added, make sure to apply the schema changes by migrating your database schema: | ||
|
||
```sh | ||
$ edgedb migration create | ||
$ edgedb migrate | ||
``` | ||
|
||
2. Configure EdgeDB Auth settings: | ||
|
||
Next, you'll need to configure the EdgeDB Auth extension. This involves setting up essential parameters, such as signing keys and allowed redirect URLs. | ||
|
||
_Below, we're showing how to set up the EdgeDB authentication using EdgeQL queries. To run these commands, you need to start the EdgeDB instance first (`edgedb`). Alternatively, you can use the EdgeDB UI (`edgedb ui`) to configure the authentication settings interactively._ | ||
|
||
**Signing Key** | ||
|
||
This key is used to sign JWT tokens. You can generate one using OpenSSL: | ||
|
||
```sh | ||
$ openssl rand -base64 32 | ||
``` | ||
|
||
Once generated, configure the signing key in EdgeDB: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::AuthConfig::auth_signing_key := '<your-generated-key>'; | ||
``` | ||
|
||
**Allowed Redirect URLs** | ||
|
||
This setting ensures that redirects are limited to the URLs under your control. Configure the allowed URLs with the following command: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::AuthConfig::allowed_redirect_urls := { | ||
'http://localhost:3000', | ||
'https://example.trycloudflare.com', | ||
'https://example.ngrok.io', | ||
}; | ||
``` | ||
|
||
**Authentication providers** | ||
|
||
You need to configure at least one authentication provider. For example, to add an email/password provider, use the following command: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH | ||
INSERT ext::auth::EmailPasswordProviderConfig { | ||
require_verification := false | ||
}; | ||
``` | ||
|
||
> [!CAUTION] | ||
> In production environments, it is recommended to set require_verification to true to ensure users verify their email addresses. | ||
|
||
**SMTP for email verification (optional)** | ||
|
||
If using the email/password provider, you need to configure SMTP for email verification and password reset emails. Here's an example using a local SMTP server like Mailpit for development purposes: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::sender := '[email protected]'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::host := 'localhost'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::port := <int32>1025; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::security := 'STARTTLSOrPlainText'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::validate_certs := false; | ||
``` | ||
|
||
### Configuring the `ExpressAuth` class | ||
|
||
After [configuring the EdgeDB Auth extension](https://www.edgedb.com/docs/guides/auth/index), you can set up the various auth routes with our route builders. | ||
|
||
|
@@ -56,7 +143,7 @@ const auth = createExpressAuth(client, { | |
}); | ||
``` | ||
|
||
## Using the session middleware: `createSessionMiddleware` | ||
### Using the session middleware: `createSessionMiddleware` | ||
|
||
We provide a middleware factory that will attach an `ExpressAuthSession` object to your request object, which you can use to make authenticated queries, or protect routes. | ||
|
||
|
@@ -80,7 +167,7 @@ app.get("/dashboard", (req: expressAuth.SessionRequest, res) => { | |
}); | ||
``` | ||
|
||
### Create your own `requireAuth` middleware | ||
#### Create your own `requireAuth` middleware | ||
|
||
You can centralize the logic to redirect unauthenticated routes into a custom middleware like this: | ||
|
||
|
@@ -110,7 +197,7 @@ app.get("/dashboard", requireAuth, (req: expressAuth.SessionRequest, res) => { | |
}); | ||
``` | ||
|
||
## Adding route handlers | ||
### Adding route handlers | ||
|
||
Route handlers can be added either using one or more of our "router factories", or by constructing your own Express `Router` object, and attaching the necessary middleware to routes that you configure yourself. The factory pattern makes it easy to quickly get a standardized set of routes to handle either the built-in UI, or some combination of email/password and/or OAuth routes. For maximum control over route locations, custom middleware patterns, or integration into existing router structures, you can use the router middleware. | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,14 +2,103 @@ | |
|
||
> Warning: This library is still in an alpha state, and so, bugs are likely and the api's should be considered unstable and may change in future releases. | ||
|
||
### Setup | ||
## Setup | ||
|
||
**Prerequisites**: | ||
- Node v18+ | ||
- **Note**: Due to using the `crypto` global, you will need to start Node with `--experimental-global-webcrypto`. You can add this option to your `NODE_OPTIONS` environment variable, like `NODE_OPTIONS='--experimental-global-webcrypto'` in the appropriate `.env` file. | ||
- Before adding EdgeDB auth to your Next.js app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers. Refer to the auth extension docs for details on how to do this. | ||
|
||
1. Initialize the auth helper by passing an EdgeDB `Client` object to `createAuth()`, along with some configuration options. This will return a `NextAppAuth` object which you can use across your app. Similarly to the `Client` it's recommended to export this auth object from some root configuration file in your app. | ||
### EdgeDB Auth Setup | ||
|
||
Before adding EdgeDB auth to your Next.js app, you will first need to enable the `auth` extension in your EdgeDB schema, and have configured the extension with some providers. | ||
|
||
1. Enable the EdgeDB Auth extension in your schema: | ||
|
||
Add the following to your EdgeDB schema: | ||
|
||
```esdl | ||
using extension auth; | ||
``` | ||
|
||
Once added, make sure to apply the schema changes by migrating your database schema: | ||
|
||
```sh | ||
$ edgedb migration create | ||
$ edgedb migrate | ||
``` | ||
|
||
2. Configure EdgeDB Auth settings: | ||
|
||
Next, you'll need to configure the EdgeDB Auth extension. This involves setting up essential parameters, such as signing keys and allowed redirect URLs. | ||
|
||
_Below, we're showing how to set up the EdgeDB authentication using EdgeQL queries. To run these commands, you need to start the EdgeDB instance first (`edgedb`). Alternatively, you can use the EdgeDB UI (`edgedb ui`) to configure the authentication settings interactively._ | ||
|
||
**Signing Key** | ||
|
||
This key is used to sign JWT tokens. You can generate one using OpenSSL: | ||
|
||
```sh | ||
$ openssl rand -base64 32 | ||
``` | ||
|
||
Once generated, configure the signing key in EdgeDB: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::AuthConfig::auth_signing_key := '<your-generated-key>'; | ||
``` | ||
|
||
**Allowed Redirect URLs** | ||
|
||
This setting ensures that redirects are limited to the URLs under your control. Configure the allowed URLs with the following command: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::AuthConfig::allowed_redirect_urls := { | ||
'http://localhost:3000', | ||
'https://example.trycloudflare.com', | ||
'https://example.ngrok.io', | ||
}; | ||
``` | ||
|
||
**Authentication providers** | ||
|
||
You need to configure at least one authentication provider. For example, to add an email/password provider, use the following command: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH | ||
INSERT ext::auth::EmailPasswordProviderConfig { | ||
require_verification := false | ||
}; | ||
``` | ||
|
||
> [!CAUTION] | ||
> In production environments, it is recommended to set require_verification to true to ensure users verify their email addresses. | ||
|
||
**SMTP for email verification (optional)** | ||
|
||
If using the email/password provider, you need to configure SMTP for email verification and password reset emails. Here's an example using a local SMTP server like Mailpit for development purposes: | ||
|
||
```esdl | ||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::sender := '[email protected]'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::host := 'localhost'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::port := <int32>1025; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::security := 'STARTTLSOrPlainText'; | ||
|
||
CONFIGURE CURRENT BRANCH SET | ||
ext::auth::SMTPConfig::validate_certs := false; | ||
``` | ||
|
||
### Initialize EdgeDB Auth Helper | ||
|
||
Initialize the auth helper by passing an EdgeDB `Client` object to `createAuth()`, along with some configuration options. This will return a `NextAppAuth` object which you can use across your app. Similarly to the `Client` it's recommended to export this auth object from some root configuration file in your app. | ||
|
||
```ts | ||
// edgedb.ts | ||
|
@@ -33,7 +122,9 @@ | |
- `passwordResetPath?: string`: The path relative to the `baseUrl` of the the password reset page; needed if you want to enable password reset emails in your app. | ||
- `magicLinkFailurePath?: string`: The path relative to the `baseUrl` of the page we should redirect users to if there is an error when trying to sign in with a magic link. The page will get an `error` search parameter attached with an error message. This property is required if you use the Magic Link authentication feature. | ||
|
||
2. Setup the auth route handlers, with `auth.createAuthRouteHandlers()`. Callback functions can be provided to handle various auth events, where you can define what to do in the case of successful signin's or errors. You only need to configure callback functions for the types of auth you wish to use in your app. | ||
### Auth Route Handlers Setup | ||
|
||
Setup the auth route handlers, with `auth.createAuthRouteHandlers()`. Callback functions can be provided to handle various auth events, where you can define what to do in the case of successful signin's or errors. You only need to configure callback functions for the types of auth you wish to use in your app. | ||
|
||
```ts | ||
// app/auth/[...auth]/route.ts | ||
|
@@ -68,7 +159,9 @@ | |
|
||
By default the handlers expect to exist under the `/auth` path in your app, however if you want to place them elsewhere, you will also need to configure the `authRoutesPath` option of `createAuth` to match. | ||
|
||
3. Now we just need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the EdgeDB Auth's builtin UI. Or alternatively you can implement your own custom UI. | ||
### UI Setup | ||
|
||
Now we need to setup the UI to allow your users to sign in/up, etc. The easiest way to get started is to use the EdgeDB Auth's builtin UI. Or alternatively you can implement your own custom UI. | ||
|
||
**Builtin UI** | ||
|
||
|
@@ -92,7 +185,7 @@ | |
- `signout` | ||
- `isPasswordResetTokenValid(resetToken: string)`: Checks if a password reset token is still valid. | ||
|
||
### Usage | ||
## Usage | ||
|
||
Now you have auth all configured and user's can signin/signup/etc. you can use the `auth.getSession()` method in your app pages to retrieve an `AuthSession` object. This session object allows you to check if the user is currently logged in with the `isSignedIn` method, and also provides a `Client` object automatically configured with the `ext::auth::client_token` global, so you can run queries using the `ext::auth::ClientTokenIdentity` of the currently signed in user. | ||
|
||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These step numbers end up being indented in a weird way compared to the explanatory text. Maybe we don't need the numbers, just have them as subheadings?
wdyt?