In this example app, I’ll cover how to set up Devise for authentication, and specify access control for your object using the logged-in user. To do this, you’ll want to set up a new app. This app is also very simple. It will contain only two tables: Users and Widgets.
A User has_many
:widgets, and a Widget belongs_to
Authentication, Authorization, and Access Control
Before we begin, let’s make sure we understand some basic web app terminology.
Authentication — The process where the computer (website) makes sure you are who you say you are.
Authorization — The idea that the user is allowed to access this website at all, or this part of the website.
Access Control — The idea that specific objects (like, objects in your database) are granted access (reading/writing) to some people and not to others.
Although these 3 terms of often confused, specifically because when we discuss these concepts in app development they are commingled, they have three distinct meanings.
Authentication is typically what we mean when we say “login.” By verifying the user’s username & password, we know that they are who they say they are. (At least, that they have the correct password.)
Authorization is often best thought of as a “public” part of your website which has no authorization (because any anonymous user can load the content) vs. an admin area where only admins are authorized to look at that part of the website.
If I have access to a part of the website, then the question becomes which objects I can access. In this example, users will log-in and create widgets. Another user, which we will simulate in an incognito window, will login and the 2nd user will not be able to see the 1st user’s widgets. The fact that the 1st and 2nd users can see only their own widgets and not each others is called access control.
rails new WidgetsApp --database=postgres
(Please note that the currently released Devise is not compatible with the pre-release Rails 7 version. If you have Rails 7 installed, you will need to create a Rails 6.1 app using
rails _184.108.40.206_ new WidgetsApp --database=postgres)
Now go through all Steps 1-9 in the Getting Started above, except Step 8 (Enum support), which we will not need for this example. After you install Devise in Step 9, there’s one final step that the setup docs leave out: You have to actually create a user and tell devise to know how to log that user in.
Remember, you’ve just run this command:
rails generate devise:install (The last command in the Setup). That’s the Devise installer. Now you must create a user and also tell Devise to attach its fields (several fields are attached by default) to your user object. You can use any name for “user” you like— account, person, persona, customer, etc. This will be the primary way people will log-in, so think about the mental model of where you want your authentication to be.
Most apps use “user”; I often write my apps using the word “account.” In this example, I will use User.