Devise Admin
& Devise User
; 我想要实现的目标:
registerable
未被删除,因此他只能编辑页面我有什么
路线:
Rails.application.routes.draw do root :to => 'dashboard#index'
devise_for :users, controllers: { registrations: 'user_registrations' }
devise_for :admins, controllers: { registrations: 'admin_registrations' }
get 'dashboard/index'
namespace :admin do
root 'dashboard#index'
resources :users
end
user_registration_controller:
class UserRegistrationsController < Devise::RegistrationsController
end
users_controller:
class UsersController < ApplicationController
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def edit
end
def create
@user = User.new(user_params)
respond_to do |format|
if @guest.save
format.html { redirect_to users_path }
else
format.html { render :new }
end
end
end
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user }
else
format.html { render :edit }
end
end
end
def destroy
user = User.find(params[:id])
user.destroy
redirect_to users_path
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
+我有用户视图,因为它们在普通的脚手架中。
=&GT;通过此设置,任何人都可以创建用户
如何解决问题的任何想法?..
答案 0 :(得分:0)
不要在Devise中使用单独的用户类,而是使用角色。 Devise只是真正用来验证一个单独的类,而你可以破解它使用两个类乱七八糟。您必须覆盖从会话中序列化/解除序列化用户的所有逻辑,以便设计知道它是否应该加载Admin或User类。
由于您将授权问题下载到身份验证层,因此它也是一个糟糕的解决方案。设计工作是验证用户是谁/他声称是谁,这不是一件小事。另一方面,授权是关于用户可以做什么的规则。 &#34;只有管理员可以创建用户&#34;是一个明确的授权规则。
最简单的基于角色的授权可能是这样的:
class AddRoleToUser < ActiveRecord::Migration
def change
add_column :users, :role, :integer, default: 0
add_index :users, :role
end
end
class User
# ...
enum role: [:visitor, :admin]
end
我们使用enum作为单个位掩码列来存储用户角色。将它声明为枚举列也为我们提供了一些免费的方法:
user.visitor?
user.admin?
user.admin!
所以我们创建一个基本的授权检查:
def create
unless current_user.admin?
redirect_to root_path, status: 401, error: 'You are not authorized to perform this action' and return
end
# ...
end
但我们不想在每次要授权时重复这一点,所以让我们清理一下:
class AuthorizationError < StandardError; end
class ApplicationController
rescue_from AuthorizationError, with: :deny_access!
private
def authorize_admin!
raise AuthorizationError, unless current_user.admin?
end
def deny_access!
redirect_to root_path,
status: 401,
error: 'You are not authorized to perform this action'
end
end
然后,我们可以使用过滤器设置控制器,以在执行操作之前检查授权:
class UsersController < ApplicationController
before_action :authorize_admin!, except: [:show]
# ...
end
然而,您可能希望查看Pundit或CanCanCan这些具有优秀社区的可靠授权库,而不是重新发明轮子。您还可以查看Rolify。