Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## fix_user_compat_with_mephisto.diff [diff]
- Index: test/unit/user_test.rb
- ===================================================================
- --- test/unit/user_test.rb (revision 1929)
- test/unit/user_test.rb (working copy)
- @@ -54,12 54,12 @@
- assert ! u.admin?
- end
- - def test_login_token
- - assert_nil users(:aaron).login_key
- - assert_nil users(:aaron).login_key_expires_at
- - users(:aaron).reset_login_key!
- - assert users(:aaron).login_key.length == 32
- - assert users(:aaron).login_key_expires_at < Time.now.utc 1.year 1.minute
- - assert users(:aaron).login_key_expires_at > Time.now.utc 1.year-1.minute
- def test_remember_token
- assert_nil users(:aaron).remember_token
- assert_nil users(:aaron).remember_token_expires_at
- users(:aaron).remember_me
- assert users(:aaron).remember_token.length == 40
- assert users(:aaron).remember_token_expires_at < Time.now.utc 2.weeks
- assert users(:aaron).remember_token_expires_at > Time.now.utc-1.minute
- end
- end
- Index: test/functional/forums_controller_test.rb
- ===================================================================
- --- test/functional/forums_controller_test.rb (revision 1929)
- test/functional/forums_controller_test.rb (working copy)
- @@ -14,16 14,16 @@
- end
- def test_remember_me_logs_into_home
- - @request.cookies['login_token'] = CGI::Cookie.new('login_token',"2;8305f94ab2b92f99137abbc235ee28e5")
- @request.cookies['auth_token'] = CGI::Cookie.new('auth_token',"265777ed4a11f9867382a1fbe2868c8a2bce37b2")
- get :index
- assert_equal 2, session[:user_id]
- end
- def test_remember_me_logs_in_when_login_required
- - users(:aaron).login_key="8305f94ab2b92f99137abbc235ee28e5"
- - users(:aaron).login_key_expires_at=Time.now.utc 1.week
- users(:aaron).remember_token="3c82fc7450acf8bc20a0c9f23bdb849cb13adf4e"
- users(:aaron).remember_token_expires_at=Time.now.utc 2.weeks
- users(:aaron).save!
- - @request.cookies['login_token'] = CGI::Cookie.new('login_token',"1;8305f94ab2b92f99137abbc235ee28e5")
- @request.cookies['auth_token'] = CGI::Cookie.new('auth_token',"3c82fc7450acf8bc20a0c9f23bdb849cb13adf4e")
- get :edit, :id => 1
- assert_equal 1, session[:user_id]
- end
- Index: test/functional/sessions_controller_test.rb
- ===================================================================
- --- test/functional/sessions_controller_test.rb (revision 1929)
- test/functional/sessions_controller_test.rb (working copy)
- @@ -25,22 25,22 @@
- post :create, :login => 'aaron', :password => 'testy', :remember_me => "1"
- users(:aaron).reload
- - assert cookies['login_token']
- - assert_equal("1;#{users(:aaron).login_key}", cookies['login_token'].first)
- - assert_not_nil users(:aaron).login_key
- - assert_not_nil users(:aaron).login_key_expires_at
- assert cookies['auth_token']
- assert_equal("#{users(:aaron).remember_token}", cookies['auth_token'].first)
- assert_not_nil users(:aaron).remember_token
- assert_not_nil users(:aaron).remember_token_expires_at
- #log off
- post :destroy
- - assert cookies['login_token'].empty?
- assert cookies['auth_token'].empty?
- # make sure it change if log in again
- sleep 1
- old = users(:aaron).clone
- post :create, :login => 'aaron', :password => 'testy', :remember_me => "1"
- users(:aaron).reload
- - assert_not_equal(old.login_key, users(:aaron).login_key)
- - assert_not_equal(old.login_key_expires_at, users(:aaron).login_key_expires_at)
- assert_not_equal(old.remember_token, users(:aaron).remember_token)
- assert_not_equal(old.remember_token_expires_at, users(:aaron).remember_token_expires_at)
- end
- def test_should_fail_login
- Index: test/fixtures/users.yml
- ===================================================================
- --- test/fixtures/users.yml (revision 1929)
- test/fixtures/users.yml (working copy)
- @@ -2,7 2,8 @@
- id: 1
- login: aaron
- email: aaron@email.com
- - password: testy
- crypted_password: f3b0ba77ac3e3196e5fc5ce82eb9ba276a64fa02 # testy
- salt: 0a0f0d417e897bba35e24ed7ad5ad48981eaf7fa
- created_at: <%= 5.days.ago.to_s :db %>
- posts_count: 2
- last_login_at: <%= 5.minutes.ago.to_s :db %>
- @@ -14,10 15,11 @@
- login: sam
- display_name: sam
- email: sam@email.com
- - password: testy
- crypted_password: 33b78c4246ee1e25f3c98597acf47a706ba9d374 # testy
- salt: fefa0dd004b8a840e1352a9d860c0349c61f682e
- created_at: <%= 4.days.ago.to_s :db %>
- posts_count: 2
- last_login_at: <%= 4.minutes.ago.to_s :db %>
- last_seen_at: <%= 4.minutes.ago.to_s :db %>
- - login_key: 8305f94ab2b92f99137abbc235ee28e5
- - login_key_expires_at: <%= Time.now.utc 1.week %>
- \ No newline at end of file
- remember_token: 265777ed4a11f9867382a1fbe2868c8a2bce37b2
- remember_token_expires_at: <%= Time.now.utc 2.weeks %>
- Index: app/models/user.rb
- ===================================================================
- --- app/models/user.rb (revision 1929)
- app/models/user.rb (working copy)
- @@ -1,26 1,9 @@
- -require 'md5'
- -
- -class User < ActiveRecord::Base
- class User < UserAuth
- has_many :moderatorships, :dependent => :destroy
- has_many :forums, :through => :moderatorships, :order => 'forums.name'
- has_many :posts
- - validates_presence_of :login, :email, :password
- - validates_uniqueness_of :login, :email, :case_sensitive => false
- - # names that start with #s really upset me for some reason
- - validates_format_of :login, :with => /^[a-zA-Z]{2}(?:\w )?$/
- - validates_length_of :login, :minimum => 2
- - # names that start with #s really upset me for some reason
- - validates_format_of :display_name, :with => /^[a-zA-Z]{2}(?:[.'\w ] )?$/
- - validates_uniqueness_of :display_name, :case_sensitive => false
- -
- - validates_confirmation_of :password, :on => :create
- - validates_length_of :password, :minimum => 5
- - before_validation { |u| u.display_name = u.login if u.display_name.blank? }
- - # first user becomes admin automatically
- - before_create { |u| u.admin = true if User.count == 0 }
- -
- attr_protected :admin, :posts_count, :login, :created_at, :updated_at, :last_login_at, :topics_count
- def self.currently_online
- @@ -28,16 11,7 @@
- User.find(user_ids)
- end
- - def reset_login_key!
- - self.login_key = MD5.md5(Time.now.to_s password rand(123456789).to_s).to_s
- - # this is not currently honored
- - self.login_key_expires_at = Time.now.utc 1.year
- - save!
- - login_key
- - end
- -
- def moderator_of?(forum)
- moderatorships.count(:all, :conditions => ['forum_id = ?', (forum.is_a?(Forum) ? forum.id : forum)]) == 1
- end
- -
- end
- Index: app/models/user_auth.rb
- ===================================================================
- --- app/models/user_auth.rb (revision 0)
- app/models/user_auth.rb (revision 0)
- @@ -0,0 1,77 @@
- require 'digest/sha1'
- class UserAuth < ActiveRecord::Base
- set_table_name 'users'
- self.abstract_class = true
- # Virtual attribute for the unencrypted password
- attr_accessor :password
- validates_presence_of :login, :email
- validates_presence_of :password, :if => :password_required?
- validates_presence_of :password_confirmation, :if => :password_required?
- validates_length_of :password, :within => 5..40, :if => :password_required?
- validates_confirmation_of :password, :if => :password_required?
- validates_length_of :login, :within => 3..40
- validates_length_of :email, :within => 3..100
- validates_uniqueness_of :login, :email, :case_sensitve => false
- # names that start with #s really upset me for some reason
- validates_format_of :login, :with => /^[a-zA-Z]{2}(?:\w )?$/
- validates_length_of :login, :minimum => 2
- # names that start with #s really upset me for some reason
- validates_format_of :display_name, :with => /^[a-zA-Z]{2}(?:[.'\w ] )?$/
- validates_uniqueness_of :display_name, :case_sensitive => false
- before_validation { |u| u.display_name = u.login if u.display_name.blank? }
- # first user becomes admin automatically
- before_create { |u| u.admin = true if User.count == 0 }
- before_save :encrypt_password
- # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
- def self.authenticate(login, password)
- u = find_by_login(login) # need to get the salt
- u && u.authenticated?(password) ? u : nil
- end
- # Encrypts some data with the salt.
- def self.encrypt(password, salt)
- Digest::SHA1.hexdigest("--#{salt}--#{password}--")
- end
- # Encrypts the password with the user salt
- def encrypt(password)
- self.class.encrypt(password, salt)
- end
- def authenticated?(password)
- crypted_password == encrypt(password)
- end
- def remember_token?
- remember_token_expires_at && Time.now.utc < remember_token_expires_at
- end
- # These create and unset the fields required for remembering users between browser closes
- def remember_me
- self.remember_token_expires_at = 2.weeks.from_now.utc
- self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
- save(false)
- end
- def forget_me
- self.remember_token_expires_at = nil
- self.remember_token = nil
- save(false)
- end
- protected
- def encrypt_password
- return if password.blank?
- self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
- self.crypted_password = encrypt(password)
- end
- def password_required?
- crypted_password.nil? || !password.blank?
- end
- end
- Index: app/controllers/application.rb
- ===================================================================
- --- app/controllers/application.rb (revision 1929)
- app/controllers/application.rb (working copy)
- @@ -1,22 1,17 @@
- class ApplicationController < ActionController::Base
- include AuthenticatedSystem
- session :session_key => '_beast_session_id'
- helper_method :current_user, :logged_in?, :admin?, :last_login
- - before_filter :login_by_token
- before_filter :login_from_cookie
- protected
- def login_required
- - login_by_token unless logged_in?
- login_from_cookie unless logged_in?
- redirect_to login_path unless logged_in? && authorized?
- end
- - def login_by_token
- - if not logged_in? and cookies[:login_token]
- - self.current_user=User.find_by_id_and_login_key(*cookies[:login_token].split(";"))
- - end
- - end
- -
- def authorized?; true; end
- # this is used to keep track of the last time a user has been seen (reading a topic)
- Index: app/controllers/sessions_controller.rb
- ===================================================================
- --- app/controllers/sessions_controller.rb (revision 1929)
- app/controllers/sessions_controller.rb (working copy)
- @@ -1,10 1,13 @@
- class SessionsController < ApplicationController
- # skip_before_filter :update_online
- def create
- - self.current_user = User.find_by_login_and_password(params[:login], params[:password])
- self.current_user = User.authenticate(params[:login], params[:password])
- if logged_in?
- flash[:notice] = "Logged in successfully."
- - cookies[:login_token]={ :value => "#{current_user.id};#{current_user.reset_login_key!}", :expires => Time.now.utc 1.year } if params[:remember_me]=="1"
- if params[:remember_me] == "1"
- self.current_user.remember_me
- cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
- end
- redirect_to home_path and return
- end
- flash.now[:notice] = "Invalid login or password, try again please."
- @@ -13,7 16,7 @@
- def destroy
- reset_session
- - cookies.delete :login_token
- cookies.delete :auth_token
- flash[:notice] = "You have been logged out."
- redirect_to home_path
- end
- Index: app/views/users/_form.rhtml
- ===================================================================
- --- app/views/users/_form.rhtml (revision 1929)
- app/views/users/_form.rhtml (working copy)
- @@ -24,4 24,4 @@
- <p>
- <label for="user_password_confirmation">Password Confirmation</label><br />
- <%= form.password_field :password_confirmation %>
- -</p>
- \ No newline at end of file
- </p>
- Index: db/schema.rb
- ===================================================================
- --- db/schema.rb (revision 1929)
- db/schema.rb (working copy)
- @@ -2,7 2,7 @@
- # migrations feature of ActiveRecord to incrementally modify your database, and
- # then regenerate this schema definition.
- -ActiveRecord::Schema.define(:version => 29) do
- ActiveRecord::Schema.define(:version => 31) do
- create_table "forums", :force => true do |t|
- t.column "name", :string
- @@ -33,7 33,7 @@
- t.column "user_id", :integer
- end
- - add_index "sessions", ["session_id"], :name => "sessions_session_id_index"
- add_index "sessions", ["session_id"], :name => "index_sessions_on_session_id"
- create_table "topics", :force => true do |t|
- t.column "forum_id", :integer
- @@ -48,23 48,24 @@
- end
- create_table "users", :force => true do |t|
- - t.column "login", :string
- - t.column "email", :string
- - t.column "password", :string
- - t.column "created_at", :datetime
- - t.column "last_login_at", :datetime
- - t.column "admin", :boolean
- - t.column "posts_count", :integer, :default => 0
- - t.column "last_seen_at", :datetime
- - t.column "display_name", :string
- - t.column "updated_at", :datetime
- - t.column "aim", :string
- - t.column "yahoo", :string
- - t.column "google_talk", :string
- - t.column "msn", :string
- - t.column "website", :string
- - t.column "login_key", :string
- - t.column "login_key_expires_at", :datetime
- t.column "login", :string
- t.column "email", :string
- t.column "crypted_password", :string
- t.column "created_at", :datetime
- t.column "last_login_at", :datetime
- t.column "admin", :boolean
- t.column "posts_count", :integer, :default => 0
- t.column "last_seen_at", :datetime
- t.column "display_name", :string
- t.column "updated_at", :datetime
- t.column "aim", :string
- t.column "yahoo", :string
- t.column "google_talk", :string
- t.column "msn", :string
- t.column "website", :string
- t.column "remember_token", :string
- t.column "remember_token_expires_at", :datetime
- t.column "salt", :string, :limit => 40
- end
- end
- Index: db/migrate/031_align_users_with_mephisto.rb
- ===================================================================
- --- db/migrate/031_align_users_with_mephisto.rb (revision 0)
- db/migrate/031_align_users_with_mephisto.rb (revision 0)
- @@ -0,0 1,15 @@
- class AlignUsersWithMephisto < ActiveRecord::Migration
- def self.up
- rename_column :users, :password, :crypted_password
- rename_column :users, :login_key, :remember_token
- rename_column :users, :login_key_expires_at, :remember_token_expires_at
- add_column :users, :salt, :string, :limit => 40
- end
- def self.down
- rename_column :users, :crypted_password, :password
- rename_column :users, :remember_token, :login_key
- rename_column :users, :remember_token_expires_at, :login_key_expires_at
- remove_column :users, :salt
- end
- end
- Index: lib/authenticated_system.rb
- ===================================================================
- --- lib/authenticated_system.rb (revision 0)
- lib/authenticated_system.rb (revision 0)
- @@ -0,0 1,98 @@
- module AuthenticatedSystem
- protected
- def logged_in?
- (@current_user ||= session[:user_id] ? User.find_by_id(session[:user_id]) : :false).is_a?(User)
- end
- def current_user
- @current_user if logged_in?
- end
- def current_user=(new_user)
- session[:user_id] = (new_user.nil? || new_user.is_a?(Symbol)) ? nil : new_user.id
- @current_user = new_user
- end
- def authorized?
- true
- end
- def login_required
- username, passwd = get_auth_data
- self.current_user ||= User.authenticate(username, passwd) || :false if username && passwd
- logged_in? && authorized? ? true : access_denied
- end
- def access_denied
- respond_to do |accepts|
- accepts.html do
- store_location
- redirect_to :controller=>"/account", :action =>"login"
- end
- accepts.xml { access_denied_with_basic_auth }
- end
- false
- end
- # store current uri in the session.
- # we can return to this location by calling return_location
- def store_location
- session[:return_to] = request.request_uri
- end
- # move to the last store_location call or to the passed default one
- def redirect_back_or_default(default)
- session[:return_to] ? redirect_to_url(session[:return_to]) : redirect_to(default)
- session[:return_to] = nil
- end
- def basic_auth_required
- unless session[:user_id] = User.authenticate(*get_auth_data)
- access_denied_with_basic_auth
- end
- end
- # adds ActionView helper methods
- def self.included(base)
- base.send :helper_method, :current_user, :logged_in?
- end
- # When called with before_filter :login_from_cookie will check for an :auth_token
- # cookie and log the user back in if apropriate
- def login_from_cookie
- return unless cookies[:auth_token] && !logged_in?
- user = User.find_by_remember_token(cookies[:auth_token])
- if user && user.remember_token?
- user.remember_me
- self.current_user = user
- cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
- flash[:notice] = "Logged in successfully"
- end
- end
- private
- def access_denied_with_basic_auth
- headers["Status"] = "Unauthorized"
- headers["WWW-Authenticate"] = %(Basic realm="Web Password")
- render :text => "Could't authenticate you", :status => '401 Unauthorized'
- end
- # gets BASIC auth info
- def get_auth_data
- user, pass = '', ''
- # extract authorisation credentials
- if request.env.has_key? 'X-HTTP_AUTHORIZATION'
- # try to get it where mod_rewrite might have put it
- authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
- elsif request.env.has_key? 'HTTP_AUTHORIZATION'
- # this is the regular location
- authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
- end
- # at the moment we only support basic authentication
- if authdata && authdata[0] == 'Basic'
- user, pass = Base64.decode64(authdata[1]).split(':')[0..1]
- end
- return [user, pass]
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement