This episode is part 3 in a Phoenix 1.4 Chat Server series:
In this episode we build out an Auth Plug for our Phoenix 1.4 Chat Server. Here's the plan:
- Add the auth plug to the browser pipeline in the router
- In the
call function of the plug, check the session for a current user, get that user from the DB and put it into the
conn.assigns. If nobody is logged in, set
nil and put it into the assigns.
- Also set whether or not the current user is an admin and put it into the assigns.
- In templates, use
@current_user to get the current user and
@admin_user to see if the user has admin access.
- Add function plugs for restricting pages to logged in or admin users. If there is a current (or admin) user, they return the conn unchanged, otherwise they redirect, show an error and halt.
- Import those two function plugs into controllers
- Create a function plug in the user controller for restricting actions to the "correct" user. E.g., users can edit their own accounts but not each others.
At the end of this episode, we can restrict any action in any controller to only logged-in users or to only admins by adding just a single line of code.