forked from asquared/authenticates_access
-
Notifications
You must be signed in to change notification settings - Fork 1
/
README
86 lines (62 loc) · 2.59 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
AuthenticatesAccess
===================
AuthenticatesAccess can be used to implement model-based authentication and
authorization features in your application. It is based around the concept
of "accessors", or model objects which are used as tokens to access other
model objects. Accessors might be users, groups, or sessions.
AuthenticatesAccess allows the use of methods within the accessors or within
the accessed objects to determine whether certain actions should be allowed.
Example
=======
Models need to define the access restrictions which will apply. If the concept
of "ownership" is to be used, it is necessary to define which attribute
refers to the object's owner. The owner should fill the role of accessor
in the application.
class User < ActiveRecord::Base
# user has an is_admin attribute
# don't let non-admins change the is_admin attribute
authenticates_writes_to :is_admin, :with_accessor_method => :is_admin
# allow users to save their own profile
authenticates_saves :with => :allow_owner
# allow admins to save the profile as well
authenticates_saves :with_accessor_method => :is_admin
# note that ownership doesn't confer all privileges!
# has_owner :self means that the accessor's ID will be compared
# with this object's own ID for the allow_owner test.
has_owner :self
# also, allow admins to save any user profile
authenticates_saves :with_accessor_method => :is_admin
end
class Comment < ActiveRecord::Base
belongs_to :user
# allow users to edit their own comments (but not others)
# has_owner :user means that user.id will be compared to accessor.id
# for the allow_owner test to pass.
has_owner :user
# register the ownership test for any saves
authenticates_saves :with => :allow_owner
# this will also allow admins to edit any comments
authenticates_saves :with_accessor_method => :is_admin
# this makes the creating user the owner of the comment
autosets_owner_on_create
end
The application controller should set an accessor to be used:
class ApplicationController < ActionController::Base
before_filter :setup_accessor
protected
def setup_accessor
ActiveRecord::Base.accessor = logged_in_user
end
def logged_in_user
User.find(session[:user_id])
end
end
The views may use methods to determine which attributes may currently
be written, or whether the object may be modified at all.
<% if @user.allowed_to_save(:is_admin) %>
<%= f.check_box :is_admin %>
<% end %>
<% if user.allowed_to_save %>
<%= link_to 'Edit', edit_user_path(user) %>
<% end %>
Copyright (c) 2009 Andrew H. Armenia, released under the MIT license.