[Git][noosfero/noosfero][master] 2 commits: Associate user with sessions

Bráulio Bhavamitra gitlab at gitlab.com
Mon Aug 10 19:18:20 BRT 2015


Bráulio Bhavamitra pushed to branch master at Noosfero / noosfero


Commits:
3326fe90 by Braulio Bhavamitra at 2015-08-10T18:49:20Z
Associate user with sessions

- - - - -
b24e60ef by Braulio Bhavamitra at 2015-08-10T18:51:28Z
Associate current session with the user model

- - - - -


9 changed files:

- app/controllers/public/account_controller.rb
- + app/models/session.rb
- app/models/user.rb
- config/application.rb
- + config/initializers/session.rb
- + db/migrate/20150625234824_add_user_id_to_session.rb
- db/schema.rb
- lib/authenticated_system.rb
- test/functional/account_controller_test.rb


Changes:

=====================================
app/controllers/public/account_controller.rb
=====================================
--- a/app/controllers/public/account_controller.rb
+++ b/app/controllers/public/account_controller.rb
@@ -16,7 +16,7 @@ class AccountController < ApplicationController
   def activate
     @user = User.find_by_activation_code(params[:activation_code]) if params[:activation_code]
     if @user
-      unless @user.environment.enabled?('admin_must_approve_new_users') 
+      unless @user.environment.enabled?('admin_must_approve_new_users')
         if @user.activate
           @message = _("Your account has been activated, now you can log in!")
           check_redirection
@@ -30,7 +30,7 @@ class AccountController < ApplicationController
           @user.activation_code = nil
           @user.save!
           redirect_to :controller => :home
-        end      
+        end
       end
     else
       session[:notice] = _("It looks like you're trying to activate an account. Perhaps have already activated this account?")
@@ -94,6 +94,7 @@ class AccountController < ApplicationController
     @invitation_code = params[:invitation_code]
     begin
       @user = User.new(params[:user])
+      @user.session = session
       @user.terms_of_use = environment.terms_of_use
       @user.environment = environment
       @terms_of_use = environment.terms_of_use


=====================================
app/models/session.rb
=====================================
--- /dev/null
+++ b/app/models/session.rb
@@ -0,0 +1,18 @@
+class Session < ActiveRecord::SessionStore::Session
+
+  # removed and redefined on super class
+  def self.find_by_session_id session_id
+    super
+  end
+
+  belongs_to :user
+
+  before_save :copy_to_columns
+
+  protected
+
+  def copy_to_columns
+    self.user_id = self.data['user']
+  end
+
+end


=====================================
app/models/user.rb
=====================================
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -96,6 +96,10 @@ class User < ActiveRecord::Base
   has_one :person, :dependent => :destroy
   belongs_to :environment
 
+  has_many :sessions, dependent: :destroy
+  # holds the current session, see lib/authenticated_system.rb
+  attr_accessor :session
+
   attr_protected :activated_at
 
   # Virtual attribute for the unencrypted password


=====================================
config/application.rb
=====================================
--- a/config/application.rb
+++ b/config/application.rb
@@ -126,7 +126,7 @@ module Noosfero
     # Make sure the secret is at least 30 characters and all random,
     # no regular words or you'll be exposed to dictionary attacks.
     config.secret_token = noosfero_session_secret
-    config.session_store :cookie_store, :key => '_noosfero_session'
+    config.session_store :active_record_store, key: '_noosfero_session'
 
     config.paths['db/migrate'] += Dir.glob "#{Rails.root}/{baseplugins,config/plugins}/*/db/migrate"
     config.i18n.load_path += Dir.glob "#{Rails.root}/{baseplugins,config/plugins}/*/locales/*.{rb,yml}"


=====================================
config/initializers/session.rb
=====================================
--- /dev/null
+++ b/config/initializers/session.rb
@@ -0,0 +1,4 @@
+ActionDispatch::Reloader.to_prepare do
+  ActiveRecord::SessionStore.session_class = Session
+end
+


=====================================
db/migrate/20150625234824_add_user_id_to_session.rb
=====================================
--- /dev/null
+++ b/db/migrate/20150625234824_add_user_id_to_session.rb
@@ -0,0 +1,31 @@
+class AddUserIdToSession < ActiveRecord::Migration
+
+  def change
+    add_column :sessions, :user_id, :integer
+    add_index :sessions, :user_id
+  end
+
+  def up
+    Session.reset_column_information
+
+    # cleanup data: {}
+    Session.where(data: "BAh7AA==\n").delete_all
+    # cleanup data with lang key only
+    Session.where("data ~ 'BAh7BjoJbGFuZyIH.{3,3}=\n'").delete_all
+
+    # very slow migration, only do for the last month
+    Session.where('updated_at > ?', 1.month.ago).find_each batch_size: 50 do |session|
+      begin
+        # this calls Session#copy_to_columns
+        session.save!
+      rescue ArgumentError
+        # old ActionController::Flash::FlashHash from rails 2.3
+        session.destroy
+      end
+
+      # limit limitless allocations
+      GC.start
+    end
+  end
+
+end


=====================================
db/schema.rb
=====================================
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -11,7 +11,7 @@
 #
 # It's strongly recommended to check this file into your version control system.
 
-ActiveRecord::Schema.define(:version => 20150603182105) do
+ActiveRecord::Schema.define(:version => 20150625234824) do
 
   create_table "abuse_reports", :force => true do |t|
     t.integer  "reporter_id"
@@ -645,10 +645,12 @@ ActiveRecord::Schema.define(:version => 20150603182105) do
     t.text     "data"
     t.datetime "created_at"
     t.datetime "updated_at"
+    t.integer  "user_id"
   end
 
   add_index "sessions", ["session_id"], :name => "index_sessions_on_session_id"
   add_index "sessions", ["updated_at"], :name => "index_sessions_on_updated_at"
+  add_index "sessions", ["user_id"], :name => "index_sessions_on_user_id"
 
   create_table "suggestion_connections", :force => true do |t|
     t.integer "suggestion_id",   :null => false


=====================================
lib/authenticated_system.rb
=====================================
--- a/lib/authenticated_system.rb
+++ b/lib/authenticated_system.rb
@@ -24,7 +24,11 @@ module AuthenticatedSystem
     # Accesses the current user from the session.
     def current_user
       @current_user ||= begin
-        User.current = (session[:user] && User.find_by_id(session[:user])) || nil
+        id = session[:user]
+        user = User.where(id: id).first if id
+        user.session = session if user
+        User.current = user
+        user
       end
     end
 
@@ -34,6 +38,7 @@ module AuthenticatedSystem
         session.delete(:user)
       else
         session[:user] = new_user.id
+        new_user.session = session
         new_user.register_login
       end
       @current_user = User.current = new_user


=====================================
test/functional/account_controller_test.rb
=====================================
--- a/test/functional/account_controller_test.rb
+++ b/test/functional/account_controller_test.rb
@@ -623,6 +623,11 @@ class AccountControllerTest < ActionController::TestCase
     end
   end
 
+  should 'fill session for new users' do
+    post :signup, :user => { :login => 'testuser', :password => '123456', :password_confirmation => '123456', :email => 'testuser at example.com' }, :profile_data => { :organization => 'example.com' }
+    assert_equal assigns(:user).session, session
+  end
+
   should 'signup filling in mandatory person fields' do
     Person.any_instance.stubs(:required_fields).returns(['organization'])
     assert_difference 'User.count' do



View it on GitLab: https://gitlab.com/noosfero/noosfero/compare/e46033bd5016beca5f189527091e1a35a66ef565...b24e60efb22bd3dbf57a79bed2cc9a97162e25ad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://listas.softwarelivre.org/pipermail/noosfero-dev/attachments/20150810/4c2ab47a/attachment-0001.html>


More information about the Noosfero-dev mailing list