The Depot Application

The Depot Application

11.3 Iteration F3: Limiting Access 11.1 Iteration F1: Adding Users

11.2 Iteration F2: Logging in

rails generate controller admin login logout index
      create  app/controllers/admin_controller.rb
       route  get "admin/index"
       route  get "admin/logout"
       route  get "admin/login"
      invoke  erb
      create    app/views/admin
      create    app/views/admin/login.html.erb
      create    app/views/admin/logout.html.erb
      create    app/views/admin/index.html.erb
      invoke  test_unit
      create    test/functional/admin_controller_test.rb
      invoke  helper
      create    app/helpers/admin_helper.rb
      invoke    test_unit
      create      test/unit/helpers/admin_helper_test.rb
edit app/controllers/admin_controller.rb
class AdminController < ApplicationController
 
  # just display the form and wait for user to
  # enter a name and password
  def login
    if request.post?
      user = User.authenticate(params[:name], params[:password])
      if user
        session[:user_id] = user.id
        redirect_to(:action => "index")
      else
        flash.now[:notice] = "Invalid user/password combination"
      end
    end
  end
 
  def logout
    session[:user_id] = nil
    flash[:notice] = "Logged out"
    redirect_to(:action => "login")
  end
 
  def index
    @total_orders = Order.count
  end
end
edit app/views/admin/login.html.erb
<div class="depot-form">
  <%= form_tag do %>
    <fieldset>
      <legend>Please Log In</legend>
 
      <div>
        <label for="name">Name:</label>
        <%= text_field_tag :name, params[:name] %>
      </div>
 
      <div>
        <label for="password">Password:</label>
        <%= password_field_tag :password, params[:password] %>
      </div>
  
      <div>
        <%= submit_tag "Login" %>
      </div>
    </fieldset>
  <% end %>
</div>
edit app/views/admin/index.html.erb
<h1>Welcome</h1>
 
It's <%= Time.now %>
We have <%= pluralize(@total_orders, "order") %>.
get /admin/login
Please Log In
post /admin/login
You are being redirected.
get http://localhost:3000/admin/index

Welcome

It's Fri Jun 29 15:13:05 -0400 2012 We have 1 order.

11.3 Iteration F3: Limiting Access 11.1 Iteration F1: Adding Users