bla*_*zoo 4 authorization ruby-on-rails cancan
您好我实际上正在使用Ryan'Bates cancan gem授权使我的应用程序的用户只管理他们创建的数据.我正在使用Sorcery gem来处理身份验证.
车型/ ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user
can :manage, Profile, :user_id => user.id
can :manage, Album, :user_id => user.id
end
end
end
Run Code Online (Sandbox Code Playgroud)
控制器/ albums_controllers.rb
# -*- encoding : utf-8 -*-
class AlbumsController < ApplicationController
# Authentification before accessing Albums
before_filter :require_login, :except => [:not_authenticated]
load_and_authorize_resource
def index
@albums = Album.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @albums }
end
end
def show
@album = Client.find(params[:id])
authorize! :show, @album
respond_to do |format|
format.html # show.html.erb
format.json { render json: @album }
end
end
def new
@album = Album.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @album }
end
end
def edit
@album = Album.find(params[:id])
authorize! :edit, @album
end
def create
@album = Album.new(params[:album])
respond_to do |format|
if @album.save
format.html { redirect_to @album, notice: 'album was successfully created.' }
format.json { render json: @album, status: :created, location: @album }
else
format.html { render action: "new" }
format.json { render json: @album.errors, status: :unprocessable_entity }
end
end
end
def update
@album = Album.find(params[:id])
authorize! :update, @album
respond_to do |format|
if @album.update_attributes(params[:album])
format.html { redirect_to @album, notice: 'Album was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: @album.errors, status: :unprocessable_entity }
end
end
end
def destroy
@album = Album.find(params[:id])
@album.destroy
respond_to do |format|
format.html { redirect_to albums_url }
format.json { head :ok }
end
end
end
Run Code Online (Sandbox Code Playgroud)
但在此之后,用户仍然可以操作其他用户的数据.我不想做什么.
load_and_authorize_resource自动为您提供@albums(因此无需再次设置它index.所以在以下内容中:
def index
@albums = Album.all
.....# some code
end
Run Code Online (Sandbox Code Playgroud)
@albums正在再次加载所有专辑,这就是它显示所有专辑的原因.你可以用这个代替:
def index
@albums = Album.accessible_by(current_ability)
.....# some code
end
Run Code Online (Sandbox Code Playgroud)
但即使这样也不需要load_and_authorize_resource填充@albums当前用户的正确相册.所以以下就足够了:
def index
.....# some code
end
Run Code Online (Sandbox Code Playgroud)
会给你相同的结果.这是康康的力量.而且load_and_authorize_resource,您可以使用authorize_resource或load_resourse单独使用.更多细节在这里
| 归档时间: |
|
| 查看次数: |
1738 次 |
| 最近记录: |