I'm working with Rails 4 and Devise 3.0.0 and am new to using these new strong paramters. I added a username to the User model using the documentation on the Devise wiki. The problem I'm running into is the strong parameters change in Rails 4.
How do I add the :login attribute to the user model to enable logging in with either the username or email?
From the rails4 readme on devise: https://github.com/plataformatec/devise/tree/rails4#strong-parameters
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :email) }
end
end
#justin.chmura
Here is a gist of how we ended up getting it working.
https://gist.github.com/AJ-Acevedo/6077336
Gist contains:
app/controllers/application_controller.rb
app/models/user.rb
config/initializers/devise.rb
You should make sure that you include the
attr_accessor :login
in the user model. Here is where I found the question explaining that attr_accessible is deprecated.
Rails 4 + Devise Login with email or username and strong parameters
Difference between attr_accessor and attr_accessible
This is what my app/models/user.rb file looks like.
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessor :login
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["username = :value OR lower(email) = lower(:value)", { :value => login }]).first
else
where(conditions).first
end
end
validates :username,
:uniqueness => {
:case_sensitive => false
}
end
It will works fine if you add an module in config/initializers as followings with all parameters,
File config/initializers/devise_permitted_parameters.rb with following contents:
module DevisePermittedParameters
extend ActiveSupport::Concern
included do
before_filter :configure_permitted_parameters
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation) }
end
end
DeviseController.send :include, DevisePermittedParameters
Related
I'm using:
ruby 2.6
rails 6.1.4
devise
devise_token_auth
active-storage usingl locally disk service
I'm creating api in which I can storage and upload pictures. I can upload pic via Insomnia but problem is when I want to add second image to the same user. Image is just replacing.
user.rb
# frozen_string_literal: true
class User < ActiveRecord::Base
def initialize
self.pictures = []
end
extend Devise::Models #added this line to extend devise model
# Include default devise modules. Others available are:
# :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
include DeviseTokenAuth::Concerns::User
VALID_USERNAME_REGEX= /^(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/ix
validates :username, presence: true, length: {minimum:3, maximum:26},
format: { with: VALID_USERNAME_REGEX, :multiline => true,
message: :invalid_username }
validate :password_complexity
attr_accessor :pictures
has_many_attached :pictures
validates :pictures, content_type: ['image/png', 'image/jpg', 'image/jpeg'],
size: { less_than: 5.megabytes , message: :invalid_size }
def password_complexity
return if password.blank? || password =~ /^((?!.*[\s]))/
errors.add :password, :invalid_password
end
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
devise_parameter_sanitizer.permit(:account_update, keys: [:pictures, :username, :email])
end
end
All controllers which I use are default from devise_token_auth. I found tip to add in config/application.rb
config.active_storage.replace_on_assign_to_many = false
but after that I'm always getting status 500
Did you add an array to the parameter so you can store multiple image ?
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:account_update, keys: [:pictures [], :username, :email])
end
I solved a similar problem by adding this to the config/environment/development.rb (as per the Rails Guide):
config.active_storage.replace_on_assign_to_many = false
Good luck!
The best way to solve this is to open application.rb and inside your module add.
config.active_storage.replace_on_assign_to_many = false
That is all you need to do. It works, Just make sure you save all your files, and restart your server.
You can see in the rails docs it says the following:
Optionally replace existing files instead of adding to them when assigning to a collection of attachments (as in #user.update!(images: [ … ])). Use config.active_storage.replace_on_assign_to_many to control this behavior.
Rails Guides
Everything was set up fine and seemed to be working. Suddenly I have an issue where if I log out and then log back in again with a different username it just logs me back in always as the first user.
Example:
user one - first#domain.com / password1
user two - second#domain.com / password2
Even if I log out and then log back in again as user two (verified as signed up correctly) it will log me in as user one.
Here is my user.rb file
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
acts_as_voter
has_many :links
has_many :comments
# Virtual attribute for authenticating by either username or email
# This is in addition to a real persisted field like 'username'
attr_accessor :login
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
elsif conditions.has_key?(:username) || conditions.has_key?(:email)
where(conditions.to_h).first
end
conditions[:email].downcase! if conditions[:email]
where(conditions.to_h).first
end
validates :username, presence: :true, uniqueness: { case_sensitive: false }
validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
validate :validate_username
def validate_username
if User.where(email: username).exists?
errors.add(:username, :invalid)
end
end
end
Application Controller
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
added_attrs = [:username, :email, :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
You might want to check your controllers. If you're determining the logged in user by using anything other than current_user, you may have used the wrong query or perhaps were using a specific user for testing purposes.
Check your User model. You're using :rememberable and might be passing a session cookie without realizing.
I'm working on creating an application with role based authorization.So,In i have created a migration to devise users to add a new column "role"
And I have the following code block in my applications controller to permit the new parameter(role).But still when i try to sign up as a new user.I get the error that the parameter role is unpermitted.Please help me to solve this issue.
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) { |u| u.permit( :email, :password, :password_confirmation, roles: [] ) }
end
end
This is what i've got in my user model
class User < ApplicationRecord
belongs_to :role
# has_many :Product
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
ROLES = %i[admin manager customer]
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, :role)
end
end
migration is as follows
class AddRoleToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :role, :string
end
end
Please help me to solve this issue.Thank you.
Your user model doesn't have access to params, so you can remove the user_params method from there. Unless you're nesting attributes, you won't need to pass in the array for the role attribute, so change
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit( :email, :password, :password_confirmation, roles: [] ) }
to
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit( :email, :password, :password_confirmation, :role ) }
#
And you should be good to go.
I am using devise for my rails app. I wanted to add the username field so I added a migration to the database.
Now I want devise to validate the user_name field for uniqueness but I am not able to figure out how to do that.
I also want it to show the error as it does with the default email field.
Just add validation for user_name in User model
validates :user_name, uniqueness: true
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) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
end
end
User Model code change - add validation
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username , uniqueness: {case_sesitive: false}
end
I am using rails 4 with strong parameters and trying to figure out how to set the strong parameters to not allow any attribute with the parameter.
I read this Rails 4 Strong parameters : permit all attributes? And would like to do the opposite of that.
params.require(:user).permit!
would permit all attributes, how could I do the opposite?
UPDATE THIS IS MY FULL CODE:
in app/controllers/application_controller.rb
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 :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:signin, :password, :remember_me) }
devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:username, :email, :password, :password_confirmation, :current_password)}
devise_parameter_sanitizer.for(:sign_in) { |a| a.permit(:signin, :password, :remember_me) }
devise_parameter_sanitizer.for(:account_update) {|a| a.permit(:username, :email, :password, :password_confirmation, :current_password)}
end
end
in app/models/admin.rb
class Admin < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable, :registerable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :signin
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:signin)
where(conditions).where(["username = :value OR lower(email) = lower(:value)", { :value => login }]).first
else
where(conditions).first
end
end
validates :username, presence: true, length: {maximum: 255}, uniqueness: { case_sensitive: false }, format: { with: /\A[a-zA-Z0-9]*\z/, message: "may only contain letters and numbers." }
end
The users.rb model is the same as the admin.rb model. This leads to two different sign up/sign in links- 1 for each model. Also I need to leave the :registerable module so that I can override the default devise's registerable module. However I modified the views to not show the admin page when typed in a browser. --- I only need to block it via command line now.
I also have posted a previous question similar to this:
Rails 4 Devise Strong Parameters Admin Model
If you're not using any user-inputted parameters (like for a GET), you don't need to use params at all. Your controller will just work, and there won't be a security issue.
The default behavior is the opposite of .permit. If you don't mention an attribute in your params arguments, it is like denying the user access to do anything with those attributes.