How to validate password with confirm password in rails 3.2
my code not work
you can tell where my error
I've tried many variations changing the code in the controller.
Password saves but not validated to the password confirm field and password field.
help me please, help me )))
views
<%= form_for :password, :url => { :action => "change_password" }, :id => #user do |f| %>
<% if #user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Save", :class => "button blue" %>
<% end %>
User Controller
def change_password
#page_title = "Changing Zetfon account password"
#user = current_user
if request.post?
#user.password = Digest::SHA1.hexdigest(params[:password][:password])
if #user.save
redirect_to :action => 'profile'
flash[:status] = "Your password was changed. Next time you sign in use your new password."
else
flash[:status] = _('Your password not changed')
render :action => "change_password"
end
end
end
User Model
validates_confirmation_of :password
attr_accessible :password_confirmation
attr_accessor :password
add the following line to your model
validates :password, confirmation: true
Is it too late to simply use has_secure_password? You can learn about it in this RailsCast:
http://railscasts.com/episodes/270-authentication-in-rails-3-1
I'm not sure why you have if request.post?. Isn't that already determined by your route?
According to the documentation for validates_confirmation_of, I think you might need to add:
validates_presence_of :password_confirmation, :if => :password_changed?
Here's the documentation:
http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_confirmation_of
The documentation seems to indicate that you don't need attr_accessible :password_confirmation either.
I hope that helps.
Related
I'm following along Railscasts #250 Authentication from Scratch but have an issue where the Password Confirmation can be different from the Password and the user will still be created.
..model/dealer.rb:
class Dealer < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
..controllers/dealers_controller.rb
class DealersController < ApplicationController
def new
#dealer = Dealer.new
end
def create
#dealer = Dealer.new(dealer_params)
if #dealer.save
redirect_to root_url, :notice => "Signed Up!"
else
render "new"
end
end
private
def dealer_params
params.require(:dealer).permit(:email, :password)
end
end
..views/dealers/new.html/erb
<%= form_for #dealer do |f| %>
<p>
<%= f.label :email %><br>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br>
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br>
<%= f.password_field :password_confirmation %>
</p>
<p class="button"><%= f.submit %></p>
Any ideas what I need to do for this to work? Two people in the comments of the Railscast had the same issue but no answer.
Have you tried to add password_confirmation to your allowed params like this:
def dealer_params
params.require(:dealer).permit(:email, :password, :password_confirmation)
end
If this doesn't help try to generate accessor for password_confirmation too:
attr_accessor :password, :password_confirmation
How do I enable the Superadmin to actually create Users? Do I need a policy CreateusersPolicy? My code currently takes me to a page/form where I can create a user, but it doesn't actually create the user.
Please let me know if I need to include more information!
config/routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users, except: :create
root "pages#home"
get "index" => "users#index"
get 'create_user' => 'users#create', as: :create_user
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.
include Pundit
protect_from_forgery
def authorize_superadmin
redirect_to root_path, alert: 'Access Denied' unless current_user.superadmin?
end
end
I also don't know what to put here in the create section.
controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :authenticate_user!
#before_filter :authorize_superadmin, except [:show]
#after_action :verify_authorized
def create
# user create code (can't get here if not admin)
end
def index
#users = User.all
authorize User
end
def show
#user = User.find(params[:id])
authorize #user
end
def update
#user = User.find(params[:id])
authorize #user
if #user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
authorize user
user.destroy
redirect_to users_path, :notice => "User deleted."
end
private
def secure_params
params.require(:user).permit(:role)
end
end
views/users/create.html.erb
<%= form_for User.new, url: create_user_path do |f| %>
<div><%= f.label :first_name %><br />
<%= f.text_field :first_name, autofocus: true %></div>
<div><%= f.label :last_name %><br />
<%= f.text_field :last_name, autofocus: true %></div>
<div><%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %></div>
<div><%= f.label :phone_number%><br />
<%= f.phone_field :phone_number, autofocus: true %></div>
<div><%= f.label :street %><br />
<%= f.text_field :street, autofocus: true %></div>
<div><%= f.label :city %><br />
<%= f.text_field :city, autofocus: true %></div>
<div><%= f.label :state %><br />
<%= f.text_field :state, autofocus: true %></div>
<div><%= f.label :zip %><br />
<%= f.text_field :zip, autofocus: true %></div>
<div><%= f.label :password %> <% if #validatable %><i>(<%= #minimum_password_length %> characters minimum)</i><% end %><br />
<%= f.password_field :password, autocomplete: "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "off" %></div>
<div><%= f.submit "Create" %></div>
<% end %>
app/polices/user_policy.rb
class UserPolicy
attr_reader :current_user, :model
def initialize(current_user, model)
#current_user = current_user
#user = model
end
def index?
#current_user.superadmin?
end
def show?
#current_user.superadmin? or #current_user == #user
end
def update?
#current_user.superadmin?
end
def destroy?
return false if #current_user == #user
#current_user.superadmin?
end
def permitted_attributes
if #current_user.superadmin?
[:role]
else
[:name, :email]
end
end
end
You don't have a create? method in the UserPolicy file so you aren't actually authorizing anything (as far as I can tell).
It should read like this:
# app/policies/user_policy.rb
def create?
#current_user.superadmin?
end
# app/controllers/users_controller.rb
def create
authorize User
# rest of method to create user
end
Also, you don't need to (or want to IMO) have the authorize_superadmin method (you do have the before_filter commented out in the controller, so you aren't calling it) because a) you will call the authorize method in your action and this would be redundant and b) you want to keep your authorization logic in one location: the UserPolicy class. If the authorization fails, it will raise an exception and will not call the rest of the action.
The Pundit documentation is a great resource to get everything setup, but it does take a little bit of trial and error.
I also highly suggest that you create an ApplicationPolicy that you inherit all of your model specific authorization from so that you can catch things that you may not have defined. It is all in the documentation.
I have a user model which contains an "email switch" column with a boolean value. I'd like to create a button in my view which allows the user to turn "on" and "off" their emails. I can't get the submit button to update the value in the User model.
<%= form_for :user do |f| %>
<label>On</label>
<%= f.radio_button :email_switch, true %>
<label>Off</label>
<%= f.radio_button :email_switch, false %>
<%= f.submit "Save", :controller => "dashboard_emails", :action => "update", :method => "put" %>
<% end %>
class DashboardEmailsController < ApplicationController
before_filter :require_user
def index
end
def update
end
private
def require_user
#user = #logged_in_user
end
class User
field :email_switch, type: Boolean, default: false
end
You need to pass the arguments to form_for not to the f.submit call. If you have a persisted user assigned to #user you should be able to do:
<%= form_for #user do |f| %>
<label>On</label>
<%= f.radio_button :email_switch, true %>
<label>Off</label>
<%= f.radio_button :email_switch, false %>
<%= f.submit "Save" %>
<% end %>
Of course you need resources :users in your config/routes.rb to get this working. This should then send a PUT request to /users/47, which in turn fires the #update action of your UsersController
I've been trying recently to show a list of the fields modified with success on submitting a form. The only problem is that my form (I use simple form) doesn't show the errors when there are some and the form can't be submitted.
Here's my code simplified :
def update
#wizard.assign_attributes(params[:wizard])
# Get changed attributes
if #wizard.save
# Set the success flash with fields modified
redirect_to #wizard
else
#title = "Edition du profil"
render 'edit'
end
end
The view :
<%= simple_form_for #wizard do |f| %>
<%= f.input :email %>
<%= f.input :story %>
<%= f.submit "Modifier", :class => "btn success small" %>
<% end %>
The model :
class Wizard < ActiveRecord::Base
has_secure_password
attr_accessible :email, :story, :password, :password_confirmation, :password_digest
serialize :ranks, Array
validates_presence_of :email, :first_name, :last_name, :gender, :story
validates_presence_of :password, :password_confirmation, :unless => Proc.new { |w| w.password_digest.present? }
# Other validations here
has_one :subject, :foreign_key => "teacher_id"
ROLES = %w[teacher]
scope :with_role, lambda { |role| {:conditions => "roles_bitmask & #{2**ROLES.index(role.to_s)} > 0"} }
# Other functions here
end
Has anyone an idea ?
Thank you in advance !
It has probably something to do with how you overwrote AR. I remember some plugin getting in trouble with assign_attributes. Meanwhile you can try :
#wizard.assign_attributes(params[:wizard], :without_protection => true)
If that works it will at least narrow down the problem to mass assignment.
you perhaps missing this part in edit/new view.Where #wizard is your model_name.
Write this piece of code in the form tag.
<% if #wizard.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#wizard.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% #wizard.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
I've installed devise for my rails app, i can go to the sign in page or the sign up page. But I want them both on a welcome page...
So I've made a welcome_page_controller.rb with the following function:
class WelcomePageController < ApplicationController
def index
render :template => '/devise/sessions/new'
render :template => '/devise/registration/new'
end
end
But when i go to the welcome page i get this error:
NameError in Welcome_page#index
Showing /Users/tboeree/Dropbox/rails_projects/rebasev4/app/views/devise/sessions/new.html.erb where line #5 raised:
undefined local variable or method `resource' for #<#<Class:0x104931c>:0x102749c>
Extracted source (around line #5):
2: <% #header_title = "Login" %>
3:
4:
5: <%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
6: <p><%= f.label :email %><br />
7: <%= f.email_field :email %></p>
8:
Does anybody knows a solution for this problem? Thanks in advance!
Does it have to do with the fact that it is missing the resource function? in the welcome_page controller? It's probably somewhere in the devise controller...?
Regards,
Thijs
Here's how I managed to did it.
I've put a sign up form in my home#index
My files:
view/home/index.html.erb
<%= render :file => 'registrations/new' %>
helper/home_helper.rb
module HomeHelper
def resource_name
:user
end
def resource
#resource = session[:subscription] || User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
def devise_error_messages!
return "" if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t("errors.messages.not_saved",
:count => resource.errors.count,
:resource => resource_name)
html = <<-HTML
<div id="error_explanation">
<h2>#{sentence}</h2>
<ul>#{messages}</ul>
</div>
HTML
html.html_safe
end
end
You need that part because Devise works with something called resource and it should be defined so you can call your registration#new anywhere.
Like that, you should be able to register. However, I needed to display errors on the same page. Here's what I added:
layout/home.html.erb (the layout used by index view)
<% flash.each do |name, msg| %>
# New code (allow for flash elements to be arrays)
<% if msg.class == Array %>
<% msg.each do |message| %>
<%= content_tag :div, message, :id => "flash_#{name}" %>
<% end %>
<% else %>
# old code
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %> #don't forget the extra end
<% end %>
I found this code here
And here's something I created: I saved my resource object if invalid in a session so that the user hasn't to fill every field again. I guess a better solution exists but it works and it's enough for me ;)
controller/registration_controller.rb
def create
build_resource
if resource.save
if resource.active_for_authentication?
# We delete the session created by an incomplete subscription if it exists.
if !session[:subscription].nil?
session[:subscription] = nil
end
set_flash_message :notice, :signed_up if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => redirect_location(resource_name, resource)
else
set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords(resource)
# Solution for displaying Devise errors on the homepage found on:
# https://stackoverflow.com/questions/4101641/rails-devise-handling-devise-error-messages
flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
# We store the invalid object in session so the user hasn't to fill every fields again.
# The session is deleted if the subscription becomes valid.
session[:subscription] = resource
redirect_to root_path #Set the path you want here
end
end
I think I didn't forget any code. Feel free to use whatever you need.
Also, you can add your sign in form in the same page (something like that:)
<%= form_for("user", :url => user_session_path) do |f| %>
<%= f.text_field :email %>
<%= f.password_field :password %>
<%= f.submit 'Sign in' %>
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
<%= link_to "Forgot your password?", new_password_path('user') %>
<% end %>
Cheers !