The Depot Application

The Depot Application

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

11.2 Iteration F2: Logging in

ruby script/generate controller admin login logout index
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/admin
      exists  test/functional/
      exists  test/unit/helpers/
      create  app/controllers/admin_controller.rb
      create  test/functional/admin_controller_test.rb
      create  app/helpers/admin_helper.rb
      create  test/unit/helpers/admin_helper_test.rb
      create  app/views/admin/login.html.erb
      create  app/views/admin/logout.html.erb
      create  app/views/admin/index.html.erb

Restart the server.

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

Welcome

It's 2010-08-27 18:28:02 -0400 We have 1 order.

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