Ruby on Rails: Authorization
Devise gem is a beautiful gem. Inside your gemfile, require:
gem 'devise', '~> 4.7', '>= 4.7.1'
Or which ever version is the most updated. Run bundle install
to grab the library and any dependencies for your rails project.Next, you need to run the generator:
rails generate devise:install
Open the devise.rb
file under the initializers
folder. You can configure the options there for email requirement in regex, password length, and other options for user inputs. Change the config.mailer_sender
to the email you wish others to receive emails from as a response. You’ll need to set up the default URL options for the Devise mailer in each environment. In the config/environments/development.rb
file, add the following code at the end of the previous code inside the file:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
The generator will install an initializer which describes ALL of Devise’s configuration options. If you are running this on a live site, localhost
should be changed to your_site.com
. Your terminal will have more instructions for you to follow, such as flash messages and notifications. You can also generate views with devise for customization by running:
rails g devise:views
This will set up a set of files that you can use with devise. The main ones to be concerned about are registration and sessions. These are signup and sign in. Next you want to type in:
rails generate devise MODEL
But MODEL
is typically for user or admin. Run rails db:migrate
. Test this is running properly by going to localhost/3000/users/sign_up
. Personal preference for renaming the sign_up
page to register can be done inside of the routes file:
devise_for :users, path: '', path_names:{sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
To create a logout, add a logout button inside of the application.html.erb
file.
<%= link_to "Logout", destroy_user_session_path, method: :delete, class: style %>
That will give you a logout button every time, but if you want to have a more dynamic code where login/sign up shows when your logged out you can use the following code:
if current_user.is_a?(GuestUser)
<%=link_to "Register", new_user_registration_path =>
<%= link_to "Login", new_user_session_path %>
else
<%= link_to "Logout", destroy_user_session_path, method: :delete%>
end
There you have login and logout! There are many other things you can do to take advantage of devise, so do some experimenting!