Creating a simple API using Elixir/Phoenix (Part 4)

In the last article we fixed the unit tests and played a little bit with Postman. Now we’ll start applying validation for some fields of our model.

At first let’s encrypt the users passwords. For that we can use a hex package called comeonin. It uses bcrypt and will make the things easy for us.

Note: if you want to know more hex packages, feel free to explore a ton of them through the following link:

Phoenix have a specific file to register all dependencies and the respective versions. This file is mix.exs. To install comeonin we need to add it to application and deps lists.

After make the changes in this file, let’s install comeonin:

mix deps.get

The algorithm behind bcrypt was made purposefully slow to prevent brute force attacks. To keep our tests running fast, we need to config the test file at config/test.exs to turn down the encryption.
We just need to insert two lines at the end of test.exs.

That’s all for comeonin installation. Now let’s implement the validations for our model.

Testing the model

Time to make our model smarter! But before to implement is important to start with the unit tests.
Open the model test file and do the following changes:

As we know the test will break because we have nothing implemented yet. 
After created our tests, let’s implement what we expect it should do! Before to start, check the errors on running the tests:

mix test

Don’t worry about it. We’ll fixing all of them updating the user model according the gist bellow:

If we run the tests again, only the model tests will pass because we need to refactor our controller tests to fits in the model validations we added.

Before refactor the controller tests let’s take some notes:
1. We created a virtual field(password) that will not be stored in the database. Only the field ‘hashed_password’ will.

2. As we saw, the function encrypt password receive the virtual field password that will check if it is valid and pass the value to the hashed password and this last one will be encrypted.

Testing the controller

One important peace of code needs to be added in our controller:

changeset = User.signup_changeset(%User{}, user_params)

This line should replace the first line of the create function because we created this function in our model and without it we cannot follow the logic we implemented.

Finally let’s refactor our controller tests:

Note: in the user view, remove the password_hash field to make the tests pass and because is not recommended to show the password_hash in a JSON response.

So that’s it for now! In the part 5, I’ll cover some important details about passing data through the views before to start the session’s creation.

Let me know in the comments what did you think about this article or any important detail not covered in it you’d like to know more about.

Show your support

Clapping shows how much you appreciated Cristiano de Araujo’s story.