Dev Series – Phoenix part 2 – Authentication using pow
Published at June 27, 2021
Authentication is a crucial part of any web application. In this tutorial, I will guide you through setting up user authentication using Pow, a powerful library for user authentication.
ADDING HEX PACKAGE?
Pow is a robust, modular, and extendable authentication and user management solution for Phoenix and Plug-based apps.
Pow also comes with handy view templates for signing up and logging in users. This makes it super easy to track who’s logged in, which will be really helpful when we start organizing the exercises each user creates.
First, add pow to the list of your dependencies on mix.exs:
defp deps do
[
# your other dependencies
{:pow, "~> 1.0.22"}
]
end
To install our newly added dependencies we need to run:
$ mix deps.get
Pow provide us with a script that help us set up your user schema, migrations, and necessary configurations.
$ mix pow.install
Next, we need to run the generated migrations:
$ mix setup
Once done we can now visit localhost:4000/registration/new:
Awesome! After signing up It seems we do not have an indicator that we are logged in. Let’s update the navbar to include signed in user:
<nav role="navigation">
<ul>
<% current_user = Pow.Plug.current_user(@conn) %>
<%= if current_user do %>
<li>
<%= current_user.email %>
</li>
<% else %>
<li>
<%= link "Sign In", to: Routes.pow_session_path(@conn, :new), class: "btn btn-primary" %>
</li>
<li>
<%= link "Sign Up", to: Routes.pow_registration_path(@conn, :new), class: "btn btn-secondary" %>
</li>
<% end %>
</ul>
</nav>
Let’s also add a way for a user to logout:
# ...other code for signed in user
<%= link "Sign Out", to: Routes.pow_session_path(@conn, :delete), method: :delete, class: "btn btn-secondary" %>
# ... else code for not signed in user
Cool! Let’s try to sign out so that we can see the Sign In and Sign Up link:
Summary
We have successfully set up authentication in your Phoenix 1.5 application using Pow package. We also updated our navbar so that we can easily login and logout to our app.
In our next blog, we’ll explore Phoenix generators and how they can streamline the setup of our application. We’ll also cover how to use them to generate CRUD operations for exercises.
Keep on Coding!