SHOW:
|
|
- or go back to the newest paste.
1 | Devise - Invalidate user session if the same user logs in from a different browser/machine | |
2 | - | class AddSignInTokenToUsers < ActiveRecord::Migration |
2 | + | #cmd: rails g migration add_sign_in_token_to_users |
3 | - | def change |
3 | + | #db/migration/######_add_sign_in_token_to_users.rb |
4 | - | add_column :users, :current_sign_in_token, :string |
4 | + | class AddSignInTokenToUsers < ActiveRecord::Migration |
5 | - | end |
5 | + | def change |
6 | add_column :users, :current_sign_in_token, :string | |
7 | - | |
7 | + | end |
8 | - | class ApplicationController < ActionController::Base |
8 | + | |
9 | - | before_filter :invalidate_simultaneous_user_session, :unless => Proc.new {|c| c.controller_name == 'sessions' and c.action_name = 'create' } |
9 | + | |
10 | - | |
10 | + | #app/application_controller.rb |
11 | - | def invalidate_simultaneous_user_session |
11 | + | class ApplicationController < ActionController::Base |
12 | - | sign_out_and_redirect(current_user) if current_user && session[:sign_in_token] != current_user.current_sign_in_token |
12 | + | before_action :invalidate_simultaneous_user_session, :unless => Proc.new {|c| c.controller_name == 'sessions' and c.action_name = 'create' } |
13 | - | end |
13 | + | |
14 | - | |
14 | + | def invalidate_simultaneous_user_session |
15 | - | def sign_in(resource_or_scope, *args) |
15 | + | sign_out_and_redirect(current_user) if current_user && session[:sign_in_token] != current_user.current_sign_in_token |
16 | - | super |
16 | + | end |
17 | - | token = Devise.friendly_token |
17 | + | |
18 | - | current_user.update_attribute :current_sign_in_token, token |
18 | + | |
19 | - | session[:sign_in_token] = token |
19 | + | |
20 | - | end |
20 | + | #config/application.rb |
21 | module Yourapp | |
22 | class Application < Rails::Application | |
23 | ||
24 | ||
25 | #add this | |
26 | Warden::Manager.after_authentication do |user, auth, opts| | |
27 | #auth.cookies - to access cookie | |
28 | token = Devise.friendly_token | |
29 | user.update_attribute :current_sign_in_token, token | |
30 | #session | |
31 | auth.env['rack.session'][:sign_in_token] = token | |
32 | end | |
33 | ||
34 | Warden::Manager.before_logout do |user, auth, opts| | |
35 | auth.env['rack.session'].delete :sign_in_token | |
36 | end | |
37 | end | |
38 | ||
39 | end |