Rails 4- Devise & User routes Clashing? - ruby-on-rails

I set up Devise for authentication on a rails 4 app. I tested sign up, sign in and edit forms. Everything worked fine.
Then I needed a form to get additional inputs from users. So I created new user routes to allow me to update/edit user records. Now my devise edit user form doesn't do anything when I click on submit.
I'm guessing this is because of some clash with the new routes but I could be wrong. Should I check something else?
my routes:
devise_for :users
resources :users, only: [:update, :edit]
demo app at http://mktdemo.herokuapp.com/users/edit - Sign in as test#test.com pwd: test1234.
application controller:
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_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :name
devise_parameter_sanitizer.for(:account_update) << :name
end
end

Related

rails - devise strong parameters is always unpermitted for registration

I want to permit :full_name parameter for my user model registration in devise, and I always getting Unpermitted parameter: :full_name as response for Users::RegistrationsController#create action
I have tried several ways as I show you next:
1. Application controller (option 1)
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
case params[:action]
when 'create'
devise_parameter_sanitizer.permit(:sign_up, keys: %i[full_name])
when 'update'
...
end
end
end
Result => Unpermitted parameter: :full_name
2. Registration controller (option 2)
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: :create
protected
def configure_sign_up_params
params.require(:user).permit(%i[full_name])
end
end
Result => Unpermitted parameter: :full_name
3. Registration controller (option 3)
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: :create
protected
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: %i[full_name ])
end
end
Result => Unpermitted parameter: :full_name
In my gemfile:
gem 'devise', '~> 4.8'
In my routes:
devise_controllers = {
confirmations: 'users/confirmations',
registrations: 'users/registrations',
invitations: 'users/invitations',
}
devise_for :users, controllers: devise_controllers
I have read devise strong params but to be honest I do not know what I am doing wrong.
Also I tried to debug in Users::RegistrationsController#create what is happening with:
def create
super do
binding.pry
end
end
but it skips the debugger breakpoint... do you have any idea what is going on?
Cheers!
Edit:
Following suggestion from JohnP, I only left :full_name in devise keys parametter sanitizer for sign_up
Also I removed a callback that is bypassing my debug breakpoint and now I can stop with pry in create action
Generally, you write strong params for a specific controller, not in your ApplicationController, because the permitted conditions will be different for each model. When using devise_parameter_sanitizer, you only need to include the extra fields you're adding - this isn't setting up your strong params from scratch, just adding keys to the default Devise list.
So, you should find that this is all you need in your Users::RegistrationsController.
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name])
end
(BTW, ensure you refer to the parameter correctly, as params[:user][:full_name].)
(Oh, and if you want to do debugging, I'd suggest installing the byebug gem. You just add an extra line byebug where you want to have a breakpoint.)

JSON API Rails 6 with Devise - SignUp Problems

When i try to use the sign_up method of Devise, i get an internal server error but, after create the user.
My application.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
before_action :configure_permitted_parameters, if: :devise_controller?
respond_to :json
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [ :username ])
end
end
Here the output,
Any ideas? 🤔
I am supplementing this with Doorkeeper, but please do not alter the operation of Devise. I also did not use Warden on my own anywhere on the app.
This issue seems to be the problem you are having:
https://github.com/heartcombo/devise/issues/4603
They suggest clearing the cookies of your browser
this usually happens when you are upgrading a bunch of stuck including
devise in one branch And than you get back to some other branch for
something and you have this newer cookie in your browser. Simple
solution is to clear cookies in browser.
Other answers mention upgrading devise version

Rails - How do you display data from the devise Users table in the View files?

I'm trying to display a simple welcome message to the user when they log in such as, "Welcome, Anthony!".
I created first_name and last_name attributes on the sign up and migrated them to the devise Users table and permitted the new attributes through the ApplicationController with this code,
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :first_name, :last_name])
end
end
This works perfectly fine, however, I want to display the first_name in my navbar in the application.html.erb file, which acts as a welcome message to the user once theyve signed in.
How do I display info from the Devise Users table?
Thanks,
Ant.
(If I need to add anything else then just let me know!)
Once you logged in you should be able to access a current_user object, from which you can get first_name and display in the welcome message in the application layout.

Rails + Devise ActionController::InvalidAuthenticityToken

Cheers!
I use Devise gem for authenticating users and locally (development env) I always get this ActionController::InvalidAuthenticityToken exception on devise::session/create action, no big deal I thought and added some dirt:
class ApplicationController < ActionController::Base
include EmailConcern
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
def handle_unverified_request
true
end
...
end
All right, no more authenticity_token exceptions, I don't mind if it happens only in dev env. But! There is another problem - :authenticate_user! is never worked, so current_user is always nil and I always getting redirected with 401 unauthorized to new session path again. User's credentials are valid and user exists in the DB.
router.rb
Rails.application.routes.draw do
resources :coupons
devise_for :users, path: 'u'
What could be the origin of this issue?
ruby-2.2.2#rails-4.2.0

Rails: Only allow admin user to create new users in Rails with Devise (No external modules)

Currently, my Users database has a column called "admin" with a boolean value and the default set to false. I have one admin user seeded into the database.
How do write my application so that users who are the admin can create new users, but users who are not cannot? (Also, users should be created only by the admin)
It seems like there should be a simple way to do this in devise that does not involve using some external module. So far however, I have not been able to find a satisfactory answer.
I would be more likely to mark the solution which is devise only. (One that is simply standard MVC/Rails solution a plus) However, if there really is a better way to do it that doesn't involve CanCan I may accept that too.
NOTE:
I have been searching around for a while and I've found several other stackoverflow questions that are very similar to this one, but either don't quite answer the question, or use other non-devise modules. (Or both)
To implement the authorization, use a method on the controller
Exactly as suggested by #diego.greyrobot
class UsersController < ApplicationController
before_filter :authorize_admin, only: :create
def create
# admins only
end
private
# This should probably be abstracted to ApplicationController
# as shown by diego.greyrobot
def authorize_admin
return unless !current_user.admin?
redirect_to root_path, alert: 'Admins only!'
end
end
To sidestep the Devise 'already logged in' problem, define a new route for creating users.
We will simply define a new route to handle the creation of users and then point the form to that location. This way, the form submission does not pass through the devise controller so you can feel free to use it anywhere you want in the normal Rails way.
# routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users, except: :create
# Name it however you want
post 'create_user' => 'users#create', as: :create_user
end
# users/new.html.erb
# notice the url argument
<%= form_for User.new, url: create_user_path do |f| %>
# The form content
<% end %>
This seems like the simplist approach. It just requires sub-classing the devise controller. See the docs for how to do that.
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
before_action :authenticate_user!, :redirect_unless_admin, only: [:new, :create]
skip_before_action :require_no_authentication
private
def redirect_unless_admin
unless current_user.try(:admin?)
flash[:error] = "Only admins can do that"
redirect_to root_path
end
end
def sign_up(resource_name, resource)
true
end
end
# config/routes.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { :registrations => 'registrations'}
end
Explaination:
Subclass the registration controller and create the route for it.
The before_action ensures that a user is logged in, and redirects them unless they are admin, if they try to sign up.
The already logged in issue is caused by Devise's require_no_authentication method and skipping it resolves the issue.
Next is that the newly created user is automatically signed in. The sign_up helper method which does this is overridden to do prevent automatic signup.
Finally, the Welcome! You have signed up successfully. sign up flash message can be changed via editing the config/locales/devise.en.yml file, if desired.
The problem is conceptual. Devise is only an Authentication library not an Authorization library. You have to implement this separately or use CanCan. Fret not however, it is easy in your case to implement this since you only have one role.
Guard your user create/update/destroy action with a before filter:
class UsersController < ApplicationController
before_filter :authorize_admin, except [:index, :show]
def create
# user create code (can't get here if not admin)
end
end
class ApplicationController < ActionController::Base
def authorize_admin
redirect_to root_path, alert: 'Access Denied' unless current_user.admin?
end
end
With this simple approach you run a before filter on any controller action that can affect a user record by first checking if the user is an admin and kicking them out to the home page if they're not.
I had this issue when working on a Rails 6 application.
I had an admin model which I Devise used to create admins.
Here's how I fixed it:
First I generated a Devise controller for the Admin model, which created the following files:
app/controllers/admins/confirmations_controller.rb
app/controllers/admins/omniauth_callbacks_controller.rb
app/controllers/admins/passwords_controller.rb
app/controllers/admins/registrations_controller.rb
app/controllers/admins/sessions_controller.rb
app/controllers/admins/unlocks_controller.rb
Next, I modified the new and create actions of the app/controllers/admins/registrations_controller.rb this way to restrict signup to admin using Devise:
class Admins::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up
def new
if admin_signed_in?
super
else
redirect_to root_path
end
end
# POST /resource
def create
if admin_signed_in?
super
else
redirect_to root_path
end
end
.
.
.
end
Afterwhich, I added the skip_before_action :require_no_authentication, only: [:new, :create] action to the app/controllers/admins/registrations_controller.rb this way to allow an already existing admin to create a new admin while being logged in:
class Admins::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
skip_before_action :require_no_authentication, only: [:new, :create]
.
.
.
end
You may need to also hide the Register and Forgot password buttons in the login form, to only been by logged in admins:
# app/views/admins/sessions/new.html.erb
<% if admin_signed_in? %>
<%= render "admins/shared/links" %>
<% end %>
Optionally, I added first_name and last_name parameters to the allowed parameters in the app/controllers/admins/registrations_controller.rb file, after already adding it to the admin model through a database migration:
class Admins::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
skip_before_action :require_no_authentication, only: [:new, :create]
.
.
.
# If you have extra params to permit, append them to the sanitizer.
def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name,
:last_name])
end
# If you have extra params to permit, append them to the sanitizer.
def configure_account_update_params
devise_parameter_sanitizer.permit(:account_update, keys: [:first_name,
:last_name])
end
.
.
.
end
Note: You will need to modify your app/views/admin/registrations views accordingly as well to cater for this
Additionally, you may need to create a new controller where you can create the index action for admins, say, app/controllers/admins/admins_controller.rb:
class Admins::AdminsController < ApplicationController
before_action :set_admin, only: [:show, :edit, :update, :destroy]
before_action :authenticate_admin!
# GET /admins
# GET /admins.json
def index
#admins = Admin.all
end
.
.
.
end
Note: If you need more control like managing admins by updating and deleting information of other admins from your dashboard, you may need to add other action like show, edit, update, destroy, and others to this file.
And for the routes:
## config/routes.rb
# List of Admins
get 'admins', to: 'admins/admins#index'
namespace :admins do
resources :admins
end
And then modify the path used after sign up in the app/controllers/admins/registrations_controller.rb to redirect to the admins_path, this will show you a list of all the admins that have been created:
class Admins::RegistrationsController < Devise::RegistrationsController
before_action :configure_sign_up_params, only: [:create]
before_action :configure_account_update_params, only: [:update]
skip_before_action :require_no_authentication, only: [:new, :create]
.
.
.
# The path used after sign up.
def after_sign_up_path_for(resource)
admins_path
end
# The path used after sign up for inactive accounts.
def after_inactive_sign_up_path_for(resource)
admins_path
end
end
Finally, you may need to change the notice that Devise gives when you create a user in the config/locales/devise.en.yml file, from:
Welcome, You have signed up successfully
to, say:
Account was created successfully.
That's all.
I hope this helps.

Resources