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
callfunction 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
niland 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_userto get the current user and
@admin_userto 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.
(Source code available for premium members)
Next episode: Part 5