Protect Routes with Plugs
Learn how to add session management in a Phoenix application
We'll cover the following...
The authentication service integrates with the Phoenix stack to provide infrastructure for session management including plugs that we can use in the router to control access to our routes.
Defining the authentication service
The authentication service is defined in the file pento/lib/pento_web/controllers/user_auth.ex
. We could open up the code base, but instead, let’s do a quick review in IEx
to see what the public API looks like.
Fire up the IEx in the terminal below with iex -S mix
, and key this in:
exports PentoWeb.UserAuth
And, we should see exported plug functions like this:
fetch_current_user/2log_in_user/2log_in_user/3log_out_user/1redirect_if_user_is_authenticated/2require_authenticated_user/2
All of these functions are plugs. The first fetches an authenticated user and adds it into the connection. The next three log users in and out. The last two plugs direct users between pages based on whether they are logged in or not. ...