DEV Community

loading...
Cover image for Building Ruby on Rails app

Building Ruby on Rails app

ivanadokic profile image Ivana ・4 min read

Ruby on Rails app with Authorization and Authentication

Ruby on Rails is the most popular server-side web application framework that is written in Ruby (open-source programming language). It's powerful and magical! Let's work through what makes it powerful and start that initial setup and learn more about Authorization and Authentication security concepts.

Step 1.

Create a new store Rails application skipping a test:

$ rails new store --skip-test-unit
$ cd shop
$ rake db:create
Enter fullscreen mode Exit fullscreen mode

Step 2.

Add Bootstrap and styles
Let’s add a ‘bootstrap-sass’ gem to our Gemfile:

gem 'bootstrap-sass', '~> 3.3', '>= 3.3.6'
Enter fullscreen mode Exit fullscreen mode

and bundle everything with:

bundle install
Enter fullscreen mode Exit fullscreen mode

Add some styles to our store application, rename the application.css to the application.scss under the app/assets/stylesheets to be able to use imports. Add these lines after the manifest:

@import "bootstrap";
@import "bootstrap-sprockets";

#main-container {
  position: relative;
  padding-top: 50px;
  padding-bottom: 50px;
}

.product-block {
  width: 750px;
}

.btn {
  font-family: Impact, fantasy;
}

body {
  background: #f19797;
  font-family: Impact, fantasy;
}

th {
  background-color: #333333;
  color: white;
}

td {
  background-color: #f8f2f2;
  color: white;
}

Enter fullscreen mode Exit fullscreen mode

And add the following into assets/javascript/application.js file, this line:

require("bootstrap")
Enter fullscreen mode Exit fullscreen mode

Step 3. Edit views

Replace the content of your views/layouts/application.html.erb file with this:

<!DOCTYPE html>
<html>
  <head>
    <title>Store</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
  <nav class="navbar navbar-inverse navbar-top navbar-fixed-top">
    <div class="container-fluid">
      <div class="container">
        <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">Store app</a>
    </div>
      </div>
    </div>
  </nav>
  <div id="main-container" class="container">
    <%= yield %>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And add those 2 methods(bootstrap_classs and flash_messages) to app/helpers/application_helper.rb which will be used to display messages:

module ApplicationHelper
  def boostrap_class(alert)
    { success: 'alert-success', error: 'alert-danger', notice: 'alert-success', warning: 'alert-warning',
      danger: 'alert-danger', alert: 'alert-danger' }[alert.to_sym]
  end

  def flash_messages(_opts = {})
    flash.each do |msg_type, message|
      concat(content_tag(:div, message, class: "alert #{boostrap_class(msg_type.to_sym)} fade in") do
        concat(content_tag(:button, id: "close-button", class: "close", type: :button, data: { dismiss: 'alert' }, "aria-label" => :Close) do
          concat content_tag(:span, "&times;".html_safe, "aria-hidden" => true)
        end)
        concat message
      end)
    end
    nil
  end
end
Enter fullscreen mode Exit fullscreen mode

Step 5. Add welcome page

Create dashboard_controller.rb file under app/controllers folder and add the following code:

class DashboardController < ApplicationController
  def index
  end
end
Enter fullscreen mode Exit fullscreen mode

Create a app/views/index.html.erb file and make it looks like this:

<%= flash_messages %>
<div class="block">
    <header class="header-group">
        <h2>Welcome to Rails Authentication and Authorization!</h2>
    </header>
    <div class="row">
        <div class="col-md-12">
        </div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

The next step would be to clear and add the following code to routes.rb file under the config folder:

Rails.application.routes.draw do
  root 'dashboard#index'
end
Enter fullscreen mode Exit fullscreen mode

Step 5. Start an application

Run rails s command and got to http://localhost:3000 browser, it should look like this:
Alt Text

There are few more steps such as creating a product scaffold, add bootstrap to product files, and add products links to the navigation bar and when it's all done if you go to http://localhost:3000/products/new you will see:
Alt Text

Step 6. Add authentication and authorization

Let’s move on to a very important part – authentication and authorization.

The next step will be to add authentication and authorization, but I would like first to deep dive into this concept which is very often misunderstood.

Breaking Down the Authentication and Authorization Problem

It's important to have a general understanding of their meaning. We can divide the "who can see what" problem into four smaller security concepts:
Identification Who you claim to be
Authentication Validation that you are you who you claim to be
Access Policy Association of roles based on your identity, what given roles are allowed to do
Authorization Mechanisms to enforce the Access Policy

Examples of Authentication and Authorization FLOWS

If you were to enter your local bank branch, here's how these concepts would apply.

Alt Text

First - Identification

Assert who you are by stating your name and showing an ID.

Second - Authentication

Verify your identity claim by verifying you possess a secret that only the "real you" would know and which has been established prior to this moment like a password or matching signature.

Third - Access Policy

Interlude At this point the bank knows that they are dealing with a verified entity. From the perspective of their system, all verified entities act with respect to roles. At the point of Authentication, the verified entity's collection of roles is also retrieved. This is the point where the association of roles based on your identity was given.

Fourth - Authorization

You then proceed to withdraw enough money. At this point, the Access Policy ("As an owner of an account, the owner is permitted to withdraw money from that account provided") is implemented in an activity known as Authorization. Since your authentication step validated you in the role of owner, this transaction proceeds.

If you try again, your roles owner and customer have a "NO ACCESS" Access Policy as relates to the bank's vault and you will not be Authorized and cannot enter the bank vault.

Commonly used Gems for authentications are: Devise, OmniAuth, Authlogic AND for authorization: CanCanCan, Pundit, more gem options can be found in Ruby Toolbox.

This FLOW applies to users of the store app. We will define its access policy and verify the identity of users.

What’s next?

The next step will be to add authentication and authorization using some of the popular rails Gems.

To connect with me please check my Github, LinkedIn or Twitter.

Thank you for reading!

Discussion (0)

Forem Open with the Forem app