a session is a semi-permanent connection between 2 computers, such as client running browser & server running rails.
there are several model for session behaviors:
1. forget session on browser close
2. use a optional "remember me" checkbox for persistent sessions.
3. remember the session forever until user explicitly sign out.
4. expire session after a certain amount of time.(this way is especially good on site containing sensitive info, like bank)
in this chapter, we will use 3, clear the session until user explicitly sign out.
it is convenient to model sessions as RESTful resources:
we will have a signin page for new session.
signin will create a session.
signout will destroy a session.
so we need a sessions controller, with new, create, destroy actions.
in users controller, we store data into database through user model, to persist data.
here for session, the data will be store in cookie, which is small piece of text places on browser.
so to do signin, we will build the cookie based authentication machinery.
1. sessions controller.
a.
rails g controller Sessions new
b.
rm -rf spec/views
rm -rf spec/helpers
c. let's create a new file sessions_controller_spec.rb to test sessions controller:
describe SessionsController do render_views describe "GET 'new'" do it "should be successful" do get 'new' response.should be_success end it "should should have the right title" do get 'new' response.should have_selector("title", :content => "Sign in") end end end
to get this work, we need to add routes.
SampleApp::Application.routes.draw do resources :users resources :sessions, :only => [:new, :create, :destroy] match '/signup', :to => 'users#new' match '/signin', :to => 'sessions#new' match '/signout', :to => 'sessions#destroy' . end
a. resources :session and take a second argument, :only, to indicate which actions it include.
b. now, we have three named routes:
signin_path ========> sessions#new
signout_path ========> sessions#destroy
sessions_path =========>sessions#create
2. the next step is the sign in form:
<h1>Sign in</h1> <%= form_for(:session, :url => sessions_path) do |f| %> <div class="field"> <%= f.label :email %><br /> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :password %><br /> <%= f.password_field :password %> </div> <div class="actions"> <%= f.submit "Sign in" %> </div> <% end %> <p>New user? <%= link_to "Sign up now!", signup_path %></p>
you may remember we use
form_for @user do |f|
in prior chapter, but here, we don't session model, so we have to give more info:
<%= form_for(:session, :url => sessions_path) do |f| %>