Magic Link

Let users sign in with a magic link, delivered to their email. While the link can be opened on any device, it will only sign the user in on the device from which the link was requested.

Level: Easy
9
233
4

Adding to our accounts context

First, a minor change we'll make is to allow our confirm_user_multi function to accept a custom context. We'll need this later for consuming email tokens delivered as magic links.

Next, we'll need three new context functions. One to deliver the email that contains our magic link. Another, for when the magic link is opened. And lastly, one that will consume a token to finally log the user in.

An overview of how our magic link will work:

deliver_user_magic_log_in/2
If we were able to find an existing user for the submitted email, an email token, which is an instance of a UserToken, is created for the user. The encoded token is sent to the email.
magic_log_in_user/1
When the magic link is opened, we verify the magic link token and broadcast a message via PubSub signaling any LiveViews waiting on this token to trigger a log in action.
complete_magic_log_in_user/1
Finally, we complete the login process by verifying the token and deleting it after use.

User schema changes

A new virtual field session_id is added to the User schema. This will be used to broadcast messages for specific magic login tokens.

Notification updates

A new function deliver_magic_log_in/2 sends an email containing the magic login link to the user.

Token management

The token validity for magic links is set to one day, and the verify_email_token_query/2 function is updated to include session_id in the selected fields.

Controller changes

A new :create action handles the login process using the magic link token.

Add to existing login page

Add a link to take a logged out user to the magic login LiveView.

LiveView for magic login

The file user_magic_login_live.ex is added to handle the frontend logic for requesting and verifying magic login links. It provides forms and feedback for the user throughout the process.

Router updates

Routes are added for the new magic link login pages.