Authlogic and multiple sessions for the same user - ruby-on-rails

I'm using Authlogic to manage the sessions in my application.
However, by default, authlogic allows a user to be logged in many times from different computers.
I don't want that (the user pays to get access and I want to avoid users sharing their accounts).
Looking in the Authlogic documentation, I've found about the perishable_token. But when trying to implement it, I just get an error saying the persistence_token is required (when it shouldn't be as I use the perishable one).
How would you do this using the Authlogic's features ?
Thanks :)

Ok so the perishable token was absolutely not the right path ;)
We "just" need to reset the persistence token every time a user logs in or logs out.
With this in my UserSession model, every user gets logged off from any other session when logging in.
class UserSession < Authlogic::Session::Base
before_destroy :reset_persistence_token
before_create :reset_persistence_token
def reset_persistence_token
record.reset_persistence_token
end
end

Related

Rails block user account if failed test during registration process

I want to build User registration flow where user signup to the blog_app and after account confirmation (via email link) he/she will be able to log in but have no ability to access their posts if he/she doesn't pass Legal Test (after the User account is confirmed, they should be presented with the Legal Test before they can do anything else, user needs to pass the test only once).
For authentication I'm using Devise gem.
I'm wondering should I use some Devise build-in module such case? or should I create additional DB column in Users table with status e.g. status: 'passed' or status: 'faild' and use pundit policy to block access in case User didn't passed the Legal Test?
Yes, you should an authorization gem like Pundit to manage authorization.
To accomplish something like this in Devise you would need separate roles for a "passed user" and a "failed user". It will quickly get messy and confusing as it's really not what it's meant for.
Using an authorization gem like Pundit is the way to go for your use case.
Yes, you will have to add a new column like status where you store the status and then override the devise's active_for_authentication? method so that the user is not allowed to login if he/she is marked as failed/banned:
def active_for_authentication?
super && self.status != 'failed'
end

Devise: How to use remember_me cookie after user sign out?

I'm working on a Rails 4.2 Application and using devise gem for authentication.
For remember_me feature, devise generates a cookie remember_user_token which gets destroy after sign_out.
Is there a way such that Devise should not destroy remember_user_token ?
I tried to false the below config in the initializer
config.expire_all_remember_me_on_sign_out = false
But it didn't help.
I need that cookie after sign-out such that it will populate the login form.
Please help.
Thanks
Coupling authentication with form pre-filling isn't necessarily a good idea. You can store the login in a cookie upon successful login. You can override the create method in your SessionsController, call super to call Devise::SessionsController#create and pass it a block. The block will be executed after a successful log in and will receive the user as a parameter.
class SessionsController < Devise::SessionsController
def create
super do |user|
cookies[:login] = user.login
end
end
end
Here is the low down on cookie store. First off, everything in a cookie is there permanently once it's set or until the user deletes the cookie manually somehow. This means, that if you set user_id and user_group_id, it's there for good in the cookie until updated or deleted. This is different from a session since the session is like ram on a computer, once the browser is closed, the session closes with it as well as all of it's data.
So, this means that when you log out your user, you need to specify that their cookie empties anything you don't wan't it to have. When your user logs in, you set anything that you want the user to have while they are logged in. So, since the session and cookie are separate things completely, they never interact together unless you choose to make them. So your session will never dump its self into the cookie store unless you make it do that.
Every time your users go to your site, you could have a single handshake that makes sure that the cookie matches the db if necessary. Otherwise, you could have differing data what only gets updated on login or what not and without the handshake, the user would have to keep logging in to make sure they are still valid which defeats the purpose of having a cookie in the first place.
The downside of client side cookie storage is security concerns. Depending on how you use the cookie to store data, a person could hijack somebodies cookie on your site and pretend they are them. This can be avoided by careful design, but just assume that whatever is in your cookie store is fair game to everybody so use it carefully and for only non secret data.
Hope this helps!

Sign out specific user with Devise in Rails

I have Devise for user authentication.
I want to sign out a user with a specific id.
in my controller
def exit
#user = User.find(5)
sign_out(#user) # this line here signs out the current_user
end
The sign out command of devise, even though I pass the #user, it signs out the current_user.
How can I select a user from the database and sign him out with the devise commands?
I am assuming this is part of some admin module, where you want to sign out a particular user.
However, this is not easy to solve. Whether or not a user is signed in or not is stored in the session. So to sign out another user, you would have to have access to its session.
Note: afaik the sign_out method only works in the current session, or maybe through warden (do not know warden well enough) it could extend to all sessions this current server has ever touched. However: if you use passenger, or some form of rails server cluster (which is pretty common), afaik this will not work. I would be interested to hear otherwise, with some explanation :) The sign_out uses the given parameter to determine the scope to sign out from in (afaik) the current session.
So what we generally did was add a kind of emergency button to sign out all users: which destroys all sessions. Note this is of course only possible if you use some database or document-store backed session-store.
Alternatively you could open all sessions, and look for the correct session (for your user), and then destroy those sessions.
To read data from a specific session in stored in activerecord, you can write the following:
#session = ActiveRecord::Base.connection.select_all( "SELECT * FROM sessions WHERE session_id = '#{sess_id}'" )
Marshal.load(ActiveSupport::Base64.decode64(#session.data))
There are alternative approaches:
use Timeoutable module, and force a timeout for a user?
if you use Rememberable you could do #user.forget_me, but I am not sure that this actually affects the current session?
from the device api doc http://rubydoc.info/github/plataformatec/devise/master/Devise/Controllers/SignInOut#sign_out-instance_method the sign_out(#user) method should works. Is it possible that the current_user by chance has the id 5?

Devise with user logged in using multiple scopes logs all but one out when using token_authenticateable

I'm using Devise with multiple scopes (in this case, a user scope and an admin scope) and admins are able to 'become' a user using the approach on the Devise wiki. This works well, except that I have one particular page that requires the use of an auth token that causes a problem with a session logged in under both a user and admin scope. The page generates a POST to a controller that requires a user to be logged in using the user auth token. The POST succeeds, but afterwards, the admin scope has been signed out. (Meaning that admin_signed_in? returns false.) Other pages that execute POSTs to the same controller without requiring the auth token work as expected without logging out the admin scope.
I suspect that something is going on with token_authenticatable where the authentication of any scopes other than the one associated with that specific token are logged out. I've searched for references in the devise gem source to both the devise sign_out and warden logout methods that could be invoked as part of the token_authenticatable functionality and wasn't able to find anything.
This is happening with Devise 1.3.4. Any help is appreciated.
In case anyone else is looking for a solution to this, I found that the before_filter/after_filter approach I described in the comment to my question seems to work fine. I think that a better, more general solution to this would be to make a change to the devise gem and underlying calls to warden, but didn't have time to make those changes for this particular problem yet.

Implementation of "Remember me" in a Rails application

My Rails-app has a sign in box with a "remember me" checkbox. Users who check that box should remain logged in even after closing their browser. I'm keeping track of whether users are logged in by storing their id in the user's session.
But sessions are implemented in Rails as session cookies, which are not persistent. I can make them persistent:
class ApplicationController < ActionController::Base
before_filter :update_session_expiration_date
private
def update_session_expiration_date
options = ActionController::Base.session_options
unless options[:session_expires]
options[:session_expires] = 1.year.from_now
end
end
end
But that seems like a hack, which is surprising for such common functionality. Is there any better way?
Edit
Gareth's answer is pretty good, but I would still like an answer from someone familiar with Rails 2 (because of it's unique CookieSessionStore).
You should almost certainly not be extending the session cookie to be long lived.
Although not dealing specifically with rails this article goes to some length to explain 'remember me' best practices.
In summary though you should:
Add an extra column to the user table to accept a large random value
Set a long lived cookie on the client which combines the user id and the random value
When a new session starts, check for the existence of the id/value cookie and authenticate the new user if they match.
The author also recommends invalidating the random value and resetting the cookie at every login. Personally I don't like that as you then can't stay logged into a site on two computers. I would tend to make sure my password changing function also reset the random value thus locking out sessions on other machines.
As a final note, the advice he gives on making certain functions (password change/email change etc) unavailable to auto authenticated sessions is well worth following but rarely seen in the real world.
I have spent a while thinking about this and came to some conclusions. Rails session cookies are tamper-proof by default, so you really don't have to worry about a cookie being modified on the client end.
Here is what I've done:
Session cookie is set to be long-lived (6 months or so)
Inside the session store
An 'expires on' date that is set to login + 24 hours
user id
Authenticated = true so I can allow for anonymous user sesssions (not dangerous because of the cookie tamper protection)
I add a before_filter in the Application Controller that checks the 'expires on' part of the session.
When the user checks the "Remember Me" box, I just set the session[:expireson] date to be login + 2 weeks. No one can steal the cookie and stay logged in forever or masquerade as another user because the rails session cookie is tamper-proof.
I would suggest that you either take a look at the RESTful_Authentication plug in, which has an implementation of this, or just switch your implementation to use the RESTful Authentication_plugin. There is a good explanation about how to use this plug in at Railscasts:
railscasts #67 restful_authentication
Here is a link to the plugin itself
restful_authentication
The restful_authentication plugin has a good implementation of this:
http://agilewebdevelopment.com/plugins/restful_authentication
Note that you don't want to persist their session, just their identity. You'll create a fresh session for them when they return to your site. Generally you just assign a GUID to the user, write that to their cookie, then use it to look them up when they come back. Don't use their login name or user ID for the token as it could easily be guessed and allow crafty visitors to hijack other users' accounts.
This worked like a charm for me:
http://squarewheel.wordpress.com/2007/11/03/session-cookie-expiration-time-in-rails/
Now my CookieStore sessions expire after two weeks, whereby the user must submit their login credentials again in order to be persistently logged-in for another two weeks.
Bascially, it's as simple as:
including one file in vendor/plugins directory
set session expiry value in application controller using just one line
I would go for Devise for a brilliant authentication solution for rails.

Resources