Rails Authorization With Devise
Authorization could be hard, but it doesn’t have to be. Part of the beauty of Rails is the ‘magic’ that’s available for us to use as developers. Although it’s absolutely possible to wire up your own authorization logic from scratch and there are most certainly use cases where that would be a better fit, the devise gem has a lot of functionality built in that would take a lot longer than basic auth. Another huge benefit is the popularity of this gem, with over 21k stars at the time of this writing, with a lot of security professionals contributing to the project.
Here’s a rundown of features offered to you by the gem from the devise gem wiki.
- Database Authenticatable: hashes and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
- Omniauthable: adds OmniAuth (https://github.com/omniauth/omniauth) support.
- Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
- Recoverable: resets the user password and sends reset instructions.
- Registerable: handles signing up users through a registration process, also allowing them to edit and destroy their account.
- Rememberable: manages generating and clearing a token for remembering the user from a saved cookie.
- Trackable: tracks sign in count, timestamps and IP address.
- Timeoutable: expires sessions that have not been active in a specified period of time.
- Validatable: provides validations of email and password. It’s optional and can be customized, so you’re able to define your own validations.
- Lockable: locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.
Lets scaffold a new Rails project and run through what’s provided to us out of the box. Add the gem to your Gemfile and run bundle.
Then you have to run the devise generator.
rails generate devise:install
From here, if you already have a User model, devise will append it’s functionality to your existing model. Meanwhile, if you haven’t created the model yet, devise will generate a User model for you. The command is the same in either scenario.
rails generate devise User
You’ll also want to migrate the model devise created for you.
Here’s what the schema looks like. Keep in mind, this is all generated by devise.
For configuring the functionality mentioned at the top of the post, such as making users invitable or passwords recoverable, etc. You’ll need to first check the devise.rb config file in your apps initializers. The instructions there are very in-depth.
At this point auth is integrated. You have a lot of routes that are generated for you for all kinds of actions. Sign up, login, edit, delete, recover a password, etc.
The basic templates for all of these actions are built as well.
Easy, quick and painless. Rails ‘magic’!