Skip to content

Commit e483819

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 e483819

File tree

2 files changed

+317
-0
lines changed

2 files changed

+317
-0
lines changed
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
# Setup
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 `serverpod_auth_*` modules. The modules makes 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+
![Sign-in with Serverpod](https://github.com/serverpod/serverpod/raw/main/misc/images/sign-in.png)
8+
9+
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`.
10+
11+
|Package|Functionality|
12+
|-|-|
13+
|`serverpod_auth_email`|Ready to use email authentication.|
14+
|`serverpod_auth_apple`|Ready to use "Sign in with Apple" authentication.|
15+
|`serverpod_auth_google`|Ready to use "Sing in with Google authentication.|
16+
17+
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).
18+
19+
## Sessions
20+
21+
When using any of the "ready-to-use" authentication providers listed above, session management based on `serverpod_auth_session` is already included.
22+
23+
Just follow any of the individual guides to set the `authenticationHandler` on your `Serverpod` instance.
24+
25+
## Email
26+
27+
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`.
28+
29+
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.
30+
31+
32+
### Server setup
33+
34+
Add the module as a dependency to the server project's `pubspec.yaml`.
35+
36+
```sh
37+
$ dart pub add serverpod_auth_email_server
38+
```
39+
40+
Further it's advisable to depend on `serverpod_auth_session` directly as well, to avoid any lint warnings when using it later.
41+
42+
```sh
43+
$ dart pub add serverpod_auth_session_server
44+
```
45+
46+
As the email auth module does not expose any endpoint by default, but rather just an [`abstract` endpoint](concepts/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.
47+
48+
For this add an `email_account_endpoint.dart` file to the project:
49+
50+
```dart
51+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart'
52+
as email_account;
53+
54+
/// Endpoint for email-based authentication.
55+
class EmailAccountEndpoint extends email_account.EmailAccountEndpoint {}
56+
```
57+
58+
In this `class` `@override`s could be used to augment the default endpoint implementation.
59+
60+
Next, add the authentication handler to the Serverpod instance.
61+
62+
```dart
63+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart';
64+
65+
void run(List<String> args) async {
66+
var pod = Serverpod(
67+
args,
68+
Protocol(),
69+
Endpoints(),
70+
authenticationHandler: AuthSessions.authenticationHandler, // Add this line
71+
);
72+
73+
...
74+
}
75+
```
76+
77+
In order to generate server and client the code for the newly added endpoint, run:
78+
79+
```bash
80+
$ serverpod generate
81+
```
82+
83+
Additionally the database schema will need to be extended to add the new tables for the email accounts. Create a new migration using the `create-migration` command.
84+
85+
```bash
86+
$ serverpod create-migration
87+
```
88+
89+
As the last step, the email authentication package needs to be configured.
90+
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.
91+
92+
```dart
93+
import 'package:serverpod_auth_email_server/serverpod_auth_email_server.dart';
94+
95+
EmailAccounts.config = EmailAccountConfig(
96+
sendRegistrationVerificationCode: (
97+
final session, {
98+
required final email,
99+
required final accountRequestId,
100+
required final verificationCode,
101+
required final transaction,
102+
}) {
103+
// Send out actual email with the verification code
104+
},
105+
sendPasswordResetVerificationCode: (
106+
final session, {
107+
required final email,
108+
required final passwordResetRequestId,
109+
required final transaction,
110+
required final verificationCode,
111+
}) {
112+
// Send out actual email with the verification code
113+
},
114+
);
115+
```
116+
117+
<!-- TODO: Explain the need for an email provider -->
118+
119+
<!-- TODO: Explain deep link vs. "retype code" approach, and when one might want to send the "request ID" -->
120+
121+
Additionally you need to update the `passwords.yaml` file to include secrets for both `serverpod_auth_session_sessionKeyHashPepper` and `serverpod_auth_email_account_passwordHashPepper`.
122+
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.
123+
124+
After a restart of the Serverpod the new endpoints will be usable from the client.
125+
126+
### Client setup
127+
128+
129+
## App setup
130+
131+
<!-- TODO: Update fully -->
132+
133+
First, add dependencies to your app's `pubspec.yaml` file for the methods of signing in that you want to support.
134+
135+
```yaml
136+
dependencies:
137+
flutter:
138+
sdk: flutter
139+
serverpod_flutter: ^3.0.0
140+
auth_example_client:
141+
path: ../auth_example_client
142+
143+
serverpod_auth_session_flutter: ^3.0.0
144+
```
145+
146+
Next, you need to set up a `SessionManager`, which keeps track of the user's state. It will also handle the authentication keys passed to the client from the server, upload user profile images, etc.
147+
148+
```dart
149+
import 'package:serverpod_auth_session_flutter/serverpod_auth_session_flutter.dart' show SessionManager;
150+
151+
late SessionManager sessionManager;
152+
late Client client;
153+
154+
void main() async {
155+
// Need to call this as we are using Flutter bindings before runApp is called.
156+
WidgetsFlutterBinding.ensureInitialized();
157+
158+
// The session manager keeps track of the signed-in state of the user. You
159+
// can query it to see if the user is currently signed in and get information
160+
// about the user.
161+
sessionManager = SessionManager(
162+
caller: client.modules.auth,
163+
);
164+
await sessionManager.init();
165+
166+
// The android emulator does not have access to the localhost of the machine.
167+
// const ipAddress = '10.0.2.2'; // Android emulator ip for the host
168+
169+
// On a real device replace the ipAddress with the IP address of your computer.
170+
const ipAddress = 'localhost';
171+
172+
// Sets up a singleton client object that can be used to talk to the server from
173+
// anywhere in our app. The client is generated from your server code.
174+
// The client is set up to connect to a Serverpod running on a local server on
175+
// the default port. You will need to modify this to connect to staging or
176+
// production servers.
177+
client = Client(
178+
'http://$ipAddress:8080/',
179+
authenticationKeyManager: sessionManager,
180+
)..connectivityMonitor = FlutterConnectivityMonitor();
181+
182+
183+
runApp(MyApp());
184+
}
185+
```
186+
187+
### User consolidation
188+
189+
<!-- TODO: Explain how to connect with other providers -->
190+
191+
## Low-level building blocks
192+
193+
### Session Management
194+
195+
|Package|Functionality|
196+
|-|-|
197+
|`serverpod_auth_session`|Database-backed session handling, with flexible configuration per session.|
198+
|`serverpod_auth_jwt`|JWT-based session implemented, which can also generate access token with public/private key cryptography to use with 3rd party services.|
199+
200+
### Authentication
201+
202+
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.
203+
204+
|Package|Functionality|
205+
|-|-|
206+
|`serverpod_auth_email_account`|Basic email authentication.|
207+
|`serverpod_auth_apple_account`|Basic "Sign in with Apple" authentication.|
208+
|`serverpod_auth_google_account`|Basic "Sing in with Google authentication.|
209+
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Upgrading from `serverpod_auth`
2+
3+
With the release of Serverpod 3.0, the single legacy `serverpod_auth` package was replace with a set of modular packages providing flexible modules for users and profiles, authentication, and session management.
4+
5+
For an existing Serverpod application which makes use of `serverpod_auth` (which still works totally fine with 3.0) to upgrade to the new package, there exists `serverpod_auth_migration` to facilitate moving over all authentication data into the new models.
6+
Once the migration is complete, the legacy `serverpod_auth` module and the `serverpod_auth_migration` module 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 (unless the developers opts out of this).
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
16+
2. Add the migration module and configure each auth provider and set up a background migration job <!-- TODO: Showcase this -->
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 via the legacy package <!-- TODO: Showcase this -->
19+
5. Later on also disable logins and password resets on the `serverpod_auth` APIs
20+
6. Once all users have been migrated (also via the background processes, albeit without passwords) remove the dependency on `serverpod_auth` and `serverpod_auth_migration` and delete all related 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 `UserInfo` / user ID, this needs to be migrated to the new `UUID` id of the `AuthUser`.
24+
During the migration a mapping, if the user has been migrated, can be looked up via the `MigratedUser` entity. But as this model will be dropped with the removal of the `serverpod_auth_migration` package in step 6, one needs to ensure to also update ones own data to point to the new `AuthUser` IDs.
25+
26+
## UserInfo / User ID
27+
28+
<!-- TODO: Explain how a look up can be made during the transition, but finally any foreign keys need to be migrated.
29+
Depending on the project scale this might be easiest to do "at once", if possible.
30+
We should probably showcase a full example here, and figure out how to integrate that into the migration that will drop the final tables.
31+
32+
Maybe add optional AuthUser relation, and then in the end make it required (while dropping the `serverpod_auth` `UserInfo`)
33+
-->
34+
35+
## Sessions
36+
37+
<!-- TODO: Explain how all default modules use the new `serverpod_auth_session` and thus this only need to be configured once -->
38+
39+
## Migrating Email Authentications
40+
41+
<!-- TODO: The update with the final link -->
42+
Before starting with the email account migration, the email authentication from `serverpod_auth_email` must be [set up as described](06-concepts/11-authentication/01-setup_new.md#email).
43+
44+
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.
45+
46+
During a login we can verify the incoming credentials, and then migrate the entire account including the password.
47+
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.
48+
49+
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.
50+
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.
51+
52+
```dart
53+
class EmailAccountEndpointWithMigration
54+
extends email_account.EmailAccountEndpoint {
55+
@override
56+
Future<String> login(
57+
final Session session, {
58+
required final String email,
59+
required final String password,
60+
}) async {
61+
// Add this before the call to `super` in the endpoint subclass
62+
await AuthMigrationEmail.migrateOnLogin(
63+
session,
64+
email: email,
65+
password: password,
66+
);
67+
68+
return super.login(session, email: email, password: password);
69+
}
70+
71+
@override
72+
Future<void> startRegistration(
73+
final Session session, {
74+
required final String email,
75+
required final String password,
76+
}) async {
77+
// Add this before the call to `super` in the endpoint subclass
78+
await AuthMigrationEmail.migrateOnLogin(
79+
session,
80+
email: email,
81+
password: password,
82+
);
83+
84+
return super.startRegistration(session, email: email, password: password);
85+
}
86+
87+
@override
88+
Future<void> startPasswordReset(
89+
final Session session, {
90+
required final String email,
91+
}) async {
92+
// Add this before the call to `super` in the endpoint subclass
93+
await AuthMigrationEmail.migrateWithoutPassword(session, email: email);
94+
95+
return super.startPasswordReset(session, email: email);
96+
}
97+
}
98+
```
99+
100+
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).
101+
102+
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`.
103+
104+
```dart
105+
AuthMigrationEmail.config = AuthMigrationEmailConfig(
106+
importProfile: false,
107+
);
108+
```

0 commit comments

Comments
 (0)