Search⌘ K
AI Features

Adding Users

Explore how to add user authentication in Rails 6 by creating models with secure password digests. Understand how to validate passwords, manage users through controllers and views, and restrict access to administrative functions to ensure application security.

Let’s start by creating a model and database table to hold our administrators’ usernames and passwords. Rather than store passwords in plain text, we’ll store a digest hash value of the password. By doing so, we ensure that even if our database is compromised, the hash won’t reveal the original password. We will use the forms:

depot> bin/rails generate scaffold User name:string password:digest

We declare the password as a digest type, which is another one of the nice extra touches that Rails provide. Now run the migration as usual:

depot> bin/rails db:migrate

A live terminal

You can run the above commands by using the following terminal.

Terminal 1
Terminal
Loading...

Next, we have to flesh out the user model:

Ruby
class User < ApplicationRecord
validates :name, presence: true, uniqueness: true
has_secure_password
end

We check that the name is present and unique, meaning that no two users can have the same name in the database.

Then there’s the mysterious has_secure_password(). ...