👥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.
Last updated