heroxav
heroxav

Reputation: 1467

Rails: Error when creating devise session

In my application I am trying to manually make devise sessions unusable by setting a session_validity_token.

How I do it:

In my devise initialization ...

Warden::Manager.after_set_user except: :fetch do |user, warden, opts|
  user.update_attribute(:session_validity_token, Devise.friendly_token) if user.session_validity_token.nil?
  warden.raw_session["validity_token"] = user.session_validity_token
end

Warden::Manager.after_fetch do |user, warden, opts|
  unless user.session_histories.unblocked.where(session_validity_token: warden.raw_session["validity_token"]).exists?
    warden.logout
  end
end

... when a user signs in or up I set the validity_token of the stored Cookie to the Users session_validity_token. If the User doesn't have one yet (signup), I create a token.

... when a URL gets fetched I check before authorizing the User if a unblocked session to that token exists. If not, the User gets logged out.

In the ApplicationController ...

def after_sign_in_path_for(resource_or_scope)
    session = SessionHistory.create(user_id: current_user.id, session_validity_token: current_user.session_validity_token)
    current_user.update_attribute(:session_validity_token, Devise.friendly_token)

    request.env['omniauth.origin'] || stored_location_for(resource) || root_path
end

... after a User gets signed in, I create a SessionHistory Record and simply set it's session_validity_token to the Users token and then recreate the Users token.

Unfortunately I get the following error:

NoMethodError in Users::SessionsController#create
undefined method `session_validity_token' for nil:NilClass

Here is the SessionController#Create Action:

def create
    if User.where("email = '#{params[:user][:login]}' or username = '#{params[:user][:login]}'").exists?
        @user = User.find(User.where("email = '#{params[:user][:login]}' or username = '#{params[:user][:login]}'").first.id)
        if @user.confirmed? || ((Time.now - @user.created_at).to_i / (24 * 60 * 60)) < 1
            super
        else
            redirect_to new_user_confirmation_path(q: "unconfirmed")
        end
    else
        flash[:alert] = "The email or username does not match any accounts"
        redirect_to new_user_session_path
    end
end

So I guess I did something wrong when handling the tokens with Warden ...

Please ask if you need additional Information.

Upvotes: 0

Views: 851

Answers (1)

Greg Tarsa
Greg Tarsa

Reputation: 1642

You may have a namespace collision between two customizations named session_validity_token. This is not naturally in the Devise model (and is not in the source for devise--I checked that).

If that is the case, and you have power over the source, consider changing the name of one, or both of the session_validity_token symbols to clarify the specific usage and relieve the conflict.

Upvotes: 1

Related Questions