我在Rails中使用了cancan
gem,但這可能比這更普遍。應用程序邏輯與授權
簡短介紹。在cancan
,你定義授權這樣的:
can :read, Post
can :manage, Post if user.is_admin?
can :manage, Post do |post| post.author == user end
這意味着,任何人都可以閱讀Post
S,但只有作者和管理員可以管理(編輯/銷燬)他們。
現在我想更改我的應用程序邏輯,以便如果它有任何評論(除非您是管理員),則不能刪除您的帖子。它仍然易於使用(添加在上面代碼的結尾)cancan
:
cannot :destroy, Post do |post| post.comments.count > 0 && !user.is_admin? end
,這意味着我可以使用下面的僞碼的視圖(HTML模板):
<h1><%=post.title%></h1>
<p><%=post.text%></p>
<%=link_to 'Edit', edit_post_path(post) if can? :edit, post%>
<%=link_to 'Delete', delete_post_path(post) if can? :destroy, post%>
我唯一的問題是將權限本身與應用邏輯混合起來是否合理?感覺那種骯髒的,但另一方面我需要打破乾燥,與應用程序中到處重複檢查(前端,API等)
<h1><%=post.title%></h1>
<p><%=post.text%></p>
<%=link_to 'Edit', edit_post_path(post) if post.can_be_edited? && can? :edit, post%>
<%=link_to 'Delete', delete_post_path(post) if post.can_be_destroyed? && can? :destroy, post %>