changed properties and the name of hyperchad to selectricity
[selectricity-live] / vendor / plugins / login_engine / README
1 = Before we start
2
3 This is a Rails Engine version of the Salted Login Generator, a most excellent login system which is sufficient for most simple cases. For the most part, this code has not been altered from its generator form, with the following notable exceptions
4
5 * Localization has been removed.
6 * The 'welcome' page has been changed to the 'home' page
7 * A few new functions have been thrown in
8 * It's... uh.... a Rails Engine now ;-)
9
10 However, what I'm trying to say is that 99.9999% of the credit for this should go to Joe Hosteny, Tobias Luetke (xal) and the folks that worked on the original Salted Login generator code. I've just wrapped it into something runnable with the Rails Engine system.
11
12 Please also bear in mind that this is a work in progress, and things like testing are wildly up in the air... but they will fall into place very soon. And now, on with the show.
13
14
15 = Installation
16
17 Installing the Login Engine is fairly simple.
18
19 Your options are:
20   1.  Install as a rails plugin:
21       $ script/plugin install login_engine
22   2.  Use svn:externals
23       $ svn propedit svn:externals vendor/plugins
24
25       You can choose to use the latest stable release:
26           login_engine http://svn.rails-engines.org/plugins/login_engine
27
28       Or a tagged release (recommended for releases of your code):
29           login_engine http://svn.rails-engines.org/logine_engine/tags/<TAGGED_RELEASE>
30
31 There are a few configuration steps that you'll need to take to get everything running smoothly. Listed below are the changes to your application you will need to make.
32
33 === Setup your Rails application
34
35 Edit your <tt>database.yml</tt>, most importantly! You might also want to move <tt>public/index.html</tt> out of the way, and set up some default routes in <tt>config/routes.rb</tt>.
36
37 === Add configuration and start engine
38
39 Add the following to the bottom of environment.rb:
40
41   module LoginEngine
42     config :salt, "your-salt-here"
43   end
44
45   Engines.start :login
46   
47 You'll probably want to change the Salt value to something unique. You can also override any of the configuration values defined at the top of lib/user_system.rb in a similar way. Note that you don't need to start the engine with <tt>Engines.start :login_engine</tt> - instead, <tt>:login</tt> (or any name) is sufficient if the engine is a directory named <some-name>_engine.
48
49
50 === Add the filters
51
52 Next, edit your <tt>app/controllers/application.rb</tt> file. The beginning of your <tt>ApplicationController</tt> should look something like this:
53
54   require 'login_engine'
55
56   class ApplicationController < ActionController::Base
57     include LoginEngine
58     helper :user
59     model :user
60     
61     before_filter :login_required
62
63 If you don't want ALL actions to require a login, you need to read further below to learn how to restrict only certain actions. 
64
65 Add the following to your ApplicationHelper:
66
67   module ApplicationHelper
68     include LoginEngine
69   end
70
71 This ensures that the methods to work with users in your views are available
72
73 === Set up ActionMailer
74
75 If you want to disable email functions within the Login Engine, simple set the :use_email_notification config flag to false in your environment.rb file:
76
77   module LoginEngine
78     
79     #  ... other options...
80     config :use_email_notification, false
81
82   end
83
84 You should note that retrieving forgotten passwords automatically isn't possible when the email functions are disabled. Instead, the user is presented with a message instructing them to contact the system administrator
85
86 If you wish you use email notifications and account creation verification, you must properly configure ActionMailer for your mail settings. For example, you could add the following in config/environments/development.rb (for a .Mac account, and with your own username and password, obviously):
87
88 ActionMailer::Base.server_settings = {
89   :address => "smtp.mac.com",
90   :port => 25,
91   :domain => "smtp.mac.com",
92   :user_name => "<your user name here>",
93   :password => "<your password here>",
94   :authentication => :login
95 }
96
97 You'll need to configure it properly so that email can be sent. One of the easiest ways to test your configuration is to temporarily reraise exceptions from the signup method (so that you get the actual mailer exception string). In the rescue statement, put a single "raise" statement in. Once you've debugged any setting problems, remove that statement to get the proper flash error handling back.
98
99
100 === Create the DB schema
101
102 After you have done the modifications the the ApplicationController and its helper, you can import the user model into the database. Migration information in login_engine/db/migrate/. 
103
104 You *MUST* check that these files aren't going to interfere with anything in your application. 
105
106 You can change the table name used by adding
107
108   module LoginEngine
109     
110     #  ... other options...
111     config :user_table, "your_table_name"
112
113   end
114
115 ...to the LoginEngine configuration in <tt>environment.rb</tt>. Then run from the root of your project:
116
117   rake db:migrate:engines ENGINE=login
118
119 to import the schema into your database.
120
121
122 == Include stylesheets
123
124 If you want the default stylesheet, add the following line to your layout:
125
126   <%= engine_stylesheet 'login_engine' %>
127   
128 ... somewhere in the <head> section of your HTML layout file.
129
130 == Integrate flash messages into your layout
131
132 LoginEngine does not display any flash messages in the views it contains, and thus you must display them yourself. This allows you to integrate any flash messages into your existing layout. LoginEngine adheres to the emerging flash usage standard, namely:
133
134 * :warning - warning (failure) messages
135 * :notice - success messages
136 * :message - neutral (reminder, informational) messages
137
138 This gives you the flexibility to theme the different message classes separately. In your layout you should check for and display flash[:warning], flash[:notice] and flash[:message]. For example:
139
140   <% for name in [:notice, :warning, :message] %>
141     <% if flash[name] %>
142       <%= "<div id=\"#{name}\">#{flash[name]}</div>" %>
143     <% end %>
144   <% end %>
145
146 Alternately, you could look at using the flash helper plugin (available from https://opensvn.csie.org/traccgi/flash_helper_plugin/trac.cgi/), which supports the same naming convention.
147
148
149 = How to use the Login Engine 
150
151 Now you can go around and happily add "before_filter :login_required" to the controllers which you would like to protect. 
152
153 After integrating the login system with your rails application navigate to your new controller's signup method. There you can create a new account. After you are done you should have a look at your DB. Your freshly created user will be there but the password will be a sha1 hashed 40 digit mess. I find this should be the minimum of security which every page offering login & password should give its customers. Now you can move to one of those  controllers which you protected with the before_filter :login_required snippet. You will automatically be re-directed to your freshly created login controller and you are asked for a password. After entering valid account data you will be taken back to the controller which you requested earlier. Simple huh?
154
155 === Protection using <tt>before_filter</tt>
156
157 Adding the line <tt>before_filter :login_required</tt> to your <tt>app/controllers/application.rb</tt> file will protect *all* of your applications methods, in every controller. If you only want to control access to specific controllers, remove this line from <tt>application.rb</tt> and add it to the controllers that you want to secure.
158
159 Within individual controllers you can restrict which methods the filter runs on in the usual way:
160
161        before_filter :login_required, :only => [:myaccount, :changepassword]
162        before_filter :login_required, :except => [:index]
163
164 === Protection using <tt>protect?()</tt>
165
166 Alternatively, you can leave the <tt>before_filter</tt> in the global <tt>application.rb</tt> file, and control which actions are restricted in individual controllers by defining a <tt>protect?()</tt> method in that controller.
167
168 For instance, in the <tt>UserController</tt> we want to allow everyone access to the 'login', 'signup' and 'forgot_password' methods (otherwise noone would be able to access our site!). So a <tt>protect?()</tt> method is defined in <tt>user_controller.rb</tt> as follows:
169
170   def protect?(action)
171     if ['login', 'signup', 'forgot_password'].include?(action)
172       return false
173     else
174       return true
175     end
176   end
177
178 Of course, you can override this Engine behaviour in your application - see below.
179
180 == Configuration
181
182 The following configuration variables are set in lib/login_engine.rb. If you wish to override them, you should set them BEFORE calling Engines.start (it is possible to set them after, but it's simpler to just do it before. Please refer to the Engine documentation for the #config method for more information).
183
184 For example, the following might appear at the bottom of /config/environment.rb:
185
186   module LoginEngine
187     config :salt, 'my salt'
188     config :app_name, 'My Great App'
189     config :app_url, 'http://www.wow-great-domain.com'
190   end
191   
192   Engines.start
193
194 === Configuration Options
195
196 +email_from+:: The email from which registration/administration emails will appear to 
197                come from. Defaults to 'webmaster@your.company'.
198 +admin_email+:: The email address users are prompted to contact if passwords cannot
199                 be emailed. Defaults to 'webmaster@your.company'.
200 +app_url+:: The URL of the site sent to users for signup/forgotten passwords, etc.
201             Defaults to 'http://localhost:3000/'.
202 +app_name+:: The application title used in emails. Defaults to 'TestApp'.
203 +mail_charset+:: The charset used in emails. Defaults to 'utf-8'.
204 +security_token_life_hours+:: The life span of security tokens, in hours. If a security
205                               token is older than this when it is used to try and authenticate
206                               a user, it will be discarded. In other words, the amount of time
207                               new users have between signing up and clicking the link they
208                               are sent. Defaults to 24 hours.
209 +two_column_input+:: If true, forms created with the UserHelper#form_input method will
210                      use a two-column table. Defaults to true.
211 +changeable_fields+:: An array of fields within the user model which the user
212                       is allowed to edit. The Salted Hash Login generator documentation
213                       states that you should NOT include the email field in this
214                       array, although I am not sure why. Defaults to +[ 'firstname', 'lastname' ]+.
215 +delayed_delete+::  Set to true to allow delayed deletes (i.e., delete of record
216                     doesn't happen immediately after user selects delete account,
217                     but rather after some expiration of time to allow this action
218                     to be reverted). Defaults to false.
219 +delayed_delete_days+:: The time delay used for the 'delayed_delete' feature. Defaults to
220                         7 days.
221 +user_table+:: The table to store User objects in. Defaults to "users" (or "user" if
222                ActiveRecord pluralization is disabled).
223 +use_email_notification+:: If false, no emails will be sent to the user. As a consequence,
224                            users who signup are immediately verified, and they cannot request
225                            forgotten passwords. Defaults to true.
226 +confirm_account+:: An overriding flag to control whether or not user accounts must be
227                     verified by email. This overrides the +user_email_notification+ flag.
228                     Defaults to true.
229
230 == Overriding controllers and views
231
232 The standard home page is almost certainly not what you want to present to your users. Because this login system is a Rails Engine, overriding the default behaviour couldn't be simpler. To change the RHTML template shown for the <tt>home</tt> action, simple create a new file in <tt>RAILS_ROOT/app/views/user/home.rhtml</tt> (you'll probably need to create the directory <tt>user</tt> at the same time). This new view file will be used instead of the one provided in the Login Engine. Easy!
233
234
235 == Tips & Tricks
236
237 How do I...
238
239   ... access the user who is currently logged in
240
241   A: You can get the user object from the session using session[:user]
242      Example: 
243        Welcome <%= session[:user].name %>
244
245     You can also use the 'current_user' method provided by UserHelper:
246     Example:
247       Welcome <%= current_user.name %>
248
249
250   ... restrict access to only a few methods? 
251   
252   A: Use before_filters build in scoping. 
253      Example: 
254        before_filter :login_required, :only => [:myaccount, :changepassword]
255        before_filter :login_required, :except => [:index]
256      
257   ... check if a user is logged-in in my views?
258   
259   A: session[:user] will tell you. Here is an example helper which you can use to make this more pretty:
260      Example: 
261        def user?
262          !session[:user].nil?
263        end
264
265   ... return a user to the page they came from before logging in?
266
267   A: The user will be send back to the last url which called the method "store_location"
268      Example:
269        User was at /articles/show/1, wants to log in.
270        in articles_controller.rb, add store_location to the show function and
271        send the user to the login form. 
272        After he logs in he will be send back to /articles/show/1
273
274 You can find more help at http://wiki.rubyonrails.com/rails/show/SaltedLoginGenerator
275
276 == Troubleshooting
277
278 One of the more common problems people have seen is that after verifying an account by following the emailed URL, they are unable to login via the normal login method since the verified field is not properly set in the user model's row in the DB.
279
280 The most common cause of this problem is that the DB and session get out of sync. In particular, it always happens for me after recreating the DB if I have run the server previously. To fix the problem, remove the /tmp/ruby* session files (from wherever they are for your installation) while the server is stopped, and then restart. This usually is the cause of the problem.
281
282 = Notes
283
284 === Database Schemas & Testing
285
286 Currently, since not all databases appear to support structure cloning, the tests will load the entire schema into your test database, potentially blowing away any other test structures you might have. If this presents an issue for your application, comment out the line in test/test_helper.rb
287
288
289 = Database Schema Details
290
291 You need a database table corresponding to the User model. This is provided as a Rails Schema file, but the schema is presented below for information. Note the table type for MySQL. Whatever DB you use, it must support transactions. If it does not, the functional tests will not work properly, nor will the application in the face of failures during certain DB creates and updates.
292
293   mysql syntax:
294   CREATE TABLE users (
295     id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
296     login VARCHAR(80) NOT NULL,
297     salted_password VARCHAR(40) NOT NULL,
298     email VARCHAR(60) NOT NULL,
299     firstname VARCHAR(40),
300     lastname VARCHAR(40),
301     salt CHAR(40) NOT NULL,
302     verified INT default 0,
303     role VARCHAR(40) default NULL,
304     security_token CHAR(40) default NULL,
305     token_expiry DATETIME default NULL,
306     deleted INT default 0,
307     delete_after DATETIME default NULL
308   ) TYPE=InnoDB DEFAULT CHARSET=utf8;
309
310   postgres:
311   CREATE TABLE "users" (
312     id SERIAL PRIMARY KEY
313     login VARCHAR(80) NOT NULL,
314     salted_password VARCHAR(40) NOT NULL,
315     email VARCHAR(60) NOT NULL,
316     firstname VARCHAR(40),
317     lastname VARCHAR(40),
318     salt CHAR(40) NOT NULL,
319     verified INT default 0,
320     role VARCHAR(40) default NULL,
321     security_token CHAR(40) default NULL,
322     token_expiry TIMESTAMP default NULL,
323     deleted INT default 0,
324     delete_after TIMESTAMP default NULL
325   ) WITH OIDS;
326
327   sqlite:
328   CREATE TABLE 'users' (
329     id INTEGER PRIMARY KEY,
330     login VARCHAR(80) NOT NULL,
331     salted_password VARCHAR(40) NOT NULL,
332     email VARCHAR(60) NOT NULL,
333     firstname VARCHAR(40),
334     lastname VARCHAR(40),
335     salt CHAR(40) NOT NULL,
336     verified INT default 0,
337     role VARCHAR(40) default NULL,
338     security_token CHAR(40) default NULL,
339     token_expiry DATETIME default NULL,
340     deleted INT default 0,
341     delete_after DATETIME default NULL
342   );
343
344 Of course your user model can have any amount of extra fields. This is just a starting point.

Benjamin Mako Hill || Want to submit a patch?