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
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 ;-)
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.
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.
17 Installing the Login Engine is fairly simple.
20 1. Install as a rails plugin:
21 $ script/plugin install login_engine
23 $ svn propedit svn:externals vendor/plugins
25 You can choose to use the latest stable release:
26 login_engine http://svn.rails-engines.org/plugins/login_engine
28 Or a tagged release (recommended for releases of your code):
29 login_engine http://svn.rails-engines.org/logine_engine/tags/<TAGGED_RELEASE>
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.
33 === Setup your Rails application
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>.
37 === Add configuration and start engine
39 Add the following to the bottom of environment.rb:
42 config :salt, "your-salt-here"
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.
52 Next, edit your <tt>app/controllers/application.rb</tt> file. The beginning of your <tt>ApplicationController</tt> should look something like this:
54 require 'login_engine'
56 class ApplicationController < ActionController::Base
61 before_filter :login_required
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.
65 Add the following to your ApplicationHelper:
67 module ApplicationHelper
71 This ensures that the methods to work with users in your views are available
73 === Set up ActionMailer
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:
79 # ... other options...
80 config :use_email_notification, false
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
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):
88 ActionMailer::Base.server_settings = {
89 :address => "smtp.mac.com",
91 :domain => "smtp.mac.com",
92 :user_name => "<your user name here>",
93 :password => "<your password here>",
94 :authentication => :login
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.
100 === Create the DB schema
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/.
104 You *MUST* check that these files aren't going to interfere with anything in your application.
106 You can change the table name used by adding
110 # ... other options...
111 config :user_table, "your_table_name"
115 ...to the LoginEngine configuration in <tt>environment.rb</tt>. Then run from the root of your project:
117 rake db:migrate:engines ENGINE=login
119 to import the schema into your database.
122 == Include stylesheets
124 If you want the default stylesheet, add the following line to your layout:
126 <%= engine_stylesheet 'login_engine' %>
128 ... somewhere in the <head> section of your HTML layout file.
130 == Integrate flash messages into your layout
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:
134 * :warning - warning (failure) messages
135 * :notice - success messages
136 * :message - neutral (reminder, informational) messages
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:
140 <% for name in [:notice, :warning, :message] %>
142 <%= "<div id=\"#{name}\">#{flash[name]}</div>" %>
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.
149 = How to use the Login Engine
151 Now you can go around and happily add "before_filter :login_required" to the controllers which you would like to protect.
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?
155 === Protection using <tt>before_filter</tt>
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.
159 Within individual controllers you can restrict which methods the filter runs on in the usual way:
161 before_filter :login_required, :only => [:myaccount, :changepassword]
162 before_filter :login_required, :except => [:index]
164 === Protection using <tt>protect?()</tt>
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.
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:
171 if ['login', 'signup', 'forgot_password'].include?(action)
178 Of course, you can override this Engine behaviour in your application - see below.
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).
184 For example, the following might appear at the bottom of /config/environment.rb:
187 config :salt, 'my salt'
188 config :app_name, 'My Great App'
189 config :app_url, 'http://www.wow-great-domain.com'
194 === Configuration Options
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
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.
230 == Overriding controllers and views
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!
239 ... access the user who is currently logged in
241 A: You can get the user object from the session using session[:user]
243 Welcome <%= session[:user].name %>
245 You can also use the 'current_user' method provided by UserHelper:
247 Welcome <%= current_user.name %>
250 ... restrict access to only a few methods?
252 A: Use before_filters build in scoping.
254 before_filter :login_required, :only => [:myaccount, :changepassword]
255 before_filter :login_required, :except => [:index]
257 ... check if a user is logged-in in my views?
259 A: session[:user] will tell you. Here is an example helper which you can use to make this more pretty:
265 ... return a user to the page they came from before logging in?
267 A: The user will be send back to the last url which called the method "store_location"
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
274 You can find more help at http://wiki.rubyonrails.com/rails/show/SaltedLoginGenerator
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.
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.
284 === Database Schemas & Testing
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
289 = Database Schema Details
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.
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;
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
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
344 Of course your user model can have any amount of extra fields. This is just a starting point.