Skip to content

Commit

Permalink
Working user signin
Browse files Browse the repository at this point in the history
  • Loading branch information
mhartl committed Aug 26, 2010
1 parent b04e0e7 commit 798463f
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 4 deletions.
1 change: 1 addition & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
end
3 changes: 2 additions & 1 deletion app/controllers/sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ def create
@title = "Sign in"
render 'new'
else
# Handle successful signin.
sign_in user
redirect_to user
end
end

Expand Down
28 changes: 28 additions & 0 deletions app/helpers/sessions_helper.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,30 @@
module SessionsHelper

def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
current_user = user
end

def current_user=(user)
@current_user = user
end

def current_user
@current_user ||= user_from_remember_token
end

def signed_in?
!current_user.nil?
end

private

def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end

def remember_token
cookies.signed[:remember_token] || [nil, nil]
end
end

11 changes: 8 additions & 3 deletions app/models/user.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# == Schema Information
# Schema version: 20100822204528
# Schema version: 20100822233125
#
# Table name: users
#
Expand All @@ -9,6 +9,7 @@
# created_at :datetime
# updated_at :datetime
# encrypted_password :string(255)
# salt :string(255)
#

class User < ActiveRecord::Base
Expand All @@ -35,8 +36,12 @@ def has_password?(submitted_password)
class << self
def authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
(user && user.has_password?(submitted_password)) ? user : nil
end

def authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
end

Expand Down
19 changes: 19 additions & 0 deletions spec/controllers/sessions_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,24 @@
flash.now[:error].should =~ /invalid/i
end
end

describe "success" do

before(:each) do
@user = Factory(:user)
@attr = { :email => @user.email, :password => @user.password }
end

it "should sign the user in" do
post :create, :session => @attr
controller.current_user.should == @user
controller.should be_signed_in
end

it "should redirect to the user show page" do
post :create, :session => @attr
response.should redirect_to(user_path(@user))
end
end
end
end

0 comments on commit 798463f

Please sign in to comment.