2012-04-08 8 views
4

私のWebアプリケーションでは、登録ユーザーは新しいコンテンツを追加して後で編集することができます。私はコンテンツの作者だけが編集できるようにしたい。ログに記録されたユーザーが作成者と同じかどうかを確認するすべてのアクションメソッドにコードを手動で記述する以外に、これを行うにはスマートな方法がありますか?コントローラ全体に使用できる属性MVC 3 - 特定のユーザーのみのアクセス

+3

コントローラやアクション属性は、個々のポストのコンテキストを持っていないでしょう一般的には誰がログインしたのかということです。あなたはそれを世話するだろう属性を探す上でアクションを作っている投稿と作者を比較する方が良いです。 –

答えて

6

コントローラ全体に使用できる属性はありますか?

はい、カスタム1でAuthorizeの属性を拡張することができます:

public class AuthorizeAuthorAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     { 
      // the user is either not authenticated or 
      // not in roles => no need to continue any further 
      return false; 
     } 

     // get the currently logged on user 
     var username = httpContext.User.Identity.Name; 

     // get the id of the article that he is trying to manipulate 
     // from the route data (this assumes that the id is passed as a route 
     // data parameter: /foo/edit/123). If this is not the case and you 
     // are using query string parameters you could fetch the id using the Request 
     var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; 

     // Now that we have the current user and the id of the article he 
     // is trying to manipualte all that's left is go ahead and look in 
     // our database to see if this user is the owner of the article 
     return IsUserOwnerOfArticle(username, id); 
    } 

    private bool IsUserOwnerOfArticle(string username, string articleId) 
    { 
     throw new NotImplementedException(); 
    } 
} 

、その後:

[HttpPost] 
[AuthorizeAuthor] 
public ActionResult Edit(int id) 
{ 
    ... perform the edit 
} 
0

私はなります

  1. 保存db.aspnet_Users colummユーザーID(GUID)コンテンツレコード
  2. に対して保存されたコンテンツ利用者のGuidに対してGUID現在のユーザーを確認し、あなたのコンテンツモデルの拡張メソッドを書きます
  3. 私はこの機能を管理ログインに上書きするコードを書いています(私は管理者ロールを作成します)。
関連する問題