2012-07-26 77 views
1

我有一個普遍的問題...阻止用戶訪問其他用戶帳戶

我已經使用Michael Hartl的教程示例構建了我的用戶模型。我遇到的問題是改變網址,並提供其他用戶信息。我使用Friendly_id,它改變了id - >名稱,但如果我將頂部的名稱更改爲另一個用戶,它將顯示其主頁。我想限制我的用戶能夠做到這一點。

這可能沒有實施Devise或CanCan或這樣的嗎?試圖拋出一個驗證,檢查用戶是否嘗試更改url欄上的名稱,即檢查名稱是否是當前登錄的用戶,如果不是,則重定向回當前用戶。

如果您需要模型信息,請告訴我。

TIA

回答

2

您可以在UsersController是驗證這種情況下像這樣把一個before_filter

# Each time you make an action on your UsersController this filter will run 
before_filter :validate_url_hack 

def validate_url_hack 
    # Check the params hash to see if the passed :id matches the current user's id 
    # (note the .to_i on params[:id], as you are comparing against a Fixnum) 
    unless params[:id].to_i == current_user.id 
    # This line redirects the user to the previous action 
    redirect_to request.referer 
    end 
end 

這只是一個猜測,但我相信,這樣的事情應該工作。

+0

更好的是,建立你的關係,所以你可以像這樣調用範圍:'@account = current_user.accounts.find(params [:id])' – Unixmonkey 2012-07-26 20:28:34

+0

所以(對不起,我是新手)...創建一個ACCOUNT模型,在用戶模型has_one:account和def show中應用爲@account = current_user.accounts.find(params [:id])? – RubyNewbie 2012-07-26 20:39:35

+0

我的當前設置會驗證用戶是否是管理員,之後會顯示他們的「顯示」頁面。但如果我去url並更改名稱,它也會呈現該用戶的「顯示」頁面。用戶無法訪問其他「顯示」頁面以外的任何內容。 (如果有意義的話) – RubyNewbie 2012-07-26 20:41:03

2

所有你想要限制特定用戶應該有一個belong_to關聯到你的用戶模式,讓你的控制器,你做

current_user.cars 

,你永遠不應該通過用戶ID的模型URL。這個assusmes你正在使用設計。

+0

不使用設計或任何「登錄」寶石。 – RubyNewbie 2012-07-26 20:48:01