Writing an Authentication Plug
The authentication process works in two stages. First, we’ll store the user ID in the session every time a new user registers or a user logs in. Second, we’ll check if there’s a new user in the session and store it in conn.assigns for every incoming request, so it can be accessed in our controllers and views. Let’s start with the second part because it’s a little easier to follow.
Create a file called lib/rumbl_web/controllers/auth.ex that looks like this:
| defmodule RumblWeb.Auth do |
| import Plug.Conn |
| |
| def init(opts), do: opts |
| |
| def call(conn, _opts) do |
| user_id = get_session(conn, :user_id) |
| user = user_id && Rumbl.Accounts.get_user(user_id) ... |
Get Programming Phoenix 1.4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.