Skip to content

Commit 8905287

Browse files
committed
docs: Document serverpod_auth_email setup and migrating from serverpod_auth to the new provider using serverpod_auth_migration
Closes serverpod/serverpod#3663
1 parent b893c13 commit 8905287

File tree

2 files changed

+336
-0
lines changed

2 files changed

+336
-0
lines changed
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
# Setup (`serverpod_auth_*`)
2+
3+
Serverpod comes with built-in support for authentication. It is possible to build a [custom authentication implementation](custom-overrides), but the recommended way to authenticate users is to use one of the provided `serverpod_auth_*` modules. The modules make it easy to authenticate with email or social sign-ins and currently supports signing in with email, Google, Apple, and Firebase.
4+
5+
Future versions of the authentication module will include more options. If you write another authentication module, please consider [contributing](/contribute) your code.
6+
7+
We provide the following packages of ready-to use authentication providers. They all include a basic user profile courtesy of `serverpod_auth_profile`, and session management through `serverpod_auth_session`.
8+
9+
|Package|Functionality|
10+
|-|-|
11+
|`serverpod_auth_email`|Ready to use email authentication.|
12+
|`serverpod_auth_apple`|Ready to use "Sign in with Apple" authentication.|
13+
|`serverpod_auth_google`|Ready to use "Sign in with Google authentication.|
14+
15+
If you would like the basic authentication offered by these package, but combine them with a different approach to session management or another kind of user profile have [a look at the underlying packages below](#low-level-building-blocks).
16+
17+
## Sessions
18+
19+
When using any of the "ready-to-use" authentication providers listed above, session management based on `serverpod_auth_session` is already included.
20+
21+
Just follow any of the individual authentication provider guides to set the `AuthSessions`' `authenticationHandler` on your `Serverpod` instance.
22+
23+
## Email
24+
25+
To get started with email based authentications, add `serverpod_auth_email` to your project. This will add a sign-up flow with email verification, and support logins and session management (through `serverpod_auth_session`). By default this adds user profiles for each registration through `serverpod_auth_profile`.
26+
27+
The only requirement for using this module is having a way to send out emails, so users can receive the initial verification email and also request a password reset later on.
28+
29+
30+
### Server setup
31+
32+
Add the module as a dependency to the server project's `pubspec.yaml`.
33+
34+
```sh
35+
$ dart pub add serverpod_auth_email_server
36+
```
37+
38+
39+
As the email auth module does not expose any endpoint by default, but rather just an [`abstract` endpoint](../working-with-endpoints#endpoint-method-inheritance), a subclass of the default implementation has to be added to the current project in order to expose its APIs to outside client.
40+
41+
For this add an `email_account_endpoint.dart` file to the project:
42+
43+
```dart
44+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart'
45+
as email_account;
46+
47+
/// Endpoint for email-based authentication.
48+
class EmailAccountEndpoint extends email_account.EmailAccountEndpoint {}
49+
```
50+
51+
In this `class` `@override`s could be used to augment the default endpoint implementation.
52+
53+
Next, add the authentication handler to the Serverpod instance.
54+
55+
```dart
56+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart';
57+
58+
void run(List<String> args) async {
59+
var pod = Serverpod(
60+
args,
61+
Protocol(),
62+
Endpoints(),
63+
authenticationHandler: AuthSessions.authenticationHandler, // Add this line
64+
);
65+
66+
...
67+
}
68+
```
69+
70+
In order to generate server and client the code for the newly added endpoint, run:
71+
72+
```bash
73+
$ serverpod generate
74+
```
75+
76+
Additionally the database schema will need to be extended to add new tables for the email accounts. Create a new migration using the `create-migration` command.
77+
78+
```bash
79+
$ serverpod create-migration
80+
```
81+
82+
As the last step, the email authentication package needs to be configured.
83+
For this set the `EmailAccounts.config` (from package `serverpod_auth_email_account_server`), which contains the business logic used by the endpoint. This configuration should be added before the `await pod.start();` call. Callbacks need to be provided for at least `sendRegistrationVerificationCode` and `sendPasswordResetVerificationCode`, while the rest can be left to their default values.
84+
85+
```dart
86+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart';
87+
88+
EmailAccounts.config = EmailAccountConfig(
89+
sendRegistrationVerificationCode: (
90+
final session, {
91+
required final email,
92+
required final accountRequestId,
93+
required final verificationCode,
94+
required final transaction,
95+
}) {
96+
// Send out actual email with the verification code
97+
},
98+
sendPasswordResetVerificationCode: (
99+
final session, {
100+
required final email,
101+
required final passwordResetRequestId,
102+
required final transaction,
103+
required final verificationCode,
104+
}) {
105+
// Send out actual email with the verification code
106+
},
107+
);
108+
```
109+
110+
If you're not hosting on Serverpod Cloud, you might consider an email sendout provider like [Mailjet](https://www.mailjet.com/) or [SendGrid](https://sendgrid.com/en-us).
111+
112+
It is up to the application to decide how to use the callbacks. Basically there are 2 primary approaches possible:
113+
- Send out the `verificationCode` and require that the client initiating the request completes the operation (account creation or password reset). In that case the user could copy/paste or retype the (short) verification into a form on the client.
114+
- Alternatively emails could contain a deep link with both the respective request ID and the verification code, which would then even support them being opened on any device (e.g. on a desktop, even if the original request was made on mobile).
115+
116+
Additionally you need to update the `passwords.yaml` file to include secrets for both `serverpod_auth_session_sessionKeyHashPepper` and `serverpod_auth_email_account_passwordHashPepper`.
117+
These should be random and at least 10 characters long. These pepper values must not be changed after the initial deployment of the server, as they are baked into every session key and stored password, and thus a roatation would invalidate previously created credentials.
118+
119+
After a restart of the Serverpod the new endpoints will be usable from the client.
120+
121+
### Client setup
122+
123+
First, add a dependency on `serverpod_auth_session_flutter` to your app's `pubspec.yaml`, to be able to make use of the sessions generated by the newly created email endpoint.
124+
125+
```yaml
126+
dependencies:
127+
flutter:
128+
sdk: flutter
129+
serverpod_flutter: ^3.0.0
130+
auth_example_client: # You generated client, name may differ
131+
path: ../auth_example_client
132+
133+
serverpod_auth_session_flutter: ^3.0.0 # Add this line
134+
```
135+
136+
Next, add the `SessionManager` to your app, passing it to the generated Serverpod `Client`.
137+
138+
```dart
139+
import 'package:serverpod_auth_session_flutter/serverpod_auth_session_flutter.dart' show SessionManager;
140+
141+
late SessionManager sessionManager;
142+
late Client client;
143+
144+
void main() async {
145+
// Need to call this as we are using Flutter bindings before runApp is called.
146+
WidgetsFlutterBinding.ensureInitialized();
147+
148+
// The session manager keeps track of the signed-in state of the user. You
149+
// can query it to see if the user is currently signed in and get information
150+
// about the user.
151+
sessionManager = SessionManager();
152+
await sessionManager.init();
153+
154+
// The android emulator does not have access to the localhost of the machine.
155+
// const ipAddress = '10.0.2.2'; // Android emulator ip for the host
156+
157+
// On a real device replace the ipAddress with the IP address of your computer.
158+
const ipAddress = 'localhost';
159+
160+
// Sets up a singleton client object that can be used to talk to the server from
161+
// anywhere in our app. The client is generated from your server code.
162+
// The client is set up to connect to a Serverpod running on a local server on
163+
// the default port. You will need to modify this to connect to staging or
164+
// production servers.
165+
client = Client(
166+
'http://$ipAddress:8080/',
167+
authenticationKeyManager: sessionManager,
168+
)..connectivityMonitor = FlutterConnectivityMonitor();
169+
170+
runApp(MyApp());
171+
}
172+
```
173+
174+
### User consolidation
175+
176+
<!-- TODO: Explain how to connect with other providers -->
177+
<!-- Other providers should just refer to this section, as the setup will be similar -->
178+
179+
## Low-level building blocks
180+
181+
### Session Management
182+
183+
|Package|Functionality|
184+
|-|-|
185+
|`serverpod_auth_session`|Database-backed session handling, with flexible configuration per session.|
186+
|`serverpod_auth_jwt`|JWT-based session implemented, which can also generate access token with public/private key cryptography to use with 3rd party services.|
187+
188+
### Authentication
189+
190+
The following package provide the core authentication functionality, but without providing a default `Endpoint` base implementation. Thus they can be combined with another session package and include further modification, like for example a custom user profile.
191+
192+
|Package|Functionality|
193+
|-|-|
194+
|`serverpod_auth_email_account`|Basic email authentication.|
195+
|`serverpod_auth_apple_account`|Basic "Sign in with Apple" authentication.|
196+
|`serverpod_auth_google_account`|Basic "Sign in with Google authentication.|
197+
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Upgrading from `serverpod_auth`
2+
3+
With the release of Serverpod 3.0, the single legacy `serverpod_auth` package was replaced with a set of modular packages providing flexible modules for users, authentication providers, profiles, and session management.
4+
5+
For an existing Serverpod application which makes use of `serverpod_auth` (which also still works with Serverpod 3.0) to upgrade to the new package, there exists `serverpod_auth_migration` to facilitate moving over all authentication- and user-related data into the new modules.
6+
Once the migration is complete, the legacy `serverpod_auth` module and the `serverpod_auth_migration` dependencies can be removed, which will also remove the then obsolete tables from the database.
7+
8+
Due to the modular approach, each used authentication provider (email, Apple, Google, etc.) needs to be configured individually for the migration.
9+
No matter through which authentication provider(s) a user is migrated, their profile will always be migrated as well by default.
10+
11+
## General timeline
12+
13+
The suggested migration timeline applies to all auth providers.
14+
15+
1. Add and configure the new auth modules for the desired providers, e.g. [email](../concepts/authentication/setup_new#email)
16+
2. Add the migration module and configure each auth provider and set up a background migration job <!-- TODO: Build and document Future call for migration -->
17+
3. Switch over all clients to use the new authentication endpoints
18+
4. After a sufficient percentage of the userbase has migrated to the new endpoints, disable sign-ups throught the legacy package <!-- TODO: Build and showcase "off switch" in legacy package -->
19+
5. Later on also disable logins and password resets on the `serverpod_auth` APIs
20+
6. Once all users have been migrated (some of them via the background processes, albeit without passwords) remove the dependency on `serverpod_auth` and `serverpod_auth_migration` and delete all obsolete code
21+
7. The next migration will then also remove obsolete tables
22+
23+
If the Serverpod application stores data with a relation to the `int` `UserInfo` ID, this needs to be migrated to the new `UUID` id of the `AuthUser`.
24+
To support this the `serverpod_auth_migration` packages provides a single hooks which is run for each user migration in which any related entities from your app can be migrated as well.
25+
26+
## Sessions
27+
28+
In order to support both sessions created by the legacy `serverpod_auth` and through the new `serverpod_auth_session` package, the `authenticationHandler` has to be updated to try both of them.
29+
Since an invalid/unknown session key just yields a `null` result, they can be chained like this:
30+
31+
```dart
32+
import 'package:serverpod_auth_server/serverpod_auth_server.dart' as auth;
33+
import 'package:serverpod_auth_email/serverpod_auth_email.dart' show AuthSessions;
34+
35+
36+
final pod = Serverpod(
37+
args,
38+
Protocol(),
39+
Endpoints(),
40+
authenticationHandler: (session, key) async {
41+
return await AuthSessions.authenticationHandler(session, key) ??
42+
await auth.authenticationHandler(session, key);
43+
},
44+
);
45+
```
46+
47+
<!-- TODO: Explain how all default modules use the new `serverpod_auth_session` and thus this only need to be configured once -->
48+
49+
<!-- Explain how to configure `authenticationHandler` to use both the old and new ones -->
50+
51+
## Migrating Email Authentications
52+
53+
Before starting with the email account migration, the email authentication from `serverpod_auth_email` must be [set up as described](../concepts/authentication/setup_new#email).
54+
55+
Since the password storage format changed between the legacy and new modules, and because we only have access to the plain text password during `login` (when it's sent from the client), there are 2 scenarios of migrating user accounts and the email authentication.
56+
57+
During a login we can verify the incoming credentials, and then migrate the entire account including the password.
58+
In all other cases (e.g. a password reset or a background migration job) we can migrate the user profile and account, but not set its password. The password could be set on a subsequent login (if it matches the one from the legacy module), or in case the user did not log in during the migration phase, they will have to resort to a password reset.
59+
60+
In order to avoid creating duplicate accounts for the "same" user in both the legacy and new system, one needs to ensure that the migration is always called before the new module would attempt any user lookups or creations.
61+
To support this in the new endpoint, which now exists as a subclass in the Serverpod application, the migration methods need to each affected endpoint.
62+
63+
```dart
64+
class EmailAccountEndpointWithMigration
65+
extends email_account.EmailAccountEndpoint {
66+
@override
67+
Future<String> login(
68+
final Session session, {
69+
required final String email,
70+
required final String password,
71+
}) async {
72+
// Add this before the call to `super` in the endpoint subclass
73+
await AuthMigrationEmail.migrateOnLogin(
74+
session,
75+
email: email,
76+
password: password,
77+
);
78+
79+
return super.login(session, email: email, password: password);
80+
}
81+
82+
@override
83+
Future<void> startRegistration(
84+
final Session session, {
85+
required final String email,
86+
required final String password,
87+
}) async {
88+
// Add this before the call to `super` in the endpoint subclass
89+
await AuthMigrationEmail.migrateOnLogin(
90+
session,
91+
email: email,
92+
password: password,
93+
);
94+
95+
return super.startRegistration(session, email: email, password: password);
96+
}
97+
98+
@override
99+
Future<void> startPasswordReset(
100+
final Session session, {
101+
required final String email,
102+
}) async {
103+
// Add this before the call to `super` in the endpoint subclass
104+
await AuthMigrationEmail.migrateWithoutPassword(session, email: email);
105+
106+
return super.startPasswordReset(session, email: email);
107+
}
108+
}
109+
```
110+
111+
After this modification, the endpoint will always attempt a migration first, because then proceeding with the desired request (eg. registering a new account if none exists yet).
112+
113+
The migration works fully out of the box. But in case the existing `UserInfo` should not be moved to a new `serverpod_auth_profile` `UserProfile`, this can be disabled through the `AuthMigrationEmailConfig`.
114+
115+
```dart
116+
AuthMigrationEmail.config = AuthMigrationConfig(
117+
importProfile: false,
118+
userMigrationHook: (session, {required newAuthUserId, required oldUserId, transaction}) => …,
119+
);
120+
```
121+
122+
## User ID Migration
123+
124+
<!-- TODO: Explain how a look up can be made during the transition, but finally any foreign keys need to be migrated.
125+
Depending on the project scale this might be easiest to do "at once", if possible.
126+
We should probably showcase a full example here, and figure out how to integrate that into the migration that will drop the final tables.
127+
128+
Maybe add optional AuthUser relation, and then in the end make it required (while dropping the `serverpod_auth` `UserInfo`)
129+
-->
130+
131+
<!-- 2 migration approaches:
132+
- create a new, nullable column for the auth user and then migrate over time
133+
- seem easier to update queries to use either the old or new ID
134+
- be careful to not use `onDelete=Cascade` on the old UserInfo references
135+
- we should take a look to see how table / columns are dropped in this case
136+
- create a second table, and copy the data over upon migration
137+
138+
- Old user clean up possible (maybe even advisable to catch outdated reads), but otherwise can just wait until the old package & migration is removed at which point the tables will be dropped.
139+
-->

0 commit comments

Comments
 (0)