= Before we start 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 * Localization has been removed. * The 'welcome' page has been changed to the 'home' page * A few new functions have been thrown in * It's... uh.... a Rails Engine now ;-) 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. 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. = Installation Installing the Login Engine is fairly simple. Your options are: 1. Install as a rails plugin: $ script/plugin install login_engine 2. Use svn:externals $ svn propedit svn:externals vendor/plugins You can choose to use the latest stable release: login_engine http://svn.rails-engines.org/plugins/login_engine Or a tagged release (recommended for releases of your code): login_engine http://svn.rails-engines.org/logine_engine/tags/ 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. === Setup your Rails application Edit your database.yml, most importantly! You might also want to move public/index.html out of the way, and set up some default routes in config/routes.rb. === Add configuration and start engine Add the following to the bottom of environment.rb: module LoginEngine config :salt, "your-salt-here" end Engines.start :login 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 Engines.start :login_engine - instead, :login (or any name) is sufficient if the engine is a directory named _engine. === Add the filters Next, edit your app/controllers/application.rb file. The beginning of your ApplicationController should look something like this: require 'login_engine' class ApplicationController < ActionController::Base include LoginEngine helper :user model :user before_filter :login_required 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. Add the following to your ApplicationHelper: module ApplicationHelper include LoginEngine end This ensures that the methods to work with users in your views are available === Set up ActionMailer 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: module LoginEngine # ... other options... config :use_email_notification, false end 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 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): ActionMailer::Base.server_settings = { :address => "smtp.mac.com", :port => 25, :domain => "smtp.mac.com", :user_name => "", :password => "", :authentication => :login } 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. === Create the DB schema 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/. You *MUST* check that these files aren't going to interfere with anything in your application. You can change the table name used by adding module LoginEngine # ... other options... config :user_table, "your_table_name" end ...to the LoginEngine configuration in environment.rb. Then run from the root of your project: rake db:migrate:engines ENGINE=login to import the schema into your database. == Include stylesheets If you want the default stylesheet, add the following line to your layout: <%= engine_stylesheet 'login_engine' %> ... somewhere in the section of your HTML layout file. == Integrate flash messages into your layout 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: * :warning - warning (failure) messages * :notice - success messages * :message - neutral (reminder, informational) messages 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: <% for name in [:notice, :warning, :message] %> <% if flash[name] %> <%= "
#{flash[name]}
" %> <% end %> <% end %> 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. = How to use the Login Engine Now you can go around and happily add "before_filter :login_required" to the controllers which you would like to protect. 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? === Protection using before_filter Adding the line before_filter :login_required to your app/controllers/application.rb 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 application.rb and add it to the controllers that you want to secure. Within individual controllers you can restrict which methods the filter runs on in the usual way: before_filter :login_required, :only => [:myaccount, :changepassword] before_filter :login_required, :except => [:index] === Protection using protect?() Alternatively, you can leave the before_filter in the global application.rb file, and control which actions are restricted in individual controllers by defining a protect?() method in that controller. For instance, in the UserController 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 protect?() method is defined in user_controller.rb as follows: def protect?(action) if ['login', 'signup', 'forgot_password'].include?(action) return false else return true end end Of course, you can override this Engine behaviour in your application - see below. == Configuration 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). For example, the following might appear at the bottom of /config/environment.rb: module LoginEngine config :salt, 'my salt' config :app_name, 'My Great App' config :app_url, 'http://www.wow-great-domain.com' end Engines.start === Configuration Options +email_from+:: The email from which registration/administration emails will appear to come from. Defaults to 'webmaster@your.company'. +admin_email+:: The email address users are prompted to contact if passwords cannot be emailed. Defaults to 'webmaster@your.company'. +app_url+:: The URL of the site sent to users for signup/forgotten passwords, etc. Defaults to 'http://localhost:3000/'. +app_name+:: The application title used in emails. Defaults to 'TestApp'. +mail_charset+:: The charset used in emails. Defaults to 'utf-8'. +security_token_life_hours+:: The life span of security tokens, in hours. If a security token is older than this when it is used to try and authenticate a user, it will be discarded. In other words, the amount of time new users have between signing up and clicking the link they are sent. Defaults to 24 hours. +two_column_input+:: If true, forms created with the UserHelper#form_input method will use a two-column table. Defaults to true. +changeable_fields+:: An array of fields within the user model which the user is allowed to edit. The Salted Hash Login generator documentation states that you should NOT include the email field in this array, although I am not sure why. Defaults to +[ 'firstname', 'lastname' ]+. +delayed_delete+:: Set to true to allow delayed deletes (i.e., delete of record doesn't happen immediately after user selects delete account, but rather after some expiration of time to allow this action to be reverted). Defaults to false. +delayed_delete_days+:: The time delay used for the 'delayed_delete' feature. Defaults to 7 days. +user_table+:: The table to store User objects in. Defaults to "users" (or "user" if ActiveRecord pluralization is disabled). +use_email_notification+:: If false, no emails will be sent to the user. As a consequence, users who signup are immediately verified, and they cannot request forgotten passwords. Defaults to true. +confirm_account+:: An overriding flag to control whether or not user accounts must be verified by email. This overrides the +user_email_notification+ flag. Defaults to true. == Overriding controllers and views 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 home action, simple create a new file in RAILS_ROOT/app/views/user/home.rhtml (you'll probably need to create the directory user at the same time). This new view file will be used instead of the one provided in the Login Engine. Easy! == Tips & Tricks How do I... ... access the user who is currently logged in A: You can get the user object from the session using session[:user] Example: Welcome <%= session[:user].name %> You can also use the 'current_user' method provided by UserHelper: Example: Welcome <%= current_user.name %> ... restrict access to only a few methods? A: Use before_filters build in scoping. Example: before_filter :login_required, :only => [:myaccount, :changepassword] before_filter :login_required, :except => [:index] ... check if a user is logged-in in my views? A: session[:user] will tell you. Here is an example helper which you can use to make this more pretty: Example: def user? !session[:user].nil? end ... return a user to the page they came from before logging in? A: The user will be send back to the last url which called the method "store_location" Example: User was at /articles/show/1, wants to log in. in articles_controller.rb, add store_location to the show function and send the user to the login form. After he logs in he will be send back to /articles/show/1 You can find more help at http://wiki.rubyonrails.com/rails/show/SaltedLoginGenerator == Troubleshooting 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. 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. = Notes === Database Schemas & Testing 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 = Database Schema Details 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. mysql syntax: CREATE TABLE users ( id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, login VARCHAR(80) NOT NULL, salted_password VARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, firstname VARCHAR(40), lastname VARCHAR(40), salt CHAR(40) NOT NULL, verified INT default 0, role VARCHAR(40) default NULL, security_token CHAR(40) default NULL, token_expiry DATETIME default NULL, deleted INT default 0, delete_after DATETIME default NULL ) TYPE=InnoDB DEFAULT CHARSET=utf8; postgres: CREATE TABLE "users" ( id SERIAL PRIMARY KEY login VARCHAR(80) NOT NULL, salted_password VARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, firstname VARCHAR(40), lastname VARCHAR(40), salt CHAR(40) NOT NULL, verified INT default 0, role VARCHAR(40) default NULL, security_token CHAR(40) default NULL, token_expiry TIMESTAMP default NULL, deleted INT default 0, delete_after TIMESTAMP default NULL ) WITH OIDS; sqlite: CREATE TABLE 'users' ( id INTEGER PRIMARY KEY, login VARCHAR(80) NOT NULL, salted_password VARCHAR(40) NOT NULL, email VARCHAR(60) NOT NULL, firstname VARCHAR(40), lastname VARCHAR(40), salt CHAR(40) NOT NULL, verified INT default 0, role VARCHAR(40) default NULL, security_token CHAR(40) default NULL, token_expiry DATETIME default NULL, deleted INT default 0, delete_after DATETIME default NULL ); Of course your user model can have any amount of extra fields. This is just a starting point.