Cannot login to Activeadmin after gem update - ruby-on-rails

After bundle update I cannot login to my Activeadmin, here is the log.
Is it because the unpermitted params? do I need to config strong parameter to make admin login work? I already have this code for devise:
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email, :password, :remember_me) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password) }
end
Started POST "/admin/login" for 127.0.0.1 at 2013-10-30 22:33:25 +1300
Processing by ActiveAdmin::Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MhoM/R/oVfad/iiov2zpqfoJ5XOSLda6rTl/V2cMIZE=", "admin_user"=>{"email"=>"tester#iv.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"}
Completed 401 Unauthorized in 0.6ms
Processing by ActiveAdmin::Devise::SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MhoM/R/oVfad/iiov2zpqfoJ5XOSLda6rTl/V2cMIZE=", "admin_user"=>{"email"=>"tester#iv.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"}
Unpermitted parameters: email, password, remember_me
Rendered /home/jcui/.rvm/gems/ruby-1.9.3-p194/gems/activeadmin-0.6.2/app/views/active_admin/devise/shared/_links.erb (0.6ms)
Rendered /home/jcui/.rvm/gems/ruby-1.9.3-p194/gems/activeadmin-0.6.2/app/views/active_admin/devise/sessions/new.html.erb within layouts/active_admin_logged_out (118.2ms)
Completed 200 OK in 130.7ms (Views: 129.9ms | ActiveRecord: 0.0ms | Solr: 0.0ms)

I assume that devise configuration is in your ApplicationController. Did you include the before_filter call?
before_filter :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email, :password, :remember_me) }
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password) }
end

Related

Completed 401 Unauthorized - Devise devise_parameter_sanitizer not permitting any values

I am new to Rails and stuck over here..could you please help me to solve this.
console
Started POST "/users/sign_in" for ::1 at 2020-03-25 11:46:10 +0530
Processing by Users::SessionsController#create as HTML
Parameters: {"authenticity_token"=>"seSNKhVVbrFM+XALvQExwMNxI1KY74or3Cy6Y0wYnU7RLjC6uuaM057jKmQ73a0g84qQNnOVREL0RZ6AuarGQA==", "user"=>{"email"=>"yadu#g.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
================================
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."email" = ? ORDER BY "users"."id" ASC LIMIT ? [["email", "yadu#g.com"], ["LIMIT", 1]]
↳ app/controllers/users/sessions_controller.rb:16:in `create'
Completed 401 Unauthorized in 248ms (ActiveRecord: 0.3ms | Allocations: 1519)
Started GET "/users/sign_in" for ::1 at 2020-03-25 11:46:10 +0530
Processing by Users::SessionsController#new as HTML
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (Duration: 1.0ms | Allocations: 525)
sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
before_action :configure_sign_in_params, only: [:create]
# GET /resource/sign_in
def new
super
end
# POST /resource/sign_in
def create
logger.debug "================================ #{configure_sign_in_params}"
super
end
# DELETE /resource/sign_out
def destroy
super
end
private
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_in_params
devise_parameter_sanitizer.permit(:sign_in) { |u| u.permit( :email, :password ) }
# params.require(:user).permit(:email, :password, :remember_me)
end
end
routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth',sessions: 'users/sessions'}
resources :users
resources :product_categories
config/initializers/devise.rb
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
config.mailer_sender = 'please-change-me-at-config-initializers-devise#example.com'
config.case_insensitive_keys = [:email]
config.strip_whitespace_keys = [:email]
config.stretches = Rails.env.test? ? 1 : 11
config.reconfirmable = true
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
config.password_length = 6..128
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
config.timeout_in = 30.minutes
config.reset_password_within = 6.hours
config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'], scope: 'public_profile,email'
config.omniauth :github, ENV['GITHUB_APP_ID'], ENV['GITHUB_APP_SECRET'], scope: 'user,public_repo'
config.omniauth :google_oauth2, ENV['GOOGLE_APP_ID'], ENV['GOOGLE_APP_SECRET'], scope: 'userinfo.email,userinfo.profile'
config.omniauth :twitter, ENV['TWITTER_APP_ID'], ENV['TWITTER_APP_SECRET']
end
Issue
I can register a user successfully, but cannot log in using that user. It shows 401 unautherized at the time. It appears that the parameter arrives in the configuration_sign_in_params method, but the return value of the configuration_sign_in_params method is empty.
All these issues are started from when i set login with social accounts ...Before that everything were fine .

No automatic sign_in after modifying devise registration controller

I initially wanted to send my user to a different page after sign_up. This works now, as I created a registrations controller. The problem now is that the user is prompted to login right after sign_up. Of course I want him to be automatically signed_in after sign_up. Any idea how I can fix that? I found this explanation but both answers do not work for me: Rails: Devise login after sign up.
Here is my registrations controller:
class RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters, if: :devise_controller?
def start_date
#user =current_user
end
protected
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status])
end
def after_sign_up_path_for(resource)
'/profiles/new' # Or :prefix_to_your_route
end
end
here are my application Logs after signup:
Started GET "/users/sign_up?job_category=IT+%26+Development&job_status=Other+Category&vacancy_id=general+application" for ::1 at 2019-08-08 15:32:17 +0200
Processing by RegistrationsController#new as HTML
Parameters: {"job_category"=>"IT & Development", "job_status"=>"Other Category", "vacancy_id"=>"general application"}
Rendering devise/registrations/new.html.erb within layouts/application
Rendered devise/registrations/new.html.erb within layouts/application (1.1ms)
Rendered shared/_navbar.html.erb (1.0ms)
Rendered shared/_flashes.html.erb (0.4ms)
Completed 200 OK in 174ms (Views: 171.7ms | ActiveRecord: 0.0ms)
Started POST "/users" for ::1 at 2019-08-08 15:32:32 +0200
Processing by RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Rb06/S6dB019mw8I46x0tJytVG7HNeVV23ZbuX/9Ykb9amYwI3bCLlk8AqNjTEGAR0qTy6rlCNZE1U6w8skslA==", "user"=>{"email"=>"testtesttest#test.de", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "applications"=>"\#{general application}", "job_category"=>"IT & Development", "job_status"=>"Other Category", "terms"=>"1"}, "commit"=>"Sign up"}
Can't verify CSRF token authenticity.
Unpermitted parameter: :terms
(0.5ms) BEGIN
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "testtesttest#test.de"], ["LIMIT", 1]]
SQL (6.9ms) INSERT INTO "users" ("email", "encrypted_password", "created_at", "updated_at", "applications", "job_category", "job_status") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["email", "testtesttest#test.de"], ["encrypted_password", "$2a$11$MlDweUU00bKQsNyA81/Cuu/o9HQSYJHM8FCInvVSaYVspvcs36oMS"], ["created_at", "2019-08-08 13:32:32.764097"], ["updated_at", "2019-08-08 13:32:32.764097"], ["applications", "{{\"general application\"}}"], ["job_category", "IT & Development"], ["job_status", "Other Category"]]
UserMailer#welcome: processed outbound mail in 0.2ms
(8.4ms) COMMIT
Redirected to http://localhost:3000/profiles/new
Completed 302 Found in 316ms (ActiveRecord: 16.2ms)
Started GET "/profiles/new" for ::1 at 2019-08-08 15:32:32 +0200
Processing by ProfilesController#new as HTML
Completed 401 Unauthorized in 3ms (ActiveRecord: 0.0ms)
Started GET "/users/sign_in" for ::1 at 2019-08-08 15:32:32 +0200
Processing by Devise::SessionsController#new as HTML
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (1.3ms)
Rendered devise/sessions/new.html.erb within layouts/application (11.0ms)
Rendered shared/_navbar.html.erb (1.4ms)
Rendered shared/_flashes.html.erb (0.5ms)
Completed 200 OK in 198ms (Views: 196.5ms | ActiveRecord: 0.0ms)
Change permitted params from:
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status])
end
to:
def configure_permitted_parameters
update_attrs = [:password, :password_confirmation, :current_password, :start_date]
devise_parameter_sanitizer.permit(:sign_up, keys: [ update_attrs, :applications, :job_category, :job_status])
end
And I think in profiles controller has a problem with before_action :authenticate_user! .
In terminal redirect has work.
You have a problem with terms, in your terminal:
Can't verify CSRF token authenticity.
Unpermitted parameter: :terms
Try changing the protect_from_forgery with: :exception to protect_from_forgery with: :exception, prepend: true
Ref: https://github.com/plataformatec/devise#controller-filters-and-helpers
Devise by default signout the session if the request is unverified.
Ref: from devise code(Devise::Controllers::Helpers),
# Overwrite Rails' handle unverified request to sign out all scopes,
# clear run strategies and remove cached variables.
def handle_unverified_request
super # call the default behaviour which resets/nullifies/raises
request.env["devise.skip_storage"] = true
sign_out_all_scopes(false)
end
Try this out if the first one solves the issue, https://github.com/plataformatec/devise/issues/2734 for solving the issue,
Change this:
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status]
To this:
devise_parameter_sanitizer.permit(:sign_up, keys: [:applications, :job_category, :job_status, :terms]

Devise - Login via phone number or email

I need to login to the application using phone number or email address. I am using devise 3.5.2 for authentication. As per this post(Devise sign up either by email or by mobile number), i have implemented the following.
application_controller.rb
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
added_attrs = [:phone, :email, :password, :password_confirmation, :remember_me]
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(added_attrs) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(added_attrs) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(added_attrs) }
end
user.rb
attr_accessor :email_confirmation, :login
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
def login=(login)
#login = self.email
end
def login
#login || self.phone || self.email
end
config/initializers/devise.rb
config.authentication_keys = [ :login ]
Now if i try to login either by using email or phone number i am getting an "unauthorized" error. A sample request is as follows.
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hCUuF5Ja9f37I4ZBSafGvCpgTnF1nKWf+q8aTEv28mW6vx3z+hIietmYjX9vi0/l/bjVqj0jDaV88mvmdXn9Vg==", "user"=>{"email"=>"jen#companyadmin.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uRnINI6Bogx3yeAP8WNpZB31jNOWnvvWVhHJg1BMZL2Hg/vQ5sl1i1Vy6zHXT+A9yi0XCN4hU+zQTLgpbsNrjg==", "user"=>{"email"=>"1234567890", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
For both requests, the response is
Completed 401 Unauthorized in 2ms
Any idea on how to fix this?
By the params you've shared, the phone or the email is being sent to the email named param. Instead it should be login.
If your view's code accepting the email or phone number is
<%= f.text_field :email %>
<%= f.text_field :phone %>
then replace it with
<%= f.text_field :login %>
This way, the param sent would be login and rest will be handled by your code.Let me know if this still gives you the error. Refer this link. This implements the same except it uses username. Also note modifying views. This seems to your problem. everything else seems to be correct.
You should override default login behaviour.
User.rb (put this code in user.rb model)
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_hash).where(["lower(phone) ILIKE '%#{login.downcase}%' OR lower(email) = :value", { :value => login.downcase }]).first
elsif conditions.has_key?(:phone) || conditions.has_key?(:email)
where(conditions.to_hash).first
end
end

Rails Devise Token Auth authentification without using email

I am trying to use devise_token_auth gem with API app on Rails 5.0.2.
I installed gem typically as mentioned on https://github.com/lynndylanhurley/devise_token_auth, so added to Gemfile, bundled and installed on User model. The problem is that, I don't want to use authentification (registration and login) with email. I just want to use telephone number instead (of course POST including with password and password_confirmation).
I added column :telephone_number, which will be unique to users table. And procced required steps to achieve this. https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-with-something-other-than-their-email-address
So this is what it looks like in code.
devise.rb
Devise.setup do |config|
...
config.authentication_keys = [ :telephone_number ]
config.case_insensitive_keys = [ :telephone_number ]
config.strip_whitespace_keys = [ :telephone_number ]
...
user.rb
class User < ActiveRecord::Base
# Include default devise modules.
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauthable, :authentication_keys => [:telephone_number]
include DeviseTokenAuth::Concerns::User
def email_required?
false
end
def email_changed?
false
end
application_controller.rb
class ApplicationController < ActionController::API
include DeviseTokenAuth::Concerns::SetUserByToken
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
added_attrs = [:telephone_number, :password, :password_confirmation, :remember_me]
devise_parameter_sanitizer.permit :sign_up, keys: added_attrs
devise_parameter_sanitizer.permit :account_update, keys: added_attrs
end
end
Server is starting properly, no exception is given. But when I test registration with RESTfull services POST on /auth it gives me validation error, that email can't be blank.
{"status":"error","data":{"id":null,"provider":"email","uid":"",
"name":null,"nickname":null,"image":null,"email":null,
"created_at":null,"updated_at":null,"telephone_number":"0123456789"},
"errors":{"email":["can't be blank","is not an email"],
"full_messages":["Email can't be blank","Email is not an email"]}}
EDIT:
Log from Puma
Started POST "/auth?=" for 127.0.0.1 at 2017-04-24 15:17:13 +0200
Processing by DeviseTokenAuth::RegistrationsController#create as */*
Parameters: {"telephone_number"=>"0123456789", "password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]", "registration"=>{"telephone_number"=>"0123456789",
"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}}
Unpermitted parameter: registration
Unpermitted parameter: registration
Unpermitted parameter: registration
(0.3ms) BEGIN
SQL (0.9ms) INSERT INTO "users" ("encrypted_password", "tokens", "created_at",
"updated_at", "telephone_number") VALUES ($1, $2, $3, $4, $5) RETURNING "id"
[["encrypted_password", "$2a$10$PgCIPAGA1VH1erHvJX5Sg.f4IPmSyfSoVM3EVbKtHkbgeUvEGL5NG"],
["tokens", "{}"], ["created_at", 2017-04-24 13:17:13 UTC], ["updated_at", 2017-04-24 13:17:13 UTC],
["telephone_number", "0123456789"]]
(0.2ms) ROLLBACK
Completed 422 Unprocessable Entity in 139ms (Views: 10.5ms | ActiveRecord: 1.3ms)
Reply on POST /auth
{"status":"error","data":{"id":null,"provider":"email","uid":"",
"name":null,"nickname":null,"image":null,"email":null,
"created_at":"2017-04-24T13:17:13.904Z","updated_at":"2017-04-24T13:17:13.904Z",
"telephone_number":"0123456789"},"errors":["An account already exists for ''"]}
It is checking and validating email, which currently is "", so no account could be registered through.
Is there any config property I should add, or override some method ?
Thank you in advance.

Devise: custom fields not saved after signing up Rails 4

I have installed devise gem in my app for registration. I have same issue like this question
I have generated Doctor model by
rails generate devise Doctor
And here is doctor.rb
class Doctor < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
I also generated controller by rails generate devise:controllers doctors
class Doctors::RegistrationsController < Devise::RegistrationsController
before_filter :sign_up_params, only: [:create]
before_filter :account_update_params, only: [:update]
#
# # GET /resource/sign_up
# def new
# super
# end
##
## # POST /resource
# def create
# super
# end
##
## # GET /resource/edit
# def edit
# super
# end
##
## # PUT /resource
# def update
# super
# end
##
## # DELETE /resource
# def destroy
# super
# end
protected
def sign_up_params
params.require(:doctor).permit(:first_name, :last_name, :email, :password, :password_confirmation, :gender, :contact_no, :about_me, :certification, :exp_summary, :username)
end
#
def account_update_params
params.require(:doctor).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password , :gender, :contact_no, :about_me, :certification, :exp_summary, :username)
end
# protected
# You can put the params you want to permit in the empty array.
#def configure_sign_up_params
# devise_parameter_sanitizer.for(:sign_up) << :first_name, :last_name, :gender, :contact_no, :about_me, :certification, :exp_summary, :username
#end
# You can put the params you want to permit in the empty array.
#def configure_account_update_params
# devise_parameter_sanitizer.for(:account_update) << :first_name, :last_name, :gender, :contact_no, :about_me, :certification, :exp_summary, :username
#end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
I have written in routes.rb file devise_for :doctor, :controllers => { sessions: "doctors/sessions"}.
Here is my logs from terminal after submitting Sign_up form
Started POST "/doctor" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Processing by Devise::RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8Dd5u5Qq+kLyAI+RaEuoSyjsxteHw4VBndQC+W5yjy0=", "doctor"=>{"username"=>"Test5", "first_name"=>"John", "last_name"=>"Smith", "contact_no"=>"8787878787", "gender"=>"true", "email"=>"john#smith.com", "about_me"=>"Test", "certification"=>"Test", "exp_summary"=>"Test", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Unpermitted parameters: username, first_name, last_name, contact_no, gender, about_me, certification, exp_summary
(0.2ms) BEGIN
Doctor Exists (0.3ms) SELECT 1 AS one FROM `doctors` WHERE `doctors`.`email` = BINARY 'john#smith.com' LIMIT 1
SQL (0.2ms) INSERT INTO `doctors` (`created_at`, `email`, `encrypted_password`, `updated_at`) VALUES ('2014-12-04 11:22:20', 'john#smith.com', '$2a$10$as.WAOu05ET7RUtnsdTC2ucqotK5Ls2Z6iKWI.wW3gSuIwohYfoTW', '2014-12-04 11:22:20')
(116.8ms) COMMIT
(0.1ms) BEGIN
SQL (0.3ms) UPDATE `doctors` SET `current_sign_in_at` = '2014-12-04 11:22:20', `current_sign_in_ip` = '127.0.0.1', `last_sign_in_at` = '2014-12-04 11:22:20', `last_sign_in_ip` = '127.0.0.1', `sign_in_count` = 1, `updated_at` = '2014-12-04 11:22:20' WHERE `doctors`.`id` = 7
(56.6ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 254ms (ActiveRecord: 174.5ms)
Started GET "/" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Processing by HomeController#index as HTML
Doctor Load (0.3ms) SELECT `doctors`.* FROM `doctors` WHERE `doctors`.`id` = 7 ORDER BY `doctors`.`id` ASC LIMIT 1
Rendered home/index.html.erb within layouts/application (0.0ms)
Completed 200 OK in 32ms (Views: 30.5ms | ActiveRecord: 0.3ms)
Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/home.css?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/turbolinks.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Started GET "/assets/home.js?body=1" for 127.0.0.1 at 2014-12-04 16:52:20 +0530
Why my custom fields are not saved? Where I do mistake?
Update
Controller Structure:
controllers
-> doctors
-> confirmations_controller.rb
-> omniauth_callbacks_controller.rb
-> passwords_controller.rb
-> registrations_controller.rb
-> sessions_controller.rb
-> unlocks_controller.rb
-> application_controller.rb
-> home_controller.rb
EDITED:
Okay! You were trying to override the devise controllers which is not required in your case. Follow these simple steps:
rails g model Doctor
Create your fields except email and password. Devise will take care of that.
rails g devise:install
rails g devise Doctor
In your ApplicationController:
before_action :configure_permitted_parameters, if: :devise_controller?
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :address, :phone, :email) }
end
Please try to do like following. Hopes it work for you. :)
class RegistrationsController < Devise::RegistrationsController
def create
devise_parameter_sanitizer.for(:sign_up) << [:first_name, :last_name]
super
end
end

Resources