User session isn't being created, any idea why not? - ruby-on-rails

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]

Related

How to create user without password and set it later with Devise form?

I'm building a Rails app and I want to create users on the rails console WITHOUT password, receive a confirmation email, and by clicking on the link in the confirmation email, set the password on my website. (I'm using Devise)
Here is what I tried so far:
app/models/user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
protected
def password_required?
confirmed? ? super : false
end
end
app/controllers/users/confirmations_controller.rb
class Users::ConfirmationsController < Devise::ConfirmationsController
protected
def after_confirmation_path_for(resource_name, resource)
sign_in(resource)
edit_registration_path(resource)
end
end
I specifically did sign_in(resource) because I want people to be signed in during the process.
app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
end
end
For the moment, when I create a user through the rails console and then click the confirmation link, I end up in the devise view, to edit my account (more specifically my password), which is great, but I can't validate the form since I have to fill my previous password to change it. But since I don't have set any password during the creation I'm stuck!
Any ideas about how I could this?
Thanks
EDIT
As mentioned in the comment, I tried to use the "forgot my password" link. It works, but after setting their password, user will have to sign in (so enter again their password). In my opinion, it might not be a very good customer experience, that's why I would like to know if there's a way to do it as I explained in my post, OR a way to sign in the user after he set his password for the first time.
UPDATE
After some suggestions, I did some changes in my files, but I still get the error saying that the current password can't be blank. Here is my code:
routes.rb
Rails.application.routes.draw do
root to: 'page#index'
devise_for :users, path: '', path_names: { sign_in: 'sign_in', sign_out:
'sign_out'}, controllers: { confirmations: 'users/confirmations',
registrations: 'users/registrations' }
end
app/controllers/users/confirmations_controller.rb
class Users::ConfirmationsController < Devise::ConfirmationsController
def update_resource(resource, params)
if resource.encrypted_password.present?
super
else
resource.update(params)
end
end
protected
def after_confirmation_path_for(resource_name, resource)
sign_in(resource)
edit_registration_path(resource)
end
end
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
protected
def password_required?
confirmed? ? super : false
end
end
app/views/devise/registrations/edit.html.erb
<h2>Edit your account</h2>
<div>
<%= devise_error_messages! %>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<p><%= current_user.first_name %> <%= current_user.last_name %></p>
<p>Email address: <strong><%= current_user.email %></strong></p>
<div class="container mb-5">
<div class="row">
<%= f.label :password %>
</div>
<div class="row">
<%= f.password_field :password, autofocus: true, class: 'form-control', :required => 'required' %>
</div>
</div>
<div class="container mb-5">
<div class="row">
<%= f.label :password_confirmation %>
</div>
<div class="row">
<%= f.password_field :password_confirmation, autofocus: true, class: 'form-control', :required => 'required' %>
</div>
</div>
<div class="container text-center mb-3">
<%= f.submit "Update", class: 'navbar-cta' %>
</div>
<% end %>
</div>
logs
Started GET "/edit" for ::1 at 2020-01-20 18:06:29 +0100
Processing by Users::RegistrationsController#edit as HTML
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 33], ["LIMIT", 1]]
Rendering devise/registrations/edit.html.erb within layouts/application
DEPRECATION WARNING: [Devise] `DeviseHelper.devise_error_messages!`
is deprecated and it will be removed in the next major version.
To customize the errors styles please run `rails g devise:views` and modify the
`devise/shared/error_messages` partial.
(called from _app_views_devise_registrations_edit_html_erb___445667363343301985_70311530657080 at /Users/victor/Documents/SaaS projects/ChurnTarget/app/views/devise/registrations/edit.html.erb:6)
Rendered devise/registrations/edit.html.erb within layouts/application (Duration: 7.3ms | Allocations: 1979)
Rendered layouts/_google_analytics.html.erb (Duration: 0.4ms | Allocations: 164)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered page/_navbar.html.erb (Duration: 1.9ms | Allocations: 669)
Rendered page/_footer.html.erb (Duration: 0.8ms | Allocations: 162)
Completed 200 OK in 226ms (Views: 221.6ms | ActiveRecord: 0.5ms | Allocations: 61076)
Started PUT "/" for ::1 at 2020-01-20 18:07:00 +0100
Processing by Users::RegistrationsController#update as HTML
Parameters: {"authenticity_token"=>"99pJ5XaS5k5NQmba31GrTu5+jeN57mdPV51XlG6WFJoizS/5rbeLerzmTQv+kbsPIPorjH9fjAz3ihPxXENo1w==", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 33], ["LIMIT", 1]]
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 33], ["LIMIT", 1]]
Unpermitted parameter: :password_confirmation
Rendering devise/registrations/edit.html.erb within layouts/application
DEPRECATION WARNING: [Devise] `DeviseHelper.devise_error_messages!`
is deprecated and it will be removed in the next major version.
To customize the errors styles please run `rails g devise:views` and modify the
`devise/shared/error_messages` partial.
(called from _app_views_devise_registrations_edit_html_erb___445667363343301985_70311530657080 at /Users/victor/Documents/SaaS projects/ChurnTarget/app/views/devise/registrations/edit.html.erb:6)
Rendered devise/shared/_error_messages.html.erb (Duration: 2.0ms | Allocations: 441)
Rendered devise/registrations/edit.html.erb within layouts/application (Duration: 7.5ms | Allocations: 1514)
Rendered layouts/_google_analytics.html.erb (Duration: 0.1ms | Allocations: 8)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered page/_navbar.html.erb (Duration: 0.1ms | Allocations: 15)
Rendered page/_footer.html.erb (Duration: 0.0ms | Allocations: 5)
Completed 200 OK in 208ms (Views: 40.7ms | ActiveRecord: 1.1ms | Allocations: 20837)
Tell me if there are other files that you would like to see.
A different solution altogether would be to use Devise::Invitable that provides the feature that you're probably looking for.
It gives you a /users/invitations/new path with a form that you can fill out which invites users. The user record is saved and then the user completes the registration process by accepting the invitation.
If you really wanted to you could send the invitations from the console with:
User.invite!(email: 'someone#example.com')
But really I would just setup some basic authorization with Pundit or CanCanCan to lock down the invitations controller and do it through the GUI. You're most likely going to need it anyways.
module Users
class RegistrationsController < ::Devise::ConfirmationsController
protected
# By default Devise requires a password check on update.
# this override checks if there is stored password so that
# a confirmed user without a password can add their password
def update_resource(resource, params)
if resource.encrypted_password.present?
super
else
resource.update(params)
end
end
end
end
update_resource is called in Devise::ConfirmationsController#update. By default it calls resource.update_with_password(params) which monkeys around with the params and adds an validation error if the current password is not valid. Its not effected by password_required? since this special "validation" is done as part of the controller flow.
This just bypasses it if there is no saved password.
You need to configure the routes as well:
devise_for :users, controllers: {
confirmations: 'users/confirmations',
registrations: 'users/registrations'
}

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

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 + Devise: if user_signed_in? not working

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

Resources