This is my users controller and i am doing michael hartl's tutorial but i am having problem in current_user.admin? in the admin_user method defined in users controller and also having problem in my destroy method as i am not able to delete user as well.
pls any solution??
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def new
#user = User.new
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(user_params)
if #user.save
flash[:success] = 'Welcome to the Sample App!'
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = 'Profile Updated'
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = 'User deleted'
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
def logged_in_user
unless logged_in?
store_location
flash[:danger] = 'Please log in.'
redirect_to login_url
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
User.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: true
has_secure_password
validates :password, length: { minimum: 6 }
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
def forget
update_attribute(:remember_digest, nil)
end
end
Link for the Delete
<li>
<%= gravatar_for user %>
<%= link_to user.name, user %>
<% if current_user.admin? && !current_user?(user) %>
| <%= link_to 'delete', user, method: :delete,
data: { confirm: 'You sure?' } %>
<% end %>
</li>
Related
I am working on a project and I need to do a password reset system.
I'm not using any gem.
mailers/password_reset.rb
class PasswordReset < ActionMailer::Base
default from: 'no-reply#educx.com'
def send_password_reset(user)
#user = user
#reset_link = edit_password_resets_url({
token: #user.password_reset_token
})
mail({
:to => user.email,
:bcc => ['reset password <resetpassword#educx.com'],
:subject => I18n.t('password_reset.send_password_reset.subject')
})
end
end
views/password_reset/send_password_reset.html.erb
<h2><%= t '.greetings', full_name: #user.full_name %></h2>
<p><%= t '.body_html', link: link_to(t('.click_here'), #reset_link) %></p>
controllers/password_resets_controller.rb
class PasswordResetsController < ApplicationController
before_action :require_no_authentication, only: [:new, :create, :edit, :update]
def new
end
def create
user = User.find_by(email: params[:email])
if user.present?
user.generate_password_reset
PasswordReset.send_password_reset(user).deliver
redirect_to root_url, notice: t('flash.notice.check_email_reset')
else
flash[:alert] = t('flash.alert.cannot_find_email_reset')
render :new
end
end
def edit
#user = User.find_by(password_reset_token: params[:token])
end
def update
#user = User.find_by!(password_reset_token: params[:token])
if #user.password_reset_sent_at < 2.hours.ago
redirect_to new_password_reset_path, alert: t('flash.alert.time_expired')
end
if #user.update(password_reset_user_params)
#user.password_reseted!
redirect_to new_user_sessions_path, notice: t('flash.notice.password_reseted_complete')
else
render :edit
end
end
private
def password_reset_user_params
params.require(:user).permit(:password, :password_confirmation)
end
end
models/user.rb
class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
VALID_BIRTHDAY_REGEX = /[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/
validates_presence_of :full_name, :email, :birthday, :about
validates_length_of :about, minimum: 10, maximum: 100
validates_format_of :email, with: VALID_EMAIL_REGEX
validates_uniqueness_of :email
validates_format_of :birthday, with: VALID_BIRTHDAY_REGEX
has_secure_password
scope :confirmed, -> { where.not(created_at: nil) }
before_create do |user|
user.confirmation_token = SecureRandom.urlsafe_base64
end
def confirm!
return if confirmed?
self.confirmed_at = Time.current
self.confirmation_token = ''
save!
end
def confirmed?
confirmed_at.present?
end
def self.authenticate(email, password)
user = confirmed.find_by(email: email)
if user.present?
user.authenticate(password)
end
end
def generate_password_reset
self.password_reset_token = SecureRandom.urlsafe_base64
self.password_reset_sent_at = Time.zone.now
save!
end
def password_reseted?
password_reset_token.present?
end
def password_reseted!
return if password_reseted?
self.password_reset_token = ''
self.password_reseted_at = Time.current
save!
end
def password_reseted_expired?
password_reset_sent_at < 1.hours.ago
end
end
views/password_resets/new.html.erb
<%= form_tag password_resets_path, :method => :post do %>
<div>
<%= label_tag :email %>
<%= text_field_tag :email, params[:email] %>
</div>
<div><%= submit_tag %></div>
views/password_resets/edit.html.erb
<%= form_for #user do |f| %>
<p>
<%= f.label :password %><br>
<%= f.password_field :password %>
<%= error_field(#user, :password) %>
</p>
<p>
<%= f.label :password_confirmation %><br>
<%= f.password_field :password_confirmation %>
<%= error_field(#user, :password_confirmation) %>
</p>
<p>
<%= f.submit %>
</p>
controllers/users_controller.rb
class UsersController < ApplicationController
before_action :can_change, only: [:edit, :update]
before_action :require_no_authentication, only: [:new, :create]
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
Signup.confirm_email(#user).deliver
redirect_to new_user_sessions_path, notice: t('flash.notice.user_created')
else
render action: :new
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(user_params)
flash[:notice] = t('flash.notice.user_updated')
redirect_to #user
else
render action: :edit
end
end
private
def user_params
params.require(:user).permit(:full_name, :email, :birthday, :password, :password_confirmation, :about)
end
def can_change
unless user_signed_in? && current_user == user
redirect_to user_path(params[:id])
end
end
def user
#user ||= User.find(params[:id])
end
end
config/routes
resource :password_resets
The email is sent with no errors. But when I click on "Edit Password" at /password_resets/edit?token=fewgfeggrf, I am redirected to user's perfil! How can I change that?
I'm at the end of 9th chapter and i'm getting an error on the root page itself..
sessions helper is
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
current_user = user
end
def current_user
#current_user ||= user_from_remember_token
end
def signed_in?
!current_user.nil?
end
def sign_out
cookies.delete(:remember_token)
current_user = nil
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil, nil]
end
end
here is my user.rb
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :password, :presence => true,
:confirmation => true,
:length => {:within => 6..40 }
before_save :encrypt_password
def signed_in?
!current_user.nil?
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt)? user : nil
end
private
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
end
and my session_controller is
class SessionsController < ApplicationController
def new
#title = "Sign in"
end
def create
user = User.authenticate(params[:session][:email], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
redirect_to user
end
end
def destroy
sign_out
redirect_to root_path
end
end
and users_controler is
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
#title = #user.name
end
def new
#user = User.new
#title = "Sign up"
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
#title = "Sign up"
render 'new'
end
end
end
thing is i'm a beginer in Rails and i was going through this tutorials n got stuck right here.
Pls help guyz
here is the screenshot of the error
error says: undefined method 'authentication_with_salt'
I think it is similar issue that was asked and the link is here
You miss current_user scope. Check the above link and hope you can fix your issue asap.
I am newbie in rails. I am trying to generate a page form. but I am geting this error.
I could not understand where is my problem.
this was the error showing and it was highlighting in this line
#companies_rates =#user.companies_rates
Here I will be having userpage, companies_rate and page3 where each pages have user id and companies rate has an column same column also exit in the page 3. Now i want display companies_rate and page 3 seperately
NameError in UsersController#show
uninitialized constant User::CompaniesRate
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
**#companies_rates =#user.companies_rates**
#title=#user.name
end
Here is my users controller
class UsersController < ApplicationController
before_action :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
#companies_mines= #user.companies_mines
#companies_rates =#user.companies_rates
#title=#user.name
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to skillable"
redirect_to #user
else
render 'new'
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:name, :email, :password,
:password_confirmation)
end
# Before filters
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
And here is my companies_rate controller
class CompaniesRatesController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def index
#companies_rates = companies_rates.all
end
def show
#companies_rates = companies_rate.find(params[:id])
end
def new
#companies_rates = companies_rates.new
end
def create
#companies_rates = companies_rates .new(params[:company,:r1,:r2,:r3])
if #post.save
redirect_to companies_rates _path, :notice => "Your post was saved"
else
render "new"
end
end
def edit
end
def update
end
def destroy
end
private
def companies_rates_params
params.require(:companies_rates).permit(:company, :r1, :r2, :r3 )
end
def correct_user
#companies_rates = current_user.companies_rates.find_by(id: params[:id])
redirect_to root_url if #ompanies_rates.nil?
end
end
Here is my users modal
class User < ActiveRecord::Base
attr_accessor :password
#attr_accessible :name, :email, :password, :password_confirmation
has_many :companies_mines
has_many :companies_rates
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
Here is my companies_rates
class CompaniesRates < ActiveRecord::Base
#attr_accessible :company, :r1, :r2, :r3
belongs_to :user
validates :company, presence: true, length: { maximum: 140 }
validates :user_id, presence: true
belongs_to :user
default_scope :order => 'companies_rates.created_at DESC'
end
Can any on tell what is my problem and how to solve it.
Change the model name to CompaniesRate.Model name should be singular
I am in a process of upgrading my app from rails 2.3.11 to 3.2.x. Everything worked well untill 3.1.x where I faced issues in session handling. Earlier I have utilized cookies for session handling but now there is a question if I can use ActiveModel for handling sessions too?????
Secondly, while still playing around with cookies, I see this unavoidable undefined method error. Any suggestions to get around this error????
Here is my codes-
Session Controller:
class SessionsController < ApplicationController
def new
#title = "Sign in"
end
def create
#title = "create session"
user = User.authenticate(params[:session][:name], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid username/password combination."
#title = "Sign in"
render 'new'
else
sign_in user
#partner = Partner.find(:first, :conditions => [ "user_id = ?", user.id])
logger.info "---------User loggin: " + current_user.name
redirect_back_or samplings_url
end
end
def destroy
#title = "Sign out"
logger.info "---------User log OUT: " + current_user.name
sign_out
redirect_to root_path
end
end
User Model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password
EmailRegex = /\A[\w+\-._]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :name, :email
validates_length_of :name, :maximum => 50
validates_format_of :email, :with => EmailRegex
validates_uniqueness_of :email, :case_sensitive => false
has_many :microposts
validates_confirmation_of :password
validates_presence_of :password
validates_length_of :password, :within => 1..40
before_save :encrypt_password
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
def remember_me!
self.remember_token = encrypt("#{salt}--#{id}--#{Time.now.utc}")
save(validate=false)
end
private
def encrypt_password
unless password.nil? #due to def remember_me! method during sign in function call
self.salt = make_salt
self.encrypted_password = encrypt(password)
end
end
def encrypt(string)
secure_hash("#{salt}#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
UserController:
class UsersController < AuthController
before_filter :authenticate, :only => [:index, :edit, :update]
before_filter :correct_user, :only => [:new, :create, :destroy]
before_filter :modify_user, :only => [:edit, :update]
filter_parameter_logging :password
def index
#users = User.all
#title = "users"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
#title = #user.name
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def new
redirect_to signin_path
if !current_user?(#user)
flash[:notice] = "Only the partner who create the risorse can modify it."
end
end
def create
#title = "sign up user"
#user = User.new(params[:user]) #hash of user attributes
if #user.save
sign_in #user
flash[:success] = "Welcome to the microaqua web application!"
redirect_to #user #equal as user_path(#user)
else
#title = "Sign up"
render 'new'
end
end
# GET /users/1/edit
def edit
#title = #user.name #"user"
end
def update
#title = #user.name #"user"
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
def destroy
redirect_to users_path
end
private
def correct_user
#user = User.find(params[:id])
reroute() unless signed_in_and_master?
end
def modify_user
#user = User.find(params[:id])
reroute() unless (current_user?(#user) or signed_in_and_master?)
end
def reroute()
flash[:notice] = "Only the partner can modify his own profile."
redirect_to(user_path(#user))
end
end
Error:
NoMethodError in SessionsController#create
undefined method `encrypted_password' for #<ActiveRecord::Relation:0x00000003632038>
.where always returns an array. Here is the code that is throwing the error in your user model:
def self.authenticate(name, submitted_password)
username = self.where(name: name)
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
You are calling .encrypted_password on an array. Change the code to this:
def self.authenticate(name, submitted_password)
username = self.where(name: name).first
return nil if username.nil?
return username if username.encrypted_password == encrypt(submitted_password)
end
If it is possible to get more than one user with the same name then you should iterate through the array and check every result.
As far as storing the session in the database, check out this SO question:Rails 3: Storing Session in Active Record (not cookie)
I try railstutorial rails4.0
now 9.2.0 and no Rspec error.
but rails s has NoMethodError in Users#index when open /users
why?
app / models / user.rb
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end
app / controllers / users_controller.rb
class UsersController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update]
before_action :correct_user, only: [:edit, :update]
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def edit
end
def update
if #user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to #user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
#Before actions
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
end
app / views / users / index.html.slim
- provide(:title, 'All users')
h1 All users
ul.users
- #users.each do |user|
li
= gravatar_for user, size: 52
= link_to user.name, user
app / helpers / users_helper.rb
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
I have not tried. but it can be something like this.
before_save { self.email = email.downcase if email}
Your error would seem to be coming from the first line of the gravatar_for method, which calls user.email.downcase, suggesting you have at least one user with a nil email address in the database.