9.1 sessions

阅读更多

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:

Sign in

<%= form_for(:session, :url => sessions_path) do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.submit "Sign in" %>
<% end %>

New user? <%= link_to "Sign up now!", signup_path %>

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| %>
here, we tell rails the resources name and the url.

now you will get this information in the param being submitted:

params[:session]
params[:session][:email]
params[:session][:password]

next we will handle this submission.


 

你可能感兴趣的:(9.1 sessions)