Basic Authentication using BCrypt

Ruby on Rails, 2015-06-17 00:11:17 UTC

1. Include BCrypt in Gemfile

gem 'bcrypt', '~> 3.1.7'



2. Model

$ rails g model Member email:string password:string



3. Route

get 'auth/sign_up', to: 'auth#sign_up'
post 'auth/sign_up/post', to: 'auth#sign_up_post'
get 'auth/sign_in', to: 'auth#sign_in'
post 'auth/sign_in/post', to: 'auth#sign_in_post'
get 'auth/sign_out', to: 'auth#sign_out'



4. View for sign up

<%= form_for(@member, url: "/auth/sign_up/post") do |f| %>
   <% if @member.errors.any? %>
    <div id="errors" class="alert alert-danger">
      <h2 class="mt5 mb5"><%= pluralize(@member.errors.count, "error") %> prevent this post from saving</h2>
      <ul>
        <% @member.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  
  <!-- email -->
  <%= f.text_field :email, html_options={ class: "form-control" } %>

  <!-- password -->
  <%= f.password_field :password, autocomplete: "off", class: "form-control" %>

  <input type="submit" value="Sign Up" >
<% end %>




5. View Sign in

<%= form_for(@member, url: "/auth/sign_in/post") do |f| %>
   
  <!-- email -->
  <%= f.text_field :email, html_options={ class: "form-control" } %>

  <!-- password -->
  <%= f.password_field :password, autocomplete: "off", class: "form-control" %>

  <input type="submit" value="Sign in" >
<% end %>




6. Controller

class AuthController < ApplicationController

  def sign_up
    @member = Member.new
  end
  
  def sign_up_post
    @email = params[:member][:email]
    @password = params[:member][:password]
    @pass = BCrypt::Password.create(@password)
    @mem = Member.new 
    @mem.email = @email
    @mem.password = @pass
    @mem.save 
    #render inline: @pass.to_s
    render inline: "success"
  end
  
  def sign_in
    @member = Member.new
  end
  
  def sign_in_post
    @email = params[:member][:email]
    @password = params[:member][:password]
    
    @user = Member.where(email: @email).take
    
    @user_hash = BCrypt::Password.new(@user.password)
    
    if @user_hash == @password
session[:member_id] = @user.id render inline: "match" else render inline: "not match" end end def sign_out reset_session # reset whole session # session.delete(:member_id) # to reset single session end end

Share: