Rails + Devise: if user_signed_in? not working - ruby-on-rails

I first discovered an issue where it didn't appear as if the user is getting logged in with this logic:
_header.html.erb:
<% if user_signed_in? %>
<li><%= link_to "Log out", destroy_user_session_path, method: :delete %></li>
<% else %>
<li><%= link_to "Sign in", new_user_session_path %></li>
<% end %>
Then I tried adding this to application_controller.rb:
before_filter :authenticate_user!
And I kept getting looped back to the login page (even with valid credentials).
It appears as if my user sessions aren't working — although I can see on my RailsAdmin console that the sign in count and last sign in date are showing as if they are logging in.
Here's my user.rb:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :omniauthable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable
belongs_to :company
has_and_belongs_to_many :productlines
end
And my routes.rb:
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }
root 'productlines#index'
end
And omniauth_callbacks_controller.rb:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
flash.notice = "Signed in through Google"
sign_in_and_redirect #user
return
else
session["devise.user_attributes"] = #user.attributes
flash.notice = "You are almost Done! Please provide a password to finish setting up your account"
redirect_to new_user_registration_path
end
end
end
Update: Here is my application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
before_filter :productline
def productline
#productlines = Productline.all
end
end
Every time I sign in, I'm rerouted back to the root_path and the "Sign In" link still appears.
Edit: Here is the log output when I click Sign In:
Started POST "/users/sign_in" for ::1 at 2015-07-06 23:20:15 -0400
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6Eh4Qw3qErGmsppatErFZYhTOZHs8DhCOMXqGAMrBzRdTd72L5rIGAChLDvnI/GzOv1kQsyL43o/B6AQQtnk4Q==", "user"=>{"email"=>"broy#bullhorn.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT 1 [["email", "b#gmail.com"]]
(0.1ms) begin transaction
SQL (0.3ms) UPDATE "users" SET "last_sign_in_at" = ?, "current_sign_in_at" = ?, "sign_in_count" = ?, "updated_at" = ? WHERE "users"."id" = ? [["last_sign_in_at", "2015-07-07 03:17:08.826634"], ["current_sign_in_at", "2015-07-07 03:20:15.963289"], ["sign_in_count", 93], ["updated_at", "2015-07-07 03:20:15.964239"], ["id", 4]]
(1.5ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 73ms (ActiveRecord: 2.1ms)
Started GET "/" for ::1 at 2015-07-06 23:20:15 -0400
Processing by ProductlinesController#index as HTML
Productline Load (0.1ms) SELECT "productlines".* FROM "productlines"
Rendered productlines/index.html.erb within layouts/application (2.1ms)
Rendered layouts/_header.html.erb (1.7ms)
Completed 200 OK in 48ms (Views: 47.3ms | ActiveRecord: 0.1ms)
Started GET "/" for ::1 at 2015-07-06 23:20:16 -0400
Processing by ProductlinesController#index as HTML
Productline Load (0.2ms) SELECT "productlines".* FROM "productlines"
Rendered productlines/index.html.erb within layouts/application (104.8ms)
Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 155ms (Views: 154.1ms | ActiveRecord: 0.2ms)

Do you want to put an exception in first on your authenticate user? That way it is not trying to run an authentication before current_user/#user/etc has even been set. For example if your root is index:
before_action :authenticate_user!, :except => [:index]
Then - be sure to have the better_errors gem and throw in some nonsense jibberish in your if user_signed_in? statement, refresh the page to trigger the console in the browser. See if #user or current_user or what you are using got set at all in the first place. I would then debug backwards from there.
https://github.com/charliesome/better_errors
Finally here is a stackoverflow link I came upon with a similar issue and a few answers below:
Rails devise: user_signed_in? not working

Related

devise rails application redirecting to users/sign_in

all -
New to rails and web development. I started a new rails application and am using Devise. Whenever I hit Log In on the users/sign_in page, the page just refreshes.
Here is my terminal log after clicking Log In. It's showing the POST, I'm not sure why it's ultimately rendering devise/sessions/new.html....:
Started POST "/users/sign_in" for ::1 at 2017-10-02 09:19:20 -0400
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ot4EJmxLvXrPpa6WYyqCXHxAUT3DcHimrIfw8HGyu5j7yuXvWArEkWzx59Dj3GZrlVDpgS/xSgXFSIt+mQqQnw==", "user"=>{"email"=>"bob#good.company", "password"=>"[FILTERED]"}, "commit"=>"Log in!"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT ? [["email", "bob#good.company"], ["LIMIT", 1]]
(0.1ms) begin transaction
(0.1ms) commit transaction
Completed 401 Unauthorized in 162ms (ActiveRecord: 0.3ms)
Started GET "/users/sign_in" for ::1 at 2017-10-02 09:19:21 -0400
Processing by Devise::SessionsController#new as HTML
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (1.2ms)
Rendered devise/sessions/new.html.erb within layouts/application (4.6ms)
Completed 200 OK in 45ms (Views: 43.5ms | ActiveRecord: 0.0ms)
My routes.rb
Rails.application.routes.draw do
get 'charges/create'
devise_for :users
get 'welcome/index'
get 'welcome/about'
resources :wikis
resources :charges, only: [:new, :create]
end
and my User.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :wikis
before_save { self.email = email.downcase }
enum role: [:standard, :admin, :premium]
after_initialize { self.role ||= :standard }
end
Thank you for any direction and please let me know if I can provide any more details / code samples etc.
please update this user password from console
this happened because of you only provided only password attribute, you skipped password_confirmation attribute
eg User.where(email: "Youremail#email.com").update(password: "password", password_confirmation: "password")

Devise's sign_in_after_reset_password doesn't seem to do what its name suggests

Devise's sign_in_after_reset_password setting supposedly signs in my user after successfully resetting the password.
However, what it seems to do in practice is to redirect back to '/', which ultimately results in showing the login page.
Why isn't it signing me in?
In user.rb:
devise :database_authenticatable,
:recoverable,
:validatable,
:encryptable
In application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
before_action :authenticate_user!, unless: :devise_controller?
#omitting business logic filters and helpers
end
Custom routes (solely to change the paths. Have tried to keep the resulting route list identical to the defaults other than the names):
devise_for :users, skip: [ :passwords, :sessions ]
devise_scope :user do
get 'users/login' => 'devise/sessions#new', as: 'new_user_session'
post 'users/login' => 'devise/sessions#create', as: 'user_session'
delete 'users/logout' => 'devise/sessions#destroy', as: 'destroy_user_session'
post 'users/password' => 'devise/passwords#create', as: 'user_password'
get 'users/password/forgot' => 'devise/passwords#new', as: 'new_user_password'
get 'users/password/reset' => 'devise/passwords#edit', as: 'edit_user_password'
patch 'users/password' => 'devise/passwords#update', as: nil
put 'users/password' => 'devise/passwords#update', as: nil
end
The investigation so far:
I had a lot of minor deviations from the structure of a sample devise application which I have been golfing back bit by bit to try and make things easier to figure out. So now my authenticate_user! filter is being specified in the same place as most examples.
Something I noticed is that after successfully resetting the password, it isn't clearing the reset password token. Maybe that's normal, it's just suspicious.
I have debugged in Devise's PasswordsController itself and after it executes the sign_in line, signed_in? does return true.
I have attempted to breakpoint inside signed_in? at the point of requesting the root path, but it seems like I get the 401 error from the web server without signed_in? ever being called. So perhaps Warden is directly kicking me out before the application even gets to run.
I'm starting to run out of avenues for investigation, so I thought I would post it here in case anyone had seen the exact same issue before.
Logs of the event:
Started PUT "/users/password" for ::1 at 2016-07-13 17:14:44 +1000
Processing by Devise::PasswordsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", "user"=>{"reset_password_token"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Change my password"}
Can't verify CSRF token authenticity
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."reset_password_token" = ? ORDER BY "users"."id" ASC LIMIT 1 [["reset_password_token", "[FILTERED]"]]
(0.0ms) begin transaction
Note Load (0.1ms) SELECT "notes".* FROM "notes" WHERE "notes"."notable_id" = ? AND "notes"."notable_type" = ? [["notable_id", 2], ["notable_type", "User"]]
Organisation Load (0.1ms) SELECT "organisations".* FROM "organisations" WHERE "organisations"."id" = ? LIMIT 1 [["id", 1]]
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE ("users"."login" = 'test1' AND "users"."id" != 2) LIMIT 1
(0.0ms) commit transaction
Redirected to http://localhost:3000/
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
Completed 302 Found in 44ms (ActiveRecord: 1.7ms)
Started GET "/" for ::1 at 2016-07-13 17:14:44 +1000
Processing by SessionsController#welcome as HTML
Completed 401 Unauthorized in 0ms (ActiveRecord: 0.0ms)
Started GET "/users/login" for ::1 at 2016-07-13 17:14:44 +1000
Processing by Devise::SessionsController#new as HTML
Rendered users/shared/_links.html.erb (0.1ms)
Rendered users/sessions/new.html.erb within layouts/application (2.2ms)
Completed 200 OK in 148ms (Views: 147.3ms | ActiveRecord: 0.0ms)
Not really answering the question itself, but I found a workaround which is at least a solution, even if it's a bad solution.
In my ApplicationController:
after_action :fix_login_after_password_reset, if: ->(controller) {
controller.controller_path == 'devise/passwords' &&
controller.action_name == 'update'
}
def fix_login_after_password_reset
user = current_user
if user && user.errors.empty?
user = User.where(id: user.id).first
sign_out
bypass_sign_in(user)
end
end
Essentially, I found a post where people who wrote their own "change password" pages found that Devise (or Warden?) was logging out the user immediately afterwards. The workaround for them was to change the call to sign_in to bypass_sign_in.
In this situation, though, Devise have already called sign_in. So I thought I'd try adding a filter that applies onto to their one action with the problem, and sign the user out, then sign in a fresh copy of the user. This fixes the issue - now the user is signed in and the root page appears.
I don't like this solution much though so I'm still digging inside Warden to try and figure out why the user is not being signed in with a call to sign_in.
I had the same issue, and found that passing an extra parameter to the sign_up function solves the problem:
sign_in(#user, :bypass => true)
This was something I found in this tutorial for setting up omniauth with a finish_signup feature. My implementation below is part of a feature I'm writing for a user to change their password and still retain their status as a logged in user.
~/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :set_current_user, only: [:edit_password, :update_password]
def edit_password
end
def update_password
if #user.update(user_params)
# Sign in the user by passing validation in case their password changed
sign_in(#user, :bypass => true)
redirect_to root_path
else
render :edit_password
end
end
private
def set_current_user
#user = User.find(current_user.id)
end
end
~/app/views/users/edit_password.html.erb
<%= form_for(#user, :url => { :action => "update_password" } ) do |f| %>
<div class="field">
<%= f.label :password, "Password" %><br />
<%= f.password_field :password, :autocomplete => "off" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %>
</div>
<div class="action_container">
<%= f.submit %>
</div>
<% end %>
routes.rb
resource :user, only: [:none] do
collection do
get :edit_password
patch :update_password
end
end

User session isn't being created, any idea why not?

I'm using a customised devise sessions controller to manage my user sessions, however whenever I try sign in as an existing user, my log in functionality doesnt work, it just returns the sign in form, and the server returns this message:
Started POST "/users/sign_in" for 127.0.0.1 at 2015-10-27 13:19:46 +0200
ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by Users::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lLtGottAklgEmCS2Y04FFZw3vAtd6EHkKOQMBCOJ4B6yeuFvN34j4OhYz9vd0SzW+gAwCI7GobMs20ubug24Fw==", "user"=>{"cell_number"=>"0798900606", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."cell_number" = $1 LIMIT 1 [["cell_number", "0798900606"]]
Completed 401 Unauthorized in 45ms (ActiveRecord: 2.5ms)
Processing by Users::SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lLtGottAklgEmCS2Y04FFZw3vAtd6EHkKOQMBCOJ4B6yeuFvN34j4OhYz9vd0SzW+gAwCI7GobMs20ubug24Fw==", "user"=>{"cell_number"=>"0798900606", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
Rendered users/sessions/new.html.slim within layouts/application (60.1ms)
Rendered application/_analytics.html.slim (4.7ms)
Rendered application/_environment_indicator.html.slim (2.5ms)
Rendered application/_preloader.html.slim (2.4ms)
Rendered application/_flashes.html.slim (3.7ms)
Category Load (0.7ms) SELECT "categories".* FROM "categories" WHERE "categories"."uuid" IS NULL LIMIT 1
Completed 200 OK in 746ms (Views: 660.3ms | ActiveRecord: 0.7ms)
My Sessions Controller looks like this:
class Users::SessionsController < Devise::SessionsController
before_action :configure_sign_in_parameters
def new
super
end
def create
#user = User.find_by(cell_number: params[:user][:cell_number])
super
end
private
def after_sign_in_path_for(resource)
root_path
end
def configure_sign_in_parameters
devise_parameter_sanitizer.for(:sign_in).push(:cell_number, :password)
end
end
My routes look like this:
Rails.application.routes.draw do
### Admin
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
### User
devise_for :users, controllers: { :registrations => "users/registrations",
:sessions => "users/sessions",
:passwords => "users/passwords" }
devise_scope :user do
namespace :vodacom do
namespace :users do
get "/register", to: 'registrations#new'
get "/create", to: 'registrations#create'
end
end
end
end
And my sign in form looks like this:
h2 Normal Log in
= simple_form_for #user, url: user_session_path(#user) do |f|
div class="form-inputs"
= f.input :cell_number, required: true, autofocus: true
= f.input :password, required: true
= f.input :remember_me, as: :boolean if devise_mapping.rememberable?
div class="form-actions"
= f.button :submit, "Log in"
Any clue what i'm doing wrong? My application controller specifies that a user should be authenticated before any action.
I figured out what I was doing wrong, my user model does not have an email attribute, rather it has a cell_number attribute. So since i'm using devise, devise defaults "email" as the authentication key for the model. In order to fix this i had to specify cell_number as an authentication key in my User model:
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:registerable,
:authentication_keys => [:cell_number]

Devise ERROR: Auth token has already been taken

Trying to signup in my RoR webapp give me the Devise Message "Auth token has already been taken"
Also, the webapp have an API and works fine, doesn't give any message, this only happen when I'm trying to use the HTML view.
user_controller.rb
before_action :set_user, only: [:show, :edit, :update, :destroy]
# DELETE /users/:id.:format
def destroy
# authorize! :delete, #user
#user.destroy
respond_to do |format|
format.html { redirect_to root_url }
end
end
private
def set_user
#user = User.find(params[:id])
end
def user_params
accessible = [ :name, :email ]
accessible << [ :password, :password_confirmation ] unless params[:user][:password].blank?
params.require(:user).permit(accessible)
end
User.rb
validates :auth_token, uniqueness: true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_create :generate_authentication_token!
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
logs
Started GET "/users/sign_up" for 127.0.0.1 at 2015-06-30 09:31:46 -0500
Processing by Devise::RegistrationsController#new as HTML
Rendered devise/registrations/new.html.haml within layouts/application (12.9ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."auth_token" IS NULL LIMIT 1
Rendered layouts/_navigation_links.html.haml (2.1ms)
Rendered layouts/_navigation.html.haml (3.4ms)
Rendered layouts/_messages.html.haml (0.2ms)
Completed 200 OK in 132ms (Views: 117.0ms | ActiveRecord: 1.5ms)
Started POST "/users" for 127.0.0.1 at 2015-06-30 09:32:00 -0500
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"20w9AXmACwggvPocKfLBdrxQRasT5OiaC7niuzooBBm3BAp8xkN6VLWyxZLRoLIpFPEIIdkxZRd9CCwsJxkeUA==", "user"=>{"email"=>"hola#x.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
(0.1ms) BEGIN
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."auth_token" = '' LIMIT 1
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'hola#x.com' LIMIT 1
(0.1ms) ROLLBACK
Rendered devise/registrations/new.html.haml within layouts/application (3.2ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."auth_token" IS NULL LIMIT 1
Rendered layouts/_navigation_links.html.haml (1.5ms)
Rendered layouts/_navigation.html.haml (2.1ms)
Rendered layouts/_messages.html.haml (0.2ms)
Completed 200 OK in 232ms (Views: 134.4ms | ActiveRecord: 1.2ms)
Started GET "/assets/jquery/jquery-bb5529929fa5581a780a38ecb7470f2c.js?body=1" for 127.0.0.1 at 2015-06-30 09:32:00 -0500
Follow the following
1) Open Rails console
rails console
2) Get the total count of users
user = User.all
user.count
this should be 1
3) Get the user and check the auth token
user = User.last
user.auth_token
auth token would be an empty string which is the reason your command is failing as the user doesn't have valid auth token
4) Create a valid auth token for the user
user.auth_token = Devise.friendly_token
user.save
It would create a valid auth token for the user and save it
5) Now you can run your commands and it would work perfectly
Cheers! :)
It's probably because you already have users in your db without auth_token,
use Devise.friendly_token to update those users with a token

Rails 4 devise_invitable invitation token invalid

I have been following Ryan Boland's excellent Rails multitenancy tutorial, but have run into a snag with devise_invitable. I am using...
Rails 4.1.5
devise 3.3.0
devise_invitable 1.3.6
Postgresql
I create a new account and user/account owner on a chosen subdomain (mysubdomain.lvh.me:3000), from which I can send a user invitation just fine. I open the invitation link in an incognito Chrome session to ensure I am not logged in or have any current session. Upon clicking on the invitation link, I am redirected to the sign in page (mysubdomain.lvh.me:3000/users/sign_in) and see a flash notice: "The invitation token provided is not valid!"
I am using a very simple mailer view (app/views/devise/mailer/invitation_instructions.html.erb)...
<%= link_to 'Accept invitation', accept_invitation_url(#resource, :invitation_token => #token) %>
As you can see, I ensured the use of #token, as described here.
Upon creating the invitation, I have confirmed the invitation token is saved to the database (in this case for hey#test.com - d1801fd8df78bd8cd125d5d8091fdc6a72c8f8faf4136cb282d497ec612195e9). I have confirmed this matches the token on invitation lookup upon acceptance request (see below traces). Still, it redirects to user sign in page rather than completing sign up, and also displays in the trace log "Filter chain halted as :resource_from_invitation_token rendered or redirected". The user remains uncomfirmed in the end after this transaction.
Any ideas on what might be going wrong for me here? I am including logs, my application controller, and my devise config below...
Here is the trace log for the invitation creation:
Started POST "/users/invitation" for 127.0.0.1 at 2014-09-07 01:28:33 +0800
Processing by Devise::InvitationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"BiIQ95wwdQz3CJ0+OoLOE9xHHvxhloHsRHrxsqf1D2Q=", "user"=>{"email"=>"hey#test.com"}, "commit"=>"Invite User"}
User Load (4.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Account Load (0.4ms) SELECT "public"."accounts".* FROM "public"."accounts" WHERE "public"."accounts"."subdomain" = 'mysubdomain' LIMIT 1
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'hey#test.com' ORDER BY "users"."id" ASC LIMIT 1
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = 'd1801fd8df78bd8cd125d5d8091fdc6a72c8f8faf4136cb282d497ec612195e9' ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) BEGIN
SQL (0.5ms) INSERT INTO "users" ("created_at", "email", "invitation_created_at", "invitation_sent_at", "invitation_token", "invited_by_id", "invited_by_type", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id" [["created_at", "2014-09-06 17:28:34.296123"], ["email", "hey#test.com"], ["invitation_created_at", "2014-09-06 17:28:34.294987"], ["invitation_sent_at", "2014-09-06 17:28:34.294987"], ["invitation_token", "d1801fd8df78bd8cd125d5d8091fdc6a72c8f8faf4136cb282d497ec612195e9"], ["invited_by_id", 1], ["invited_by_type", "User"], ["updated_at", "2014-09-06 17:28:34.296123"]]
(2.2ms) COMMIT
Rendered devise/mailer/invitation_instructions.html.erb (1.3ms)
Devise::Mailer#invitation_instructions: processed outbound mail in 23.5ms
Sent mail to hey#test.com (26.0ms)
Date: Sun, 07 Sep 2014 01:28:34 +0800
From: please-change-me-at-config-initializers-devise#example.com
Reply-To: please-change-me-at-config-initializers-devise#example.com
To: hey#test.com
Message-ID: <...>
Subject: Invitation instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
Accept invitation
Redirected to http://mysubdomain.lvh.me:3000/users
Completed 302 Found in 888ms (ActiveRecord: 10.0ms)
Here is the trace upon following the invitation link...
Started GET "/users/invitation/accept?invitation_token=3GXDmi7NntDRdhvo57q5" for 127.0.0.1 at 2014-09-07 01:28:38 +0800
Processing by Devise::InvitationsController#edit as HTML
Parameters: {"invitation_token"=>"3GXDmi7NntDRdhvo57q5"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."invitation_token" = 'd1801fd8df78bd8cd125d5d8091fdc6a72c8f8faf4136cb282d497ec612195e9' ORDER BY "users"."id" ASC LIMIT 1
Redirected to http://mysubdomain.lvh.me:3000/users/sign_in
Filter chain halted as :resource_from_invitation_token rendered or redirected
Completed 302 Found in 5ms (ActiveRecord: 0.6ms)
Started GET "/users/sign_in" for 127.0.0.1 at 2014-09-07 01:28:38 +0800
Processing by Devise::SessionsController#new as HTML
Account Load (0.4ms) SELECT "public"."accounts".* FROM "public"."accounts" WHERE "public"."accounts"."subdomain" = 'mysubdomain' LIMIT 1
Rendered devise/shared/_links.erb (0.7ms)
Rendered devise/sessions/new.html.erb within layouts/application (4.4ms)
Completed 200 OK in 21ms (Views: 16.6ms | ActiveRecord: 1.3ms)
Here is my application_controller for good measure...
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :load_schema, :authenticate_user!, :set_mailer_host
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :company, :email, :password, :password_confirmation, :remember_me, :image, :image_cache)}
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :company, :email, :password_confirmation, :current_password, :image, :image_cache)}
end
private
def load_schema
Apartment::Database.switch('public')
return unless request.subdomain.present?
if current_account
Apartment::Database.switch(current_account.subdomain)
else
redirect_to root_url(subdomain: false)
end
end
def current_account
#current_account ||= Account.find_by(subdomain: request.subdomain)
end
helper_method :current_account
def set_mailer_host
subdomain = current_account ? "#{current_account.subdomain}." : ""
ActionMailer::Base.default_url_options[:host] = "#{subdomain}lvh.me:3000"
end
def after_sign_out_path_for(resource_or_scope)
new_user_session_path
end
def after_invite_path_for(resource)
users_path
end
end
Here is my Devise initializer (config/initializers/devise.rb), I have added the line "config.allow_insecure_token_lookup = true" to see if this helps, but to no avail...
Devise.setup do |config|
config.mailer_sender = 'please-change-me-at-config-initializers-devise#example.com'
require 'devise/orm/active_record'
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 8..128
config.sign_out_via = :delete
config.allow_insecure_token_lookup = true
end
I'd prefer to comment but I have only 36 points and am not allowed so here's an incomplete answer:
this is the code from devise_invitable InvitationsController which is redirecting your request
def resource_from_invitation_token
unless params[:invitation_token] && self.resource = resource_class.find_by_invitation_token(params[:invitation_token], true)
set_flash_message(:alert, :invitation_token_invalid)
redirect_to after_sign_out_path_for(resource_name)
end
end
in your rails console try running:
token = '3GXDmi7NntDRdhvo57q5' #the token sent in the invitation email
User.find_by_invitation_token(token, true)
and see if that returns your User. It probably won't but maybe this will bring you closer to an answer. I hope so.

Resources