2013-04-28 32 views
0

我正在使用設備用於用戶認證的軌。我可以創建新的用戶帳戶並能夠登錄。但是,一旦我使用帳戶登錄,則可以通過更改用戶url來登錄其他帳戶。與設計軌 - 登錄後能夠訪問其他帳戶

例如:Supose我成功登錄成爲用戶1,然後我被重定向到http://www.example.com/users/1。現在,如果我將url更改爲http://www.example.com/users/2,那麼我可以查看用戶2的帳戶詳細信息等等。我如何禁止登錄的用戶訪問其他帳戶詳細信息?

使用rails 3.2.13和devise 2.2.3。

回答

0

設計通常不會自己處理授權,只有驗證。也就是說,它可以要求一些用戶登錄才能訪問資源,但不檢查資源屬於特定用戶(這是故意的 - 哪些資源是可以訪問由用戶是複雜的,取決於在您的應用程序。這是一個驗證工具的範圍之外的問題)。

您需要實施某種授權系統 - 我強烈建議使用CanCan gem - 它可以與Devise輕鬆集成,並且很容易配置您的應用需要的任何授權邏輯。有一個體面的RailsCast on CanCan(不令人驚訝,因爲RailsCasts和CanCan都是由同一個人)。

+0

謝謝你的澄清。我一定會考慮CanCan。 – sthustfo 2013-04-29 11:38:28

+0

如果有任何使用CanCan的實時應用程序,請讓我知道嗎?我想我需要了解各種角色的概念?對於例如:在我的應用程序,我應該如何創建「管理員」 previliges /角色的用戶,而不是「正常」角色的用戶。 – sthustfo 2013-04-30 06:38:15

0

設計只處理認證,而不是授權。它確保有一個current_user,但不是該用戶是否應該查看特定資源。

CanCan就像一個很好的全面授權解決方案。你可以在Ruby Toolbox找到更多。

但是對於一些快速和骯髒的,你可以做這樣的事情在你的users_controller:

before_filter :get_user, :user_views_only_own_records 

def get_user 
    @user = User.find_by_id(params[:id]) 
    head :404 if @user.nil? 
end 

def user_views_only_own_records 
    if @user.id != current_user.id 
    head :403 # or whatever you want to do when someone tries to peek at another user 
    end 
end 

但在某些時候,你會希望允許管理員查看任何用戶,或其他類似的情況,和一旦你開始爲不同的角色定義不同的訪問級別,你會希望CanCan或類似的東西使它更容易。

+0

感謝您的澄清。我接受@MrTheWalrus的回答只是因爲他早於你回答。 – sthustfo 2013-04-29 11:39:46

0

假設你有像一個profiles_controller,該指數在用戶的配置文件中的信息,您可以執行以下操作:

class ProfilesController < ApplicationController 
before_filter :authenticate_user! # Provided by Devise 
before_filter :find_user  
before_filter :ensure_proper_user 

def index 
....stuff 
end 

private 
def find_user 
    @user = User.find_by_profile_name(params[:profile_name]) 
end 

def ensure_proper_user 
    if current_user != @user 
    flash[:error] = "You do not have premission to do that." 
    redirect_to root_path 
    end 
end 
相關問題