it might be a silly question but I am stuck with this for some time as I am new to rails.
I am basically using a custom registration controller to overwrite devise
class RegistrationsController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /Users
def index
#Users = User.all
end
# GET /Users/1
def show
end
# GET /Users/new
def new
#User = User.new
#course = Course.find_by id: params["course_id"]
end
# POST /Users
def create
#User = User.new(user_params)
if #User.save
redirect_to #User.paypal_url(registration_path(#User))
else
render :new
end
end
protect_from_forgery except: [:hook]
def hook
params.permit! # Permit all Paypal input params
status = params[:payment_status]
if status == "Completed"
#User = User.find params[:invoice]
#User.update_attributes notification_params: params, status: status, transaction_id: params[:txn_id], purchased_at: Time.now
end
render nothing: true
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#User = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:course_id, :name, :email, :password,:password_confirmation)
end
end
In my routes I have
devise_for :users ,:controllers => { :registrations => "registrations" }
So now I have
edit_user_registration_path GET /users/edit(.:format) registrations#edit
My question is how can I route only edit back to devise/registrations/edit or what can i add to my registrations controller so that I get something similar?
If you want to delegate the create action of the registrations controller to Devise, I recommend you to create a controller that inherits from the Devise one:
class RegistrationsController < Devise::RegistrationsController
def create
super #We call super because we don't want to override this action
end
def edit
#Custom code to override this action
end
end
Your route's configuration stays as it is, you just have to change your controller, you may also want to know that it's possible to ADD functionality to what devise already does, instead of override it:
def edit
super do |resource|
#Here you add what you'll do AFTER devise works
end
end
Related
I am currently building a simple web app with Ruby on Rails that allows logged in users to perform CRUD actions to the User model. I would like to add a function where:
Users can select which actions they can perform per controller;
Ex: User A can perform actions a&b in controller A, whereas User B can only perform action B in controller A. These will be editable via the view.
Only authorized users will have access to editing authorization rights of other users. For example, if User A is authorized, then it can change what User B will be able to do, but User B, who is unauthorized, will not be able to change its own, or anyone's performable actions.
I already have my users controller set up with views and a model
class UsersController < ApplicationController
skip_before_action :already_logged_in?
skip_before_action :not_authorized, only: [:index, :show]
def index
#users = User.all
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
redirect_to users_path
else
render :new
end
end
def show
set_user
end
def edit
set_user
end
def update
if set_user.update(user_params)
redirect_to user_path(set_user)
else
render :edit
end
end
def destroy
if current_user.id == set_user.id
set_user.destroy
session[:user_id] = nil
redirect_to root_path
else
set_user.destroy
redirect_to users_path
end
end
private
def user_params
params.require(:user).permit(:email, :password)
end
def set_user
#user = User.find(params[:id])
end
end
My sessions controller:
class SessionsController < ApplicationController
skip_before_action :login?, except: [:destroy]
skip_before_action :already_logged_in?, only: [:destroy]
skip_before_action :not_authorized
def new
end
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to user_path(user.id), notice: 'You are now successfully logged in.'
else
flash.now[:alert] = 'Email or Password is Invalid'
render :new
end
end
def destroy
session[:user_id] = nil
redirect_to root_path, notice: 'You have successfully logged out'
end
end
The login/logout function works, no problem there.
I started off by implementing a not_authorized method in the main application controller which by default prevents users from accessing the respective actions if the user role is not equal to 1.
def not_authorized
return if current_user.nil?
redirect_to users_path, notice: 'Not Authorized' unless current_user.role == 1
end
the problem is that I would like to make this editable. So users with role = 1 are able to edit each user's access authorization, if that makes sense.
How would I go about developing this further? I also do not want to use gems, as the sole purpose of this is for me to learn.
Any insights are appreciated. Thank you!
The basics of an authorization system is an exception class:
# app/errors/authorization_error.rb
class AuthorizationError < StandardError; end
And a rescue which will catch when your application raises the error:
class ApplicationController < ActionController::Base
rescue_from 'AuthorizationError', with: :deny_access
private
def deny_access
# see https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses
redirect_to '/somewhere', status: :forbidden
end
end
This avoids repeating the logic all over your controllers while you can still override the deny_access method in subclasses to customize it.
You would then perform authorization checks in your controllers:
class ThingsController
before_action :authorize!, only: [:update, :edit, :destroy]
def create
#thing = current_user.things.new(thing_params)
if #thing.save
redirect_to :thing
else
render :new
end
end
# ...
private
def authorize!
#thing.find(params[:id])
raise AuthorizationError unless #thing.user == current_user || current_user.admin?
end
end
In this pretty typical scenario anybody can create a Thing, but the users can only edit things they have created unless they are admins. "Inlining" everything like this into your controllers can quickly become an unwieldy mess through as the level of complexity grows - which is why gems such as Pundit and CanCanCan extract this out into a separate layer.
Creating a system where the permissions are editable by users of the application is several degrees of magnitude harder to both conceptualize and implement and is really beyond what you should be attempting if you are new to authorization (or Rails). You would need to create a separate table to hold the permissions:
class User < ApplicationRecord
has_many :privileges
end
class Privilege < ApplicationRecord
belongs_to :thing
belongs_to :user
end
class ThingsController
before_action :authorize!, only: [:update, :edit, :destroy]
# ...
private
def authorize!
#thing.find(params[:id])
raise AuthorizationError unless owner? || admin? || privileged?
end
def owner?
#thing.user == current_user
end
def admin?
current_user.admin?
end
def privileged?
current_user.privileges.where(
thing: #thing,
name: params[:action]
)
end
end
This is really a rudimentary Role-based access control system (RBAC).
i have this routes:
Rails.application.routes.draw do
root 'login#new'
get '/home/inicio', to: 'home#index'
scope '/login' do
get '/acesso', to:'login#new'
post '/acessorecebendo', to:'login#create', as:'user'
get '/sair', to:'login#destroy'
end
resources :login
resources :home
resources :produtos
resources :fornecedors
end
the Login controller:
class LoginController < ApplicationController
protect_from_forgery
def new
if session[:user]
#user = User.find(session[:user])
end
end
def destroy
reset_session
redirect_to "/login/acesso", notice: "VocĂȘ foi deslogado"
end
def create
user = User.validate(login_params[:email], login_params[:senha])
if user
session[:user] = user.id
redirect_to "/home/inicio", notice: "login feito com sucesso"
else
redirect_to "/login/acesso", notice: "Dados incorretos"
end
end
private
def login_params
params.require(:login).permit(:email, :senha)
end
end
The home controller:
class HomeController < ApplicationController protect_from_forgery with: :exception
def new
#user = User.find_by(id: session[:user]) end
def index
#produtos = Produto.all
render 'inicio' end
def show
if session[:user]
#user = User.find(session[:user])
end end end
I'm getting an error on the Home view (new.html.erb):
<header>
<h2>Bem-vindo <%= #user.nome %></h2>
<nav>
undefined method `nome' for nil:NilClass
Why i have some problems with the session? I can do the login and i wanna see the user informations of this session on the redirected page, like if i can pass the #user variable assigned on the login action to the home controller to use it.
This is happening because your #user is being set only in index and show, but you are trying to reference it from the new action.
Consider moving this logic to a before_action
class HomeController < ApplicationController
before_action if: ->{ session[:user] } do
#user = User.find_by(id: session[:user])
end
end
If this controller needs to assume that #user is present, you should also have a before_action that handles the case of a missing user account. I usually put this behavior into a AuthenticatedController class and inherit from it where needed.
User.find is not optimal here, because it will throw an exception if no record is found.
I have a user model which uses Devise for authentication and also have an administrator model, which also uses Devise.
I want administrators to be able to edit users profile via administrators/users/{user.id}/edit, however I want this process to be done through Devise Controllers, therefore I tried to inherit from the Users::RegistrationsController as shown below:
class Administrators::UsersController < Users::RegistrationsController
before_action :set_user, only: [:show,:edit,:update,:destroy]
def index
#users=User.all
end
def show
end
def new
super
end
def update
#user.update(user_params)
redirect_to [:administrators,:users]
end
but I get the following error:
Could not find devise mapping for path "/administrators/users". This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: #request.env["devise.mapping"] = Devise.mappings[:user]
I tried to change the routes but I still get the same error.
Could you please help me?
Inheriting from Devise::RegistrationsController may initially seem like a good idea from a code reuse standpoint but it really not a very good idea.
The intent of the controllers is very different - Devise::RegistrationsController partially deals with an un-authenicated user - and the Devise controllers are scary beasts due to the amount of flexibility built in Devise.
Instead you should just setup a plain old CRUD controller as the task at hand is not very complex compared to clobbering over half of Devise::RegistrationsController.
# config/routes.rb
namespace :administrators do
resources :users
end
# app/controllers/administrators/base_controller.rb
module Administrators
class AuthorizationError < StandardError; end
class BaseController
respond_to :html
before_action :authenticate_user!
# Replace with the lib of your choice such as Pundit or CanCanCan
before_action :authorize_user!
rescue_from AuthorizationError, with: :unauthorized
private
def authorize_user!
raise AuthorizationError and return unless current_user.admin?
end
def unauthorized
redirect_to new_session_path, alert: 'You are not authorized.'
end
end
end
class Administrators::UsersController < Administrators::BaseController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def show
end
def index
#users = User.all
end
def new
#user = User.new
end
def create
#user = User.create(user_params)
respond_with(:administrators, #user)
end
def edit
end
def update
#user.update(user_params)
respond_with(:administrators, #user)
end
def destroy
#user.destroy
respond_with(:administrators, #user)
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
Instead you may want to focus on reusing the views through partials for example.
See:
ActionController::Responder
Pundit
CanCanCan
When my user signs up, it originally gets redirected to its blank profile page.
However, I need the user to be redirected to a additional info page in order to retrieve more information
My users controller looks like this
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
def additional_info
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
UserMailer.welcome_email(#user).deliver
sign_in #user
redirect_to users: 'additional_info'
flash[:success] = "Welcome to InYourShoes!"
return #user
else
render'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
end
As you can see, additional_info is the other page I'm trying to redirect to. I'm aware that I create 2 users objects, but I'm not sure if its correct. Frankly speaking I'm kind of lost.
my routes for the pages is this:
resources :users
resources :sessions, only: [:new, :create, :destroy]
match '/additionalinfo',to: 'users#additional_info', via: 'get'
Thanks for the help!
in yours routes
match '/additionalinfo',to: 'users#additional_info', via: 'get', as: :additional_info
in controller
redirect_to additional_info_path
Alternatively, you can change the redirect line to:
redirect_to action: 'additional_info'
Assuming you have the action defined in your routes:
get :additional_info, to: 'users#additional_info' # use get rather than match
I am implementing blog app in ruby on rails where I want to restrict normal user( only admin can create) from creating new articles. For this purpose, I have put befor_filter in articles_controller.rb file which is following. I have hided create button from user in UI but still normal user can create new article by typing in address bar of browser.By using below code, normal user can not go on new article page but it gives me "undefined method `is_admin? when i type in address bar. For more info, I have implemented devise for user authentication.
class ArticlesController < ApplicationController
before_filter :is_user_admin, only: [:new, :create]
def is_user_admin
unless current_user.is_admin?
:root
return false
end
end
end
class ArticlesController < ApplicationController
before_filter :is_user_admin, only: [:new, :create]
def is_user_admin
unless current_user.is_admin?
:root
return false
end
end
def index
#articles = Article.all(:order => "created_at DESC")
end
def show
#article = Article.find(params[:id])
end
def new
#article = Article.new
end
def create
#article = Article.new(params[:article])
#article.user_id = current_user.id
#article.save
redirect_to article_path(#article)
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to action: 'index'
end
def edit
#article = Article.find(params[:id])
end
def update
#article = Article.find(params[:id])
#article.update_attributes(params[:article])
flash.notice = "Article '#{#article.title}' Updated!"
redirect_to article_path(#article)
end
end
applicaiton_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(user)
if current_user.is_admin?
dashboard_index_path
else
:root
end
end
end
Basically, I want to restrict normal user (other than admin) to create , update or delete articles either from UI(this is done) or typing address in address bar.
I have no idea why i am getting this and what can i do to avoid this. Should i write above method in application_controller.rb file.
You propably want to redirect users to login so they can't access the action in your controller, if they're not admins. Hence, you could do something like this:
def is_user_admin
redirect_to(action: :index) unless current_user.try(:is_admin?)
end
Your current_user is nil apparently.
You should put before_filter :authenticate_user!, :except => [:show, :index] at the top of your controller in order to authenticate user.
Make sure that at least there is an user before checking for the permission. You can do that adding this code to every controller that requires an authentication:
before_filter :authenticate_user!
Doing this, you will always have a current user and hence will be able to check for its permission the way you pointed on your question.