Skip to content
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
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions packages/auth-core/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

This library contains some low-level utilities to help working with the EdgeDB auth extension; namely resolving the api endpoint urls from an edgedb `Client` object, providing wrappers around those api's to help handle the various auth flows (including handling PKCE), and adding typesafety.

It is recommended to instead use the separate helper libraries created to make integration with popular frameworks as easy as possible. Currently supported frameworks:
It is recommended to instead use the separate helper libraries created to make integration with popular frameworks as easy as possible. Currently supported frameworks and libraries:

- Next.js (@edgedb/auth-nextjs)
- Next.js ([@edgedb/auth-nextjs](https://github.com/edgedb/edgedb-js/tree/master/packages/auth-nextjs))
- Remix ([@edgedb/auth-remix](https://github.com/edgedb/edgedb-js/tree/master/packages/auth-remix))
- SvelteKit ([@edgedb/auth-sveltekit](https://github.com/edgedb/edgedb-js/tree/master/packages/auth-sveltekit))
- Express ([@edgedb/auth-express](https://github.com/edgedb/edgedb-js/tree/master/packages/auth-express))
- _...more coming soon_
95 changes: 90 additions & 5 deletions packages/auth-express/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -39,7 +38,93 @@ 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:
Copy link
Collaborator

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?

Suggested change
1. Enable the EdgeDB Auth extension in your schema:
#### Enable the EdgeDB Auth extension in your schema

wdyt?


Add the following to your EdgeDB schema:

```sql
beerose marked this conversation as resolved.
Show resolved Hide resolved
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:

```sql
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:

```sql
CONFIGURE CURRENT BRANCH SET
ext::auth::AuthConfig::allowed_redirect_urls := {
'http://localhost:3000',
'http://localhost:3000/auth'
beerose marked this conversation as resolved.
Show resolved Hide resolved
};
```

**Authentication providers**

You need to configure at least one authentication provider. For example, to add an email/password provider, use the following command:

```sql
CONFIGURE CURRENT BRANCH
INSERT ext::auth::EmailPasswordProviderConfig {
require_verification := false
};
```

_Note: In production environments, it is recommended to set require_verification to true to ensure users verify their email addresses._
beerose marked this conversation as resolved.
Show resolved Hide resolved

**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:

```sql
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.

Expand All @@ -56,7 +141,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.

Expand All @@ -80,7 +165,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:

Expand Down Expand Up @@ -110,7 +195,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.

Expand Down
103 changes: 97 additions & 6 deletions packages/auth-nextjs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,101 @@

> 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:

```sql
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:

```sql
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:

```sql
CONFIGURE CURRENT BRANCH SET
ext::auth::AuthConfig::allowed_redirect_urls := {
'http://localhost:3000',
'http://localhost:3000/auth'
};
```

**Authentication providers**

You need to configure at least one authentication provider. For example, to add an email/password provider, use the following command:

```sql
CONFIGURE CURRENT BRANCH
INSERT ext::auth::EmailPasswordProviderConfig {
require_verification := false
};
```

_Note: 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:

```sql
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
Expand All @@ -33,7 +120,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
Expand Down Expand Up @@ -68,7 +157,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**

Expand All @@ -92,7 +183,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.

Expand Down
Loading