Login and Authentication: Part 2

  • Authentication
  • Automatic login on signup

Now that we have the concept, it's time to implement this for our user login. In this section, we add an authentication pipeline for routes that need authentication and we add an endpoint that allows our frontend to login.

Adding authentication

Let's make our AuthController a bit more useful and finish setting up Ueberauth and Guardian. Following along with their documentation, let's update our router:

defmodule PhoenixChat.Router do
use PhoenixChat.Web, :router
...
pipeline :api do
plug :accepts, ["json"]
end
pipeline :api_auth do
plug Guardian.Plug.VerifyHeader, realm: "Bearer"
plug Guardian.Plug.LoadResource
end
...
scope "/api", PhoenixChat do
pipe_through :api
resources "/users", UserController, except: [:show, :index, :new, :edit]
end
scope "/auth", PhoenixChat do
pipe_through [:api, :api_auth]
post "/:identity/callback", AuthController, :callback
end
end

In addition to creating an "/auth" scope, we created a new pipeline. Our new pipeline takes care to verify our Authorization header and load the resource using our serializer. We learned about the serializer when we configured Guardian, so let's discuss the authorization header.

Under-the-hood Guardian relies on an HTTP header, Authorization, to pass the JSON web token between the frontend and the backend. If you don't know what an authorization header is, it will become abundantly clear later on when we head back over to the frontend to make a call with an authorization header.

Now we need to implement the callback function we specified. Open up our AuthController and change it to include our callback/2 function. We can also get rid of the test function.

defmodule PhoenixChat.AuthController do
use PhoenixChat.Web, :controller
alias PhoenixChat.{ErrorView, UserView, User, AuthController}
plug Ueberauth
def callback(%{assigns: %{ueberauth_auth: auth}} = conn, _params) do
result = with {:ok, user} <- user_from_auth(auth),
:ok <- validate_pass(user.encrypted_password, auth.credentials.other.password),
do: signin_user(conn, user)
case result do
{:ok, user, token} ->
conn
|> put_status(:created)
|> render(UserView, "show.json", user: user, token: token)
{:error, reason} ->
conn
|> put_status(:bad_request)
|> render(ErrorView, "error.json", error: reason)
end
end
end

If we read down the function, what we're doing is: get the user from Ueberauth, validate the password, and sign in the user. If it's successful we'll render the user view along with our JSON web token. In the event of an error, we'll show the error view instead.

Let's implement the individual functions that make up our callback, we'll start with user_from_auth/1. For this function we need to lookup a user by the email address provided by Ueberauth. Add the following function to web/controller/auth_controller.ex, below the callback.

...
defp user_from_auth(auth) do
result = Repo.get_by(User, email: auth.info.email)
case result do
nil -> {:error, %{"email" => ["invalid email"]}}
user -> {:ok, user}
end
end

The next step in our authentication process is validating the password. We'll use pattern matching in our validate_pass/2 function to handle missing or blank passwords and Comeonin to compare the clear text password and the one stored in the database. To handle the comparison we'll rely on Comeonin and the Bcrypt module.

Bcrypt is the hashing algorithm we used in our registration_changeset/2 to compute our hashed password. The code below is what we should end up with.

...
defp validate_pass(_encrypted, password) when password in [nil, ""] do
{:error, "password required"}
end
defp validate_pass(encrypted, password) do
if Comeonin.Bcrypt.checkpw(password, encrypted) do
:ok
else
{:error, "invalid password"}
end
end

Lastly, we need to sign in so we can retrieve the user and JSON web token:

...
defp signin_user(conn, user) do
token = conn
|> Guardian.Plug.api_sign_in(user)
|> Guardian.Plug.current_token
{:ok, user, token}
end

That's it for the controller but there's still one step left: updating our user view to support the JSON web token. We can start by creating a new function similar to "user.json" but including our token. Then we can use pattern matching in "show.json" to render the JSON with or without the JWT token.

With all the pieces together, this is how our view should appear:

defmodule PhoenixChat.UserView do
use PhoenixChat.Web, :view
alias PhoenixChat.{UserView}
def render("index.json", %{users: users}) do
%{data: render_many(users, UserView, "user.json")}
end
def render("show.json", %{user: user, token: token}) do
%{data: render_one(user, UserView, "user_token.json", token: token)}
end
def render("show.json", %{user: user}) do
%{data: render_one(user, UserView, "user.json")}
end
def render("user.json", %{user: user}) do
%{email: user.email,
id: user.id,
username: user.username}
end
def render("user_token.json", %{user: user, token: token}) do
%{email: user.email,
id: user.id,
token: token,
username: user.username}
end
end

One thing our frontend application will need to know, is who current user is. To facilate this, let's build an endpoint to return the user given a JSON web token. This will be our "/me" endpoint, let's go ahead and add the endpoint to the router:

...
scope "/auth", PhoenixChat do
pipe_through [:api, :api_auth]
get "/me", AuthController, :me
post "/:identity/callback", AuthController, :callback
delete "/signout", AuthController, :delete
end
...

Now we can go back to our AuthController and implement our me function. For now all we want our endpoint to do is retrieve the currently logged in user and return their info to us. If they're not logged in, an HTTP error code will do. To do this, we're going to introduce a new Guardian plug: EnsureAuthenicated.

With EnsureAuthenticated, Guardian will check to see whether our incoming HTTP request contains our Authentication header. In the event that it does not, Guardian will take care of returning the appropriate error code and won't run any other functions in the module. The first step is to add the plug to the top of our controller:

defmodule PhoenixChat.AuthController do
use PhoenixChat.Web, :controller
alias PhoenixChat.{ErrorView, UserView, User, AuthController}
plug Ueberauth
plug Guardian.Plug.EnsureAuthenticated, [handler: AuthController] when action in [:delete, :me]
...
end

By now we should be somewhat familiar with what this does but just in case, let's go over it. Here we are adding a new plug to our request pipeline, EnsureAuthentication, passing a set of options (namely the error handler), and lastly we use a guard to apply the plug only for requests to our /me or /signout routes. This is because (obviously) we don't want to ensure a user is authenticated before that user can login.

To get everything working we only need to implement our me function now. Since we know EnsureAuthenticated will take care of logged out users, our method is pretty simple. We need to retrieve the current user and return them using the UserView. Add the following to our auth_controller.

...
def me(conn, _params) do
user = Guardian.Plug.current_resource(conn)
render(conn, UserView, "show.json", user: user)
end
...

We're not quite done. According to the Guardian docs for EnsureAuthenticated, we will need to add another function in the event a user is not authenticated. From the docs:

Looks for a previously verified token. If one is found, continues, otherwise it will call the :unauthenticated function of your handler.

While we're at it, let's also add an :unauthorized function in case we want to use the EnsurePermissions plug in the future.

...
def unauthenticated(conn, _params) do
conn
|> put_status(:unauthorized)
|> render(ErrorView, "error.json", errors: %{"account" => ["insufficient privilege"]})
end
def unauthorized(conn, _params) do
conn
|> put_status(:forbidden)
|> render(ErrorView, "error.json", error: %{"account" => ["unauthorized"]})
end

It's probably worthwhile to at least skim the rest of the Guardian docs so you know about some of the functionality. Knowing what is available and what is required will help a lot when debugging.

Automatic login on signup

Now that we can sign a user up and login independently, let's automatically log a user in upon signup. This is actually really simple. Since "login" really just means returning a valid token to a user, we can generate a token after an account has successfully been created and pass that along to the user. We only have to change two lines of code.

def create(conn, %{"user" => user_params}) do
changeset = User.registration_changeset(%User{}, user_params)
case Repo.insert(changeset) do
{:ok, user} ->
{:ok, token, _claims} = Guardian.encode_and_sign(user, :token)
conn
|> put_status(:created)
|> render("show.json", user: user, token: token)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render(PhoenixChat.ChangesetView, "error.json", changeset: changeset)
end
end

Now we have everything we need to register for an account and sign-in. Let's head back to the frontend to connect it.

Previous: Login and Authentication: Part 1Next: Move Logic to Redux