jcnetdev-restful-authentication 1.0.20080704

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. data/CHANGELOG +68 -0
  2. data/README +176 -0
  3. data/Rakefile +22 -0
  4. data/TODO +15 -0
  5. data/generators/authenticated/USAGE +1 -0
  6. data/generators/authenticated/authenticated_generator.rb +478 -0
  7. data/generators/authenticated/lib/insert_routes.rb +50 -0
  8. data/generators/authenticated/templates/_model_partial.html.erb +8 -0
  9. data/generators/authenticated/templates/activation.html.erb +3 -0
  10. data/generators/authenticated/templates/authenticated_system.rb +187 -0
  11. data/generators/authenticated/templates/authenticated_test_helper.rb +22 -0
  12. data/generators/authenticated/templates/controller.rb +43 -0
  13. data/generators/authenticated/templates/helper.rb +2 -0
  14. data/generators/authenticated/templates/login.html.erb +16 -0
  15. data/generators/authenticated/templates/mailer.rb +25 -0
  16. data/generators/authenticated/templates/migration.rb +26 -0
  17. data/generators/authenticated/templates/model.rb +69 -0
  18. data/generators/authenticated/templates/model_controller.rb +86 -0
  19. data/generators/authenticated/templates/model_helper.rb +93 -0
  20. data/generators/authenticated/templates/model_helper_spec.rb +158 -0
  21. data/generators/authenticated/templates/observer.rb +11 -0
  22. data/generators/authenticated/templates/signup.html.erb +19 -0
  23. data/generators/authenticated/templates/signup_notification.html.erb +8 -0
  24. data/generators/authenticated/templates/site_keys.rb +38 -0
  25. data/generators/authenticated/templates/spec/controllers/access_control_spec.rb +90 -0
  26. data/generators/authenticated/templates/spec/controllers/authenticated_system_spec.rb +101 -0
  27. data/generators/authenticated/templates/spec/controllers/sessions_controller_spec.rb +139 -0
  28. data/generators/authenticated/templates/spec/controllers/users_controller_spec.rb +198 -0
  29. data/generators/authenticated/templates/spec/fixtures/users.yml +60 -0
  30. data/generators/authenticated/templates/spec/helpers/users_helper_spec.rb +141 -0
  31. data/generators/authenticated/templates/spec/models/user_spec.rb +290 -0
  32. data/generators/authenticated/templates/stories/rest_auth_stories.rb +22 -0
  33. data/generators/authenticated/templates/stories/rest_auth_stories_helper.rb +81 -0
  34. data/generators/authenticated/templates/stories/steps/ra_navigation_steps.rb +49 -0
  35. data/generators/authenticated/templates/stories/steps/ra_resource_steps.rb +179 -0
  36. data/generators/authenticated/templates/stories/steps/ra_response_steps.rb +171 -0
  37. data/generators/authenticated/templates/stories/steps/user_steps.rb +153 -0
  38. data/generators/authenticated/templates/stories/users/accounts.story +186 -0
  39. data/generators/authenticated/templates/stories/users/sessions.story +134 -0
  40. data/generators/authenticated/templates/test/functional_test.rb +88 -0
  41. data/generators/authenticated/templates/test/mailer_test.rb +31 -0
  42. data/generators/authenticated/templates/test/model_functional_test.rb +99 -0
  43. data/generators/authenticated/templates/test/unit_test.rb +164 -0
  44. data/init.rb +1 -0
  45. data/lib/authentication.rb +43 -0
  46. data/lib/authentication/by_cookie_token.rb +85 -0
  47. data/lib/authentication/by_password.rb +65 -0
  48. data/lib/authorization.rb +15 -0
  49. data/lib/authorization/aasm_roles.rb +64 -0
  50. data/lib/authorization/stateful_roles.rb +63 -0
  51. data/lib/trustification.rb +15 -0
  52. data/lib/trustification/email_validation.rb +20 -0
  53. data/rails/init.rb +3 -0
  54. data/restful-authentication.gemspec +74 -0
  55. metadata +116 -0
@@ -0,0 +1,50 @@
1
+ Rails::Generator::Commands::Create.class_eval do
2
+ def route_resource(*resources)
3
+ resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
4
+ sentinel = 'ActionController::Routing::Routes.draw do |map|'
5
+
6
+ logger.route "map.resource #{resource_list}"
7
+ unless options[:pretend]
8
+ gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
9
+ "#{match}\n map.resource #{resource_list}\n"
10
+ end
11
+ end
12
+ end
13
+
14
+ def route_name(name, path, options = {})
15
+ sentinel = 'ActionController::Routing::Routes.draw do |map|'
16
+
17
+ logger.route "map.#{name} '#{path}', :controller => '#{options[:controller]}', :action => '#{options[:action]}'"
18
+ unless options[:pretend]
19
+ gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
20
+ "#{match}\n map.#{name} '#{path}', :controller => '#{options[:controller]}', :action => '#{options[:action]}'"
21
+ end
22
+ end
23
+ end
24
+ end
25
+
26
+ Rails::Generator::Commands::Destroy.class_eval do
27
+ def route_resource(*resources)
28
+ resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
29
+ look_for = "\n map.resource #{resource_list}\n"
30
+ logger.route "map.resource #{resource_list}"
31
+ gsub_file 'config/routes.rb', /(#{look_for})/mi, ''
32
+ end
33
+
34
+ def route_name(name, path, options = {})
35
+ look_for = "\n map.#{name} '#{path}', :controller => '#{options[:controller]}', :action => '#{options[:action]}'"
36
+ logger.route "map.#{name} '#{path}', :controller => '#{options[:controller]}', :action => '#{options[:action]}'"
37
+ gsub_file 'config/routes.rb', /(#{look_for})/mi, ''
38
+ end
39
+ end
40
+
41
+ Rails::Generator::Commands::List.class_eval do
42
+ def route_resource(*resources)
43
+ resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
44
+ logger.route "map.resource #{resource_list}"
45
+ end
46
+
47
+ def route_name(name, path, options = {})
48
+ logger.route "map.#{name} '#{path}', :controller => '{options[:controller]}', :action => '#{options[:action]}'"
49
+ end
50
+ end
@@ -0,0 +1,8 @@
1
+ <%% if logged_in? -%>
2
+ <div id="<%= file_name %>-bar-greeting">Logged in as <%%= link_to_current_<%= file_name %> :content_method => :login %></div>
3
+ <div id="<%= file_name %>-bar-action" >(<%%= link_to "log out", logout_path, { :title => "Log out" } %>)</div>
4
+ <%% else -%>
5
+ <div id="<%= file_name %>-bar-greeting"><%%= abbr_tag_with_IP 'Not logged in', :style => 'border: none;' %></div>
6
+ <div id="<%= file_name %>-bar-action" ><%%= link_to "Log in", login_path, { :title => "Log in" } %> /
7
+ <%%= link_to "Sign up", signup_path, { :title => "Create an account" } %></div>
8
+ <%% end -%>
@@ -0,0 +1,3 @@
1
+ <%%=h @<%= file_name %>.login %>, your account has been activated. Welcome aboard!
2
+
3
+ <%%=h @url %>
@@ -0,0 +1,187 @@
1
+ module AuthenticatedSystem
2
+ protected
3
+ # Returns true or false if the <%= file_name %> is logged in.
4
+ # Preloads @current_<%= file_name %> with the <%= file_name %> model if they're logged in.
5
+ def logged_in?
6
+ !!current_<%= file_name %>
7
+ end
8
+
9
+ # Accesses the current <%= file_name %> from the session.
10
+ # Future calls avoid the database because nil is not equal to false.
11
+ def current_<%= file_name %>
12
+ @current_<%= file_name %> ||= (login_from_session || login_from_basic_auth || login_from_cookie) unless @current_<%= file_name %> == false
13
+ end
14
+
15
+ # Store the given <%= file_name %> id in the session.
16
+ def current_<%= file_name %>=(new_<%= file_name %>)
17
+ session[:<%= file_name %>_id] = new_<%= file_name %> ? new_<%= file_name %>.id : nil
18
+ @current_<%= file_name %> = new_<%= file_name %> || false
19
+ end
20
+
21
+ # Check if the <%= file_name %> is authorized
22
+ #
23
+ # Override this method in your controllers if you want to restrict access
24
+ # to only a few actions or if you want to check if the <%= file_name %>
25
+ # has the correct rights.
26
+ #
27
+ # Example:
28
+ #
29
+ # # only allow nonbobs
30
+ # def authorized?
31
+ # current_<%= file_name %>.login != "bob"
32
+ # end
33
+ #
34
+ def authorized?(action=nil, resource=nil, *args)
35
+ logged_in?
36
+ end
37
+
38
+ # Filter method to enforce a login requirement.
39
+ #
40
+ # To require logins for all actions, use this in your controllers:
41
+ #
42
+ # before_filter :login_required
43
+ #
44
+ # To require logins for specific actions, use this in your controllers:
45
+ #
46
+ # before_filter :login_required, :only => [ :edit, :update ]
47
+ #
48
+ # To skip this in a subclassed controller:
49
+ #
50
+ # skip_before_filter :login_required
51
+ #
52
+ def login_required
53
+ authorized? || access_denied
54
+ end
55
+
56
+ # Redirect as appropriate when an access request fails.
57
+ #
58
+ # The default action is to redirect to the login screen.
59
+ #
60
+ # Override this method in your controllers if you want to have special
61
+ # behavior in case the <%= file_name %> is not authorized
62
+ # to access the requested action. For example, a popup window might
63
+ # simply close itself.
64
+ def access_denied
65
+ respond_to do |format|
66
+ format.html do
67
+ store_location
68
+ redirect_to new_<%= controller_routing_name %>_path
69
+ end
70
+ # format.any doesn't work in rails version < http://dev.rubyonrails.org/changeset/8987
71
+ # you may want to change format.any to e.g. format.any(:js, :xml)
72
+ format.any do
73
+ request_http_basic_authentication 'Web Password'
74
+ end
75
+ end
76
+ end
77
+
78
+ # Store the URI of the current request in the session.
79
+ #
80
+ # We can return to this location by calling #redirect_back_or_default.
81
+ def store_location
82
+ session[:return_to] = request.request_uri
83
+ end
84
+
85
+ # Redirect to the URI stored by the most recent store_location call or
86
+ # to the passed default. Set an appropriately modified
87
+ # after_filter :store_location, :only => [:index, :new, :show, :edit]
88
+ # for any controller you want to be bounce-backable.
89
+ def redirect_back_or_default(default)
90
+ redirect_to(session[:return_to] || default)
91
+ session[:return_to] = nil
92
+ end
93
+
94
+ # Inclusion hook to make #current_<%= file_name %> and #logged_in?
95
+ # available as ActionView helper methods.
96
+ def self.included(base)
97
+ base.send :helper_method, :current_<%= file_name %>, :logged_in?, :authorized? if base.respond_to? :helper_method
98
+ end
99
+
100
+ #
101
+ # Login
102
+ #
103
+
104
+ # Called from #current_<%= file_name %>. First attempt to login by the <%= file_name %> id stored in the session.
105
+ def login_from_session
106
+ self.current_<%= file_name %> = <%= class_name %>.find_by_id(session[:<%= file_name %>_id]) if session[:<%= file_name %>_id]
107
+ end
108
+
109
+ # Called from #current_<%= file_name %>. Now, attempt to login by basic authentication information.
110
+ def login_from_basic_auth
111
+ authenticate_with_http_basic do |login, password|
112
+ self.current_<%= file_name %> = <%= class_name %>.authenticate(login, password)
113
+ end
114
+ end
115
+
116
+ #
117
+ # Logout
118
+ #
119
+
120
+ # Called from #current_<%= file_name %>. Finaly, attempt to login by an expiring token in the cookie.
121
+ # for the paranoid: we _should_ be storing <%= file_name %>_token = hash(cookie_token, request IP)
122
+ def login_from_cookie
123
+ <%= file_name %> = cookies[:auth_token] && <%= class_name %>.find_by_remember_token(cookies[:auth_token])
124
+ if <%= file_name %> && <%= file_name %>.remember_token?
125
+ self.current_<%= file_name %> = <%= file_name %>
126
+ handle_remember_cookie! false # freshen cookie token (keeping date)
127
+ self.current_<%= file_name %>
128
+ end
129
+ end
130
+
131
+ # This is ususally what you want; resetting the session willy-nilly wreaks
132
+ # havoc with forgery protection, and is only strictly necessary on login.
133
+ # However, **all session state variables should be unset here**.
134
+ def logout_keeping_session!
135
+ # Kill server-side auth cookie
136
+ @current_<%= file_name %>.forget_me if @current_<%= file_name %>.is_a? <%= class_name %>
137
+ @current_<%= file_name %> = false # not logged in, and don't do it for me
138
+ kill_remember_cookie! # Kill client-side auth cookie
139
+ session[:<%= file_name %>_id] = nil # keeps the session but kill our variable
140
+ # explicitly kill any other session variables you set
141
+ end
142
+
143
+ # The session should only be reset at the tail end of a form POST --
144
+ # otherwise the request forgery protection fails. It's only really necessary
145
+ # when you cross quarantine (logged-out to logged-in).
146
+ def logout_killing_session!
147
+ logout_keeping_session!
148
+ reset_session
149
+ end
150
+
151
+ #
152
+ # Remember_me Tokens
153
+ #
154
+ # Cookies shouldn't be allowed to persist past their freshness date,
155
+ # and they should be changed at each login
156
+
157
+ # Cookies shouldn't be allowed to persist past their freshness date,
158
+ # and they should be changed at each login
159
+
160
+ def valid_remember_cookie?
161
+ return nil unless @current_<%= file_name %>
162
+ (@current_<%= file_name %>.remember_token?) &&
163
+ (cookies[:auth_token] == @current_<%= file_name %>.remember_token)
164
+ end
165
+
166
+ # Refresh the cookie auth token if it exists, create it otherwise
167
+ def handle_remember_cookie! new_cookie_flag
168
+ return unless @current_<%= file_name %>
169
+ case
170
+ when valid_remember_cookie? then @current_<%= file_name %>.refresh_token # keeping same expiry date
171
+ when new_cookie_flag then @current_<%= file_name %>.remember_me
172
+ else @current_<%= file_name %>.forget_me
173
+ end
174
+ send_remember_cookie!
175
+ end
176
+
177
+ def kill_remember_cookie!
178
+ cookies.delete :auth_token
179
+ end
180
+
181
+ def send_remember_cookie!
182
+ cookies[:auth_token] = {
183
+ :value => @current_<%= file_name %>.remember_token,
184
+ :expires => @current_<%= file_name %>.remember_token_expires_at }
185
+ end
186
+
187
+ end
@@ -0,0 +1,22 @@
1
+ module AuthenticatedTestHelper
2
+ # Sets the current <%= file_name %> in the session from the <%= file_name %> fixtures.
3
+ def login_as(<%= file_name %>)
4
+ @request.session[:<%= file_name %>_id] = <%= file_name %> ? <%= table_name %>(<%= file_name %>).id : nil
5
+ end
6
+
7
+ def authorize_as(<%= file_name %>)
8
+ @request.env["HTTP_AUTHORIZATION"] = <%= file_name %> ? ActionController::HttpAuthentication::Basic.encode_credentials(<%= table_name %>(<%= file_name %>).login, 'monkey') : nil
9
+ end
10
+
11
+ <% if options[:rspec] -%>
12
+ # rspec
13
+ def mock_<%= file_name %>
14
+ <%= file_name %> = mock_model(<%= class_name %>, :id => 1,
15
+ :login => 'user_name',
16
+ :name => 'U. Surname',
17
+ :to_xml => "<%= class_name %>-in-XML", :to_json => "<%= class_name %>-in-JSON",
18
+ :errors => [])
19
+ <%= file_name %>
20
+ end
21
+ <% end -%>
22
+ end
@@ -0,0 +1,43 @@
1
+ # This controller handles the login/logout function of the site.
2
+ class <%= controller_class_name %>Controller < ApplicationController
3
+ # Be sure to include AuthenticationSystem in Application Controller instead
4
+ include AuthenticatedSystem
5
+
6
+ # render new.rhtml
7
+ def new
8
+ end
9
+
10
+ def create
11
+ logout_keeping_session!
12
+ <%= file_name %> = <%= class_name %>.authenticate(params[:login], params[:password])
13
+ if <%= file_name %>
14
+ # Protects against session fixation attacks, causes request forgery
15
+ # protection if user resubmits an earlier form using back
16
+ # button. Uncomment if you understand the tradeoffs.
17
+ # reset_session
18
+ self.current_<%= file_name %> = <%= file_name %>
19
+ new_cookie_flag = (params[:remember_me] == "1")
20
+ handle_remember_cookie! new_cookie_flag
21
+ redirect_back_or_default('/')
22
+ flash[:notice] = "Logged in successfully"
23
+ else
24
+ note_failed_signin
25
+ @login = params[:login]
26
+ @remember_me = params[:remember_me]
27
+ render :action => 'new'
28
+ end
29
+ end
30
+
31
+ def destroy
32
+ logout_killing_session!
33
+ flash[:notice] = "You have been logged out."
34
+ redirect_back_or_default('/')
35
+ end
36
+
37
+ protected
38
+ # Track failed login attempts
39
+ def note_failed_signin
40
+ flash[:error] = "Couldn't log you in as '#{params[:login]}'"
41
+ logger.warn "Failed login for '#{params[:login]}' from #{request.remote_ip} at #{Time.now.utc}"
42
+ end
43
+ end
@@ -0,0 +1,2 @@
1
+ module <%= controller_class_name %>Helper
2
+ end
@@ -0,0 +1,16 @@
1
+ <h1>Log In</h1>
2
+
3
+ <%% form_tag <%= controller_routing_name %>_path do -%>
4
+ <p><label for="login">Login</label><br/>
5
+ <%%= text_field_tag 'login', @login %></p>
6
+
7
+ <p><label for="password">Password</label><br/>
8
+ <%%= password_field_tag 'password', nil %></p>
9
+
10
+ <!-- Uncomment this if you want this functionality
11
+ <p><label for="remember_me">Remember me:</label>
12
+ <%%= check_box_tag 'remember_me', '1', @remember_me %></p>
13
+ -->
14
+
15
+ <p><%%= submit_tag 'Log in' %></p>
16
+ <%% end -%>
@@ -0,0 +1,25 @@
1
+ class <%= class_name %>Mailer < ActionMailer::Base
2
+ def signup_notification(<%= file_name %>)
3
+ setup_email(<%= file_name %>)
4
+ @subject += 'Please activate your new account'
5
+ <% if options[:include_activation] %>
6
+ @body[:url] = "http://YOURSITE/activate/#{<%= file_name %>.activation_code}"
7
+ <% else %>
8
+ @body[:url] = "http://YOURSITE/login/" <% end %>
9
+ end
10
+
11
+ def activation(<%= file_name %>)
12
+ setup_email(<%= file_name %>)
13
+ @subject += 'Your account has been activated!'
14
+ @body[:url] = "http://YOURSITE/"
15
+ end
16
+
17
+ protected
18
+ def setup_email(<%= file_name %>)
19
+ @recipients = "#{<%= file_name %>.email}"
20
+ @from = "ADMINEMAIL"
21
+ @subject = "[YOURSITE] "
22
+ @sent_on = Time.now
23
+ @body[:<%= file_name %>] = <%= file_name %>
24
+ end
25
+ end
@@ -0,0 +1,26 @@
1
+ class <%= migration_name %> < ActiveRecord::Migration
2
+ def self.up
3
+ create_table "<%= table_name %>", :force => true do |t|
4
+ t.column :login, :string, :limit => 40
5
+ t.column :name, :string, :limit => 100, :default => '', :null => true
6
+ t.column :email, :string, :limit => 100
7
+ t.column :crypted_password, :string, :limit => 40
8
+ t.column :salt, :string, :limit => 40
9
+ t.column :created_at, :datetime
10
+ t.column :updated_at, :datetime
11
+ t.column :remember_token, :string, :limit => 40
12
+ t.column :remember_token_expires_at, :datetime
13
+ <% if options[:include_activation] -%>
14
+ t.column :activation_code, :string, :limit => 40
15
+ t.column :activated_at, :datetime<% end %>
16
+ <% if options[:stateful] -%>
17
+ t.column :state, :string, :null => :no, :default => 'passive'
18
+ t.column :deleted_at, :datetime<% end %>
19
+ end
20
+ add_index :<%= table_name %>, :login, :unique => true
21
+ end
22
+
23
+ def self.down
24
+ drop_table "<%= table_name %>"
25
+ end
26
+ end
@@ -0,0 +1,69 @@
1
+ require 'digest/sha1'
2
+
3
+ class <%= class_name %> < ActiveRecord::Base
4
+ include Authentication
5
+ include Authentication::ByPassword
6
+ include Authentication::ByCookieToken
7
+ <% if options[:aasm] -%>
8
+ include Authorization::AasmRoles
9
+ <% elsif options[:stateful] -%>
10
+ include Authorization::StatefulRoles<% end %>
11
+ validates_presence_of :login
12
+ validates_length_of :login, :within => 3..40
13
+ validates_uniqueness_of :login, :case_sensitive => false
14
+ validates_format_of :login, :with => RE_LOGIN_OK, :message => MSG_LOGIN_BAD
15
+
16
+ validates_format_of :name, :with => RE_NAME_OK, :message => MSG_NAME_BAD, :allow_nil => true
17
+ validates_length_of :name, :maximum => 100
18
+
19
+ validates_presence_of :email
20
+ validates_length_of :email, :within => 6..100 #r@a.wk
21
+ validates_uniqueness_of :email, :case_sensitive => false
22
+ validates_format_of :email, :with => RE_EMAIL_OK, :message => MSG_EMAIL_BAD
23
+
24
+ <% if options[:include_activation] && !options[:stateful] %>before_create :make_activation_code <% end %>
25
+
26
+ # HACK HACK HACK -- how to do attr_accessible from here?
27
+ # prevents a user from submitting a crafted form that bypasses activation
28
+ # anything else you want your user to change should be added here.
29
+ attr_accessible :login, :email, :name, :password, :password_confirmation
30
+
31
+ <% if options[:include_activation] && !options[:stateful] %>
32
+ # Activates the user in the database.
33
+ def activate!
34
+ @activated = true
35
+ self.activated_at = Time.now.utc
36
+ self.activation_code = nil
37
+ save(false)
38
+ end
39
+
40
+ def active?
41
+ # the existence of an activation code means they have not activated yet
42
+ activation_code.nil?
43
+ end<% end %>
44
+
45
+ # Authenticates a user by their login name and unencrypted password. Returns the user or nil.
46
+ #
47
+ # uff. this is really an authorization, not authentication routine.
48
+ # We really need a Dispatch Chain here or something.
49
+ # This will also let us return a human error message.
50
+ #
51
+ def self.authenticate(login, password)
52
+ u = <% if options[:stateful] %>find_in_state :first, :active, :conditions => {:login => login}<%
53
+ elsif options[:include_activation] %>find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login]<%
54
+ else %>find_by_login(login)<% end %> # need to get the salt
55
+ u && u.authenticated?(password) ? u : nil
56
+ end
57
+
58
+ protected
59
+
60
+ <% if options[:include_activation] -%>
61
+ def make_activation_code
62
+ <% if options[:stateful] -%>
63
+ self.deleted_at = nil
64
+ <% end -%>
65
+ self.activation_code = self.class.make_token
66
+ end
67
+ <% end %>
68
+
69
+ end