Only allow a user to edit their own content - ruby-on-rails-4

I am using RoR 4 and the Devise gem for user authentication. I want a user to be able to edit their own content and not anyone else's content. The authenticate_user method only seems to make sure the user is logged in before they can edit the content. But another user can just sign up and edit everyone else's content.
My controller looks like:
class PrayersController < ApplicationController
before_action :find_prayer, only: [:show, :edit, :updated, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#prayers = Prayer.all.order("created_at DESC")
end
def show
end
def new
#prayer = current_user.prayers.build
end
def edit
end
def create
#prayer = current_user.prayers.build(prayer_params)
if #prayer.save
redirect_to #prayer, notice: "Successfully created prayer"
else
render 'new'
end
end
def update
#prayer = Prayer.find_by_id(params[:id])
if #prayer.update(prayer_params)
redirect_to #prayer, notice: "Prayer was successfully updated"
else
render 'edit'
end
end
def destroy
#prayer.destroy
redirect_to root_path
end
private
def prayer_params
params.require(:prayer).permit(:title, :body)
end
def find_prayer
#prayer = Prayer.find(params[:id])
end
end
I tried to make a before_action of my own that looked something like this:
def own_prayer
if !current_user == Prayer.current_user
redirect_to #prayer, notice: "You cannot edit this prayer"
end
end
But that did not work. I can limit access to the form via the view with a similar action but I don't think this is entirely safe?
Thank you

I guess you don't have class method current_user on Prayer class. Also seems you have has_many :prayers in your User model. So to get prayer's user you need to call user method on Prayer instance variable.
It's supposed to be like that:
#prayer = Prayer.find params[:id]
unless current_user == #prayer.user
redirect_to(#prayer, notice: "You cannot edit this prayer") and return
end
If you need more tricky restriction rules then use cancan gem

Related

Devise not redirecting to specified page after User sign up

Problem: I am using the after_sign_up_path_for(resource) method provided by Devise but I cannot seem to get the User redirected to the specified page after they sign up. Currently I receive a Template Missing error with the url being www.localhost:3000/users. Ideally, I would like to have the User redirected to www.localhost:3000/subscribers/new
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def create
#user = User.new(sign_up_params)
#domain = #user.email.split('#').last
#company = Company.find_by_domain(#domain)
#user.company_id = #company.id
if #user.save
after_sign_up_path_for(#user)
else
render 'new'
end
end
private
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :participation_code, :company_id)
end
protected
def after_sign_up_path_for(resource)
"/subscribers/new"
end
end
routes.rb
...
devise_for :users, controllers: { registrations: "registrations" }
...
Error Log I Get:
Template is Missing
Missing template registrations/create, devise/registrations/create,
devise/create, application/create with {:locale=>[:en], :formats=
[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby,
:coffee, :arb, :haml, :jbuilder]}.
UPDATE: I have tried moving the after_sign_up_path_for(resource) to the ApplicationController but still got the same result.
Very interesting. I simply changed
def create
...
end
to...
def update
...
end
Now everything works perfectly and my after_sign_up_path_for(resource) method is recognized.
Add below method in your application controller
Devise: Where to redirect users once they have logged in
def after_sign_up_path_for(resource)
"http://www.google.com" # <- Path you want to redirect the user to.
end
Maybe it worth to put redirect_method in after_action : create callback?
you dont need to create controller you can redirect user to specific path by defining
def after_sign_in_path_for(resource)
your_path
end
remember use after_sign_in_path_for not after_sign_up_path_for

Best in place sending routing error

I have a user controller as follows. I want to use the best_in_place gem for editing name and bio in profile page. I have followed Ryan Bates railscast but its not working correctly. When I tried to see the error through the chrome inspector I see best in place is requesting url http://localhost:3001/user/3 and now throwing 404 not found error.
users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!, only: [:profile]
respond_to :json, :html
def profile
#user = current_user
end
def show
#user = User.find(params[:id])
end
def update
if current_user.update(user_params)
respond_with current_user
end
end
def edit
#user = current_user
end
private
def user_params
params.require(:user).permit(:name, :bio)
end
end
routes.rb
Rails.application.routes.draw do
resources :user
end
In routes.rb you configured routes as resources :user which gives following routes:
But we can see your controller is UsersController so you have to configured your routes as: resources :users Which gives following routes:
Hope this may solve your problem.

Rails before filter not redirecting

Any reason why this before action would not redirect when #user is nil?
def set_user
#user ||= User.find(params[:id])
redirect_to "/errors/404" unless #user
end
I can actually see it redirecting in the log (pasted below).
Redirected to http://localhost:3000/errors/404
but instead of rendering that error page and routing away from the controller action, it completes the action and causes an error saying #user is nil.
The find method never returns nil. Instead, if a record with that ID doesn't exist, it throws an ActiveRecord::RecordNotFound error.
The easiest fix would be to use rescue_from:
class YourController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :redirect_to_not_found
# Other code
private
def set_user
#user ||= User.find(params[:id])
end
def redirect_to_not_found
redirect_to "/errors/404"
end
end
Now, the redirect_to_not_found method will be called whenever a user isn't found.

Omniauth and strong parameters

So this is probably going to be a very dumb question but i've set up Oauth with twitter as the provider in a similar way to Ryan Bates's 'Simple Omniauth Railscast - my question is now that that is set up and working should i be setting strong parameters in my sessions controller or is this not necessary?
SessionsController.rb
class SessionsController < ApplicationController
def create
#user = User.find_by_uid(auth_hash[:uid]) || User.create_user(auth_hash)
session[:uid] = #user.id
if #user
redirect_to root_path
else
redirect_to root_path, flash: {signinerror: "Oops, something went wrong with your sign in. Please try again."}
end
end
def auth_hash
request.env['omniauth.auth']
end
def destroy
session[:uid] = nil
redirect_to root_path
end
end
User.rb
class User < ActiveRecord::Base
has_many :opinions
def self.create_user(auth_hash)
create do |user|
user.provider = auth_hash[:provider]
user.name = auth_hash[:info][:name]
user.uid = auth_hash[:uid]
user.username = auth_hash[:info][:nickname]
user.email = auth_hash[:info][:email]
user.image = auth_hash[:info][:image]
end
end
end
Thanks
Since you don't use mass assignment on object creation, strong parameters will not give you any additional security.
With this plugin Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted.
https://github.com/rails/strong_parameters

Adding an editable field to omniauth generated / existing user

I'm using omniauth-twitter to create and authenticate users in my rails app and I'm successfully getting everything I need from Twitter, avatar, username, description, etc. But I'd like to let users add a custom string to display on their account page.
I added a column to the User table and ran the migration. The column is there.
I can't seem to get the update form to work, however. I'm not seeing errors. I just get a page refresh. Since I didn't have an existing form or controller methods to begin with I added them manually.
Here's my Users controller (I'm using friendly-id, hope that doesn't throw you.)
class UsersController < ApplicationController
def index
#users = User.all
end
def show
#user = User.friendly.find(params[:id])if params[:id]
end
def edit
#user = User.friendly.find(params[:id])if params[:id]
end
def update
#user = User.friendly.find(params[:id])if params[:id]
end
private
def user_params
params.require(:user).permit(:custom_text)
end
end
I'm not sure if I need both edit and update methods here, but I thought I'd try.
Here's my form (SLIM Template) which I include on the user's show page:
= form_for #user do |f|
= f.text_field :custom_text
= f.submit
The submit button works, as it were, but nothing is updated.
I'm pretty sure I'm just overlooking something painfully obvious.
I can't seem to get the update form to work, however. I'm not seeing errors.
Nothing is getting updated because you are not updating anything in the first place. As per the current code in the update action, its just selecting the record to be updated from the database but doing nothing with it.
def update
#user = User.friendly.find(params[:id])if params[:id] ## Simply selecting
end
In order to update the fetched record, you should call either update or update_attributes method on the instance of User model passing the changed attributes values to the method.
SOLUTION:
Use the following updated code in your UsersController. I have also DRYed up the code little bit by adding a before_action callback named set_user. The set_user method will be called every time before performing the actions such as show, edit and update and will take care of setting the instance variable #user.
class UsersController < ApplicationController
## Adding a before action callback
before_action :set_user, only: [:show, :edit, :update]
def index
#users = User.all
end
def show
end
def edit
end
def update
if #user.update(user_params)
## Redirect to user show page on successful update
redirect_to #user, notice: 'User was successfully updated.'
else
## Render user edit page again upon failure to update
render action: 'edit'
end
end
private
def set_user
#user = User.friendly.find(params[:id]) if params[:id]
end
def user_params
params.require(:user).permit(:custom_text)
end
end
Have you tried changing your form code to set the multipart:true to allow file to be sent
Try this and then upload the photo
= form_for #user,html: {multipart: true} do |f|
= f.file_field :custom_photo
= f.submit
I might also be missing something painfully obvious or new in Rails 4, but it seems like you should actually be telling the DB to update your record:
def update
#user = User.friendly.find(params[:id]) if params[:id]
#user.update_attributes(user_params) if #user
end
private
def user_params
params.require(:user).permit(:custom_text)
end
Without this second line in the update action, it's just finding the record and not doing anything with it...