How To Create Auth by Connecting Devise into Your ROR Project

Written by mariosknl | Published 2020/07/01
Tech Story Tags: ruby-on-rails | microverse | user-authentication | project | backend | ruby | rails | programming

TLDR Ruby on Ruby on Rails is designed under the MVC principles - Model View Controllers. Devise is a flexible authentication solution for Ruby on ROR projects. The solution is called devise and it is available in Ruby on Rack-Rack. The easiest way to use it is to create a Ruby-on-Racks app with the gem. The gem is a gem for anything you can think of and it can help you create a user-authentication solution for your application. For example, create a class called DeviseRegistrations and use it to authenticate users.via the TL;DR App

As a student of Microverse, I’ve reached the point where Rails’ framework was introduced to me. It appeared to me with the best omens on its hands. Ruby on Rails is a starting point for many start-ups because all of them got blinded by its beauty and simplicity. I have to admit that I felt intimidated for a while. Surely I can't say we are the best friends now but things started to make sense. Ruby on Rails is designed under the MVC principles - Model View Controllers.
Devise is a flexible authentication solution for Rails

As things started to get more advanced, after 4 months of coding in Microverse, the time has come to create something real. But wait, how do they include user functionality in applications? Where are the credentials being kept and how can I make it happen without re-inventing the wheel.
Those types of questions kept spinning in my mind in the beginning. Fellow students advised me to calm down and spend time on documentation. Rails' world is surrounded by libraries called gems. There is a gem for anything you can think of. Without wasting more time let's see Devise magic in action. Let's create a Rails app together.
rails new devise_gem
rails g scaffold Post post:text
rails db:migrate 
rails s 
  1. Starting from the top, we initialize a new rails app called devise_gem.
  2. We use the scaffold command to create all of the necessary files for us without having to type all these on our own. Post is going to be our model. You can replace it with whatever you want. Text is the column type our model is in the database. 
  3. Migrate the database for our application.
  4. Run the server. Check the browser and confirm that everything working well. You should see the welcome page of Rails in the localhost:3000
Application’s basic structure has been created for us. That’s great right? 
update routes => config/routes.rb - root 'posts#index'
restart the server always after modifying routes files or controllers files
Visit Gemfile in the root folder of your application
Many gems-libraries are already there for you by default. We won't deal with these at the moment.  
Add devise gem in the general dependencies(this means anywhere outside of groups. Yes, you can put it between the comments. You can also leave your comment above in case you forget what this is. 
[EXTRA TIP]: Visit rubygems.org. It will be your friend from now on.
gem ‘devise’
Back in the terminal and bundle install to get the devise dependencies in your project.
On this step, we need to set up devise for our application. It simple but make sure you won't miss any step while doing that. (Did that a few times)
rails g devise:install


Devise installation will ask you to follow some extra steps. Please, execute it one by one. Remember that we have already set our route file and even though it's not as devise tells us, don't get confused, because devise gives us an example. This mean there are only 3 steps left.
Lastly, after running all the commands, we have to do one more! Don't yell at me now with all your complaints. All of them are necessary for different reasons. 
rails g devise User
That was all. You have everything that you need in order to have your User functionality in your application. From now on, everything has to do with the way you want to use it. I will show you some basic things but feel free to test it yourself.
visit app/controllers/posts_controller.rb

Inside the class and in the top let's add one line: 
before_action :authenticate_user!, except: [:index, :show]
This tells to our application that
un-authenticated
users -meaning the ones that haven’t been registered in our database- can only visit our index and show page.
By default,
devise gem has only email and password as fields
. If we want to have other fields as well - which we will do now - we need to do some things. 
Create RegistrationsController - (app/controllers/registrations_controller.rb)
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
 params.require(:user).permit(:name, :username, :email,:password, :password_confirmation)
end
def account_update_params
 params.require(:user).permit(:name, :username, :email,:password, :password_confirmation, :current_password)
end
Then, we have to update our routes with our new controller (
config/routes.rb
)
devise_for :users, controllers => { registrations: 'registrations' }
Next,  let’s create a migration file with the new fields we want to request from the user. Up to now, they weren't in our database and we want to include them in case you didn't get it yet
rails g migration AddFieldsToUser - CamelCase
rails g migration add_fields_to_user - snake_case
Both of them do exactly the same job. Choose whatever suits better for you but be careful while typing. Everything matters on Rails. 
Check migration file cause we want to include some lines of code there.Inside the change method:
add_column :users, :name, :string
add_column :users, :username, :string
add_index :users, :username, unique: true
You may have noticed that we haven't done anything with our database since we generated our scaffold Post model. Until now, we are still dealing with the user setup and devise configuration itself. I'm sure that you are thinking that all these were too much but surely it's worth our time because if we wanted to do that all these methods on our own, we would have spent double time
Time for our migrations now:
rails db:migrate
From now on, we have new fields in our table, and we need to update our views located in the devise folder.
app/views/devise/registrations/new.html.erb.

<div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true %>
  </div>


  <div class=“field">
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </div>
Create associations between controller && model
app/model/user.rb
 User model
has_many :posts
# app/model/post.rb
 Post Model
belongs_to :user

rails g (generate) migration AddUserIdToPosts user_id:integer
Migration file should look like this:
def change
    add_column :posts, :user_id, :integer
  end
After that being done, we have to configure our post_controller to work with Devise.
def new
 @post = current_user.posts.build
end
def create
 @post = current_user.posts.build(post_params)
end
Devise provides us with lots of built-in methods like current_user, is_admin? etc. You can find all of the in the Devise Github repository. (https://github.com/heartcombo/devise)
I know that I've said that again but keep in mind that it's always a good idea whenever you are making changes either to the controller or the routes to restart the server in your terminal to be sure that all of the changes are now loaded in the application. If you try now to create a new Post as this is our root page you will arrive at the login page. Of course, we haven't created any user up to now. Let's do that if we want to enter our app and create some posts!
Basic things are introduced in this article. I was fascinated by the simplicity and how logical are things in Ruby thus in Ruby on Rails. There were cases where I felt like writing an essay to someone. If you haven't tried it out yet I strongly recommend you to spend some time with it. 
Last but not least, completely unrelated with the topic of this article but I thought it would be a good idea to add it as a conclusion. Remember that our minds love to play games with us. We want to learn everything at once. We are comparing ourselves with other people. We are feeling intimidating. Imposter Syndrome has huge impact in our life as developers. Rails may be outdated but if you are good at it, you will surely be of need. Choose your path and stay focused.
Be healthy both physically and mentally!
Huge Credit to all my fellow students in Microverse and of course the school itself for giving as the chance to be involved in this great tech community.
Thank you for spending time reading! 
Photo credits: Zane Lee

Published by HackerNoon on 2020/07/01