πUsers & Authentication
Users
The user.ex
schema looks like this:
Users have some extra fields not included by phx.gen.auth
:
name
:string
A users full name
avatar
:string
A URL to the users avatar image
last_signed_in_ip
:string
The IP address of the last login by this user.
is_subscribed_to_marketing_notifications
:boolean
Track whether a user wants to receive marketing emails or not.
is_admin
:boolean
Admins get access to a special dashboard where they can modify users, see logs, etc.
is_suspended
:boolean
An admin can suspend a user, preventing them from logging in.
is_deleted
:boolean
Allows for soft deletion of users
is_onboarded
:boolean
Track whether or not a user has seen an onboarding screen after registering.
Authentication
We used phx.gen.auth (email/password) and modified the templates to use Tailwind and Petal Components.
Setting and accessing the current user
Controller actions
For controller actions we use the plug provided by mix phx.gen.auth
to set conn.assigns.current_user
.
You can see the :fetch_current_user
plug used in the :browser
pipeline in the router.
If you want to enforce the user then you can use the :require_authenticated_user
plug.
Live views
We can't rely on our plugs in live views, since live views connect over web sockets and avoid the traditional request/response lifecycle. However, a live view will have access to the session, which contains the user token set upon login. Hence, in the live view mount we can use the token to find the user_token
set in our database for that users session, and from there obtain the logged in user.
Instead of doing this on every live view mount
function, we can extract this out into an on_mount function and then apply it in the router, like a mini pipeline.
Social login providers
Petal Pro uses Ueberauth to handle social providers. Ueberauth simplifies the oauth process and have a large number of providers supported. We have set up a couple of providers to get you started:
Google
Github
How does it work?
A user is redirected to a provider. The URL for this redirect is generated by the Ueberauth library:
When you setup either "Google" or "Github", buttons will appear in the sign in and register pages that go to those URL's above.
Once a user has successfully signed in to the provider, they are redirected back to your web application. You can see where they end up by looking in the router:
In the file user_ueberauth_controller.ex
there are callback functions - one for each provider. In these callback functions we take the user info provided by the provider and use that to sign in a user (registering them if they aren't already):
How does this fit in with the existing `user` schema?
The user table doesn't change. Everything revolves around a user's email address. A user might register with a password and some time later login via Google. As long as the email used for Google sign in is the same as the registered email, then the login will work. The same goes for Github and Twitter.
If a user doesn't exist and they login via a provider, then they will be registered under the email address given by the provider. Since the user table has a not-null constraint on the hashed_password
column, a password will be randomly generated. This way we don't modify the original table structure of the mix phx.gen.auth
generator.
If a user logs in with a provider and then wants to change their (randomly generated) password they will have to click "Forgot my password".
What if the user forgets what social login they used?
Under this implementation there is nothing you can do apart from tell the user to try each provider and see which works. You could add a new field to the user schema (user.provider
) if you like.
Setup Google sign in
Create a Google Project
Create Oauth 2.0 Client ID (youβll likely have to create an OAuth consent screen before you can create the OAuth Client ID)
The user type youβll require will be External
Go to "Create credentials" -> "OAuth client ID" and fill in the details - make sure of the following:
Authorized JavaScript origins -
http://localhost:4000
Authorized redirect URIs -
http://localhost:4000/auth/google/callback
Add your client ID + client secret to your .env file:
export GOOGLE_OAUTH_CLIENT_ID=""
export GOOGLE_OAUTH_SECRET=""
Stop your server and make sure you enter
direnv allow
Start your server again
Setup Github sign in
Create an OAuth App - it can be either under your personal account or an organization:
Personal account:
Click your avatar -> Settings
Developer settings (down the bottom)
Oauth Apps
Create
Organization account:
Go to your organization's profile
Settings tab
Developer settings (down the bottom)
OAuth apps
Create
Fill in the details - the only thing that matters is "Authorization callback URL", which should be
http://localhost:4000/auth/github
Generate a new client secret
Paste client ID and secret into your
.env
file:export GITHUB_OAUTH_CLIENT_ID=""
export GITHUB_OAUTH_SECRET=""
Adding more providers
See a list of Ueberauth strategies here. You can copy how we've done it for the previous 3 providers. Check out the file user_ueberauth_controller.ex
for how to deal with the callbacks. Your main job is taking the data given by the provider and using it to register a user.
Passwordless
If enabled, users can both register and login without a password (it's enabled by default).
Passwordless sign in was added in v1.2.0. You can toggle it on and off in config.exs
:
When it's enabled, a "Continue with passwordless" button will show up on the sign-in and register pages:
How passwordless works
Passwordless allows users to either register or log in with their email address. They get sent a code and use the code as a temporary password. The code expires in a short timeframe and gets deleted if the user enters the wrong code for more than a couple of attempts.
You can think of passwordless as another social login. However, instead of a company like Github verifying the user's credentials, the user's email service verifies them instead. The main difference is that you don't get other information like a user's name and avatar with passwordless - only the email address.
This means users can register and access your web app with only an email. For Petal Pro this is okay, as during onboarding we ask the user to add their name. We also generate a random password for them (every user requires a password as a database rule set by phx.gen.auth). A user therefore can click "Reset password" if they like and choose to use password-based login in the future.
Passwordless process:
User submits email
Find or create a user using the email (new users are given a random password, which they can reset at any time), and set the user to
assigns.auth_user
A
user_token
is generated with the encrypted pin code in itPush patch to
/passwordless/sign-in-code/:hashed_user_id
(user id is obfuscated in a hashed format using the HashId lib)The user enters the code sent to their email (gets a limited number of attempts before the
user_token
is deletedIf correct - generates a sign-in token for the user - however live views can't insert cookies, so we need to make a trip to the server
Place the sign-in token in a hidden field in a form (encoded it as base64)
Submit the form using phx-trigger-action
This POSTs it to
PetalProWeb.UserSessionController.create_from_token/2
create_from_token/2
will use the token to log the user in (set the appropriate cookie)
Two-factor authentication (2FA) with TOTP
2FA boosts the security of your web application by allowing users to opt into a two-factored sign-in procedure (their ordinary sign-in plus entering a one-time password).
Users can go to their settings and enable 2FA by syncing their account to a tool that implements the Time-based One-time Password (TOTP) algorithm (the main one being Google Authenticator).
Once set up the user will also be provided with some backup codes (in case they lose their phone).
Now, when signing in a user will be forced to enter a TOTP from their authenticator app:
How is TOTP implemented?
The schema looks like this:
The key field is the secret
. This is what is passed to the authenticator app and allows the web application to work out which codes are correct.
How to turn off 2FA
The simplest way is to remove access to the 2FA settings. This will prevent users from setting it up. In future it will also be easy enough to turn it back on if you want.
Remove the routes:
2. Remove the menu item in the user settings layout:
Last updated