Skip to content
Newer
Older
100644 196 lines (127 sloc) 12.6 KB
05412be @binarylogic Update README with setup tutorial
binarylogic authored
1 = Authlogic Example App
2
3 This is an example of how to use Authlogic in a rails app. Authlogic is a clean, simple, and unobtrusive ruby authentication solution.
4
5 <b>Please note that there are multiple branches for this example app that show how to do different things in Authlogic.</b>
6
6c044db @binarylogic Fix README links
binarylogic authored
7 * This application live: http://authlogicexample.binarylogic.com
8 * Reset passwords tutorial: http://www.binarylogic.com/2008/11/16/tutorial-reset-passwords-with-authlogic
9 * Authlogic: http://github.com/binarylogic/authlogic
05412be @binarylogic Update README with setup tutorial
binarylogic authored
10
11 == What does this example app contain?
12
13 1. User registration.
14 2. Automatically log users in upon successful registration.
15 3. A my account area where the user can view / change details about their account, including their password.
16 4. Automatically update the users session when they change their password.
17 5. Logout functionality.
18 6. Login functionality with a "remember me" option.
19 7. Secure password / token system, based on proven principals used in ruby / rails for years.
20 8. Automatically store information on the users and their session in the databases. Such as login count, IP address, when they logged in last, and when their last activity occurred.
21 9. Count how many users are logged in / out in your system.
22
23 == Tutorial on how to create this app and easily setup Authlogic
24
25 === 1. Install
26
27 Install the gem / plugin (recommended)
28
29 $ sudo gem install authlogic
30
31 Now add the gem dependency in your config:
32
33 # config/environment.rb
34 config.gem "authlogic"
35
36 Or you install this as a plugin (for older versions of rails)
37
38 script/plugin install git://github.com/binarylogic/authlogic.git
39
40 === 2. Create your UserSession model
41
42 Authlogic introduces a new flavor of models that extends Authlogic::Session::Base. The point of this model is to handle all of the session details for you. Just like ActiveRecord handles all of the database details. You can create, update, and delete sessions just like an ActiveRecord model. It basically sits in between you and the cookies in the same manner ActiveRecord sits in between you and the database. The best part is that you use it the same way too.
43
44 So lets assume you are setting up a session for your User model. You can call this anything you want, but I recommend naming it after the model you are authenticating with, this way if you want to add multiple session models down the road you can easily do this without have name clashes.
45
46 Let's create a user_session.rb file:
47
48 $ script/generate session user_session
49
50 This will create a file that looks like:
51
52 # app/models/user_session.rb
53 class UserSession < Authlogic::Session::Base
54 # configuration here, see documentation for sub modules of Authlogic::Session
55 end
56
57 === 3. Ensure proper database fields
58
59 If you don't already have a User model, go ahead and create one:
60
61 script/generate model user
62
63 Since you are authenticating with your User model, it can have the following columns. The names of these columns can be changed with configuration. Better yet, Authlogic tries to guess these names by checking for the existence of common names. If you checkout the Authlogic::ActsAsAuthentic submodules in the {documentation}[[http://authlogic.rubyforge.org]], it will show you the various names checked, chances are you won't have to specify any configuration for your field names, even if they aren't the same names as below.
64
65 t.string :login, :null => false # optional, you can use email instead, or both
66 t.string :email, :null => false # optional, you can use login instead, or both
67 t.string :crypted_password, :null => false # optional, see below
68 t.string :password_salt, :null => false # optional, but highly recommended
69 t.string :persistence_token, :null => false # required
70 t.string :single_access_token, :null => false # optional, see Authlogic::Session::Params
71 t.string :perishable_token, :null => false # optional, see Authlogic::Session::Perishability
72
73 # Magic columns, just like ActiveRecord's created_at and updated_at. These are automatically maintained by Authlogic if they are present.
74 t.integer :login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
75 t.integer :failed_login_count, :null => false, :default => 0 # optional, see Authlogic::Session::MagicColumns
76 t.datetime :last_request_at # optional, see Authlogic::Session::MagicColumns
77 t.datetime :current_login_at # optional, see Authlogic::Session::MagicColumns
78 t.datetime :last_login_at # optional, see Authlogic::Session::MagicColumns
79 t.string :current_login_ip # optional, see Authlogic::Session::MagicColumns
80 t.string :last_login_ip # optional, see Authlogic::Session::MagicColumns
81
82 <b>Credential fields are optional:</b>
83 Notice the login, email, and crypted_password fields are optional. That's because Authlogic doesn't care how you authenticate, you don't have to use your own authentication method. If you prefer, you could use OpenID, LDAP, or whatever you want and not even provide your own authentication system. These authentication methods can EASILY be added by using an authlogic add on (see Authlogic Addons above). I recommend providing your own as an option though. Your interface, such as the registration form, can dictate which method is the default.
84
85 <b>What are all of the token fields?</b>
86 Instead of giving you a token for each task (reset passwords, etc.), authlogic gives you the different kinds of tokens that tasks need. They are your "keys" to do the following:
87
88 * Persistence token: Used by Authlogic internally, it is stored in your cookies and sessions to persist the user. This is much more secure than plainly storing the user's id.
89 * Single access token: Use this for a private feed or API access. Ex: www.whatever.com?user_credentials=[single access token]. Grants access but does NOT persist.
90 * Perishable token: Great for authenticating users to reset passwords, confirm their account, etc.
91
92 See the {documentation}[http://authlogic.rubyforge.org] for more details.
93
94 === 4. Set up your model
95
96 Make sure you have a model that you will be authenticating with. Since we are using the User model it should look something like:
97
98 class User < ActiveRecord::Base
99 acts_as_authentic do |c|
100 c.my_config_option = my_value # for available options see documentation in: Authlogic::ActsAsAuthentic
101 end # block optional
102 end
103
104 One thing to note here is that this tries to take care of all the authentication grunt work, <b>including validating your login, email, password, and token fields</b>. You can easily disable this with configuration. Ex: c.validate_email_field = false. See the Authlogic::ActsAsAuthentic sub modules in the {documentation}[http://authlogic.rubyforge.org] for more details.
105
106 === 5. Create a UserSessionsController
107
108 This is where users will log in and out. It is responsible for managing their session. You create this controller JUST LIKE you do for any other model. The actions are exactly the same as well:
109
110 $ script/generate controller user_sessions
111
112 {Here is the source for the user_session_controller.rb}[http://github.com/binarylogic/authlogic_example/blob/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/controllers/user_sessions_controller.rb].
113
114 Notice it's exactly the same as any other resource controller. Then your views can be anything you want.
115
116 {Here are the view for the UserSessionsController}[http://github.com/binarylogic/authlogic_example/tree/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/views/user_sessions].
117
118 This is nothing new, it works just like all of your other RESTful controllers.
119
120 Now just map your routes:
121
122 # config/routes.rb
123 map.resource :user_session
124 map.root :controller => "user_sessions", :action => "new" # optional, this just sets the root route
125
126 === 6. Persist sessions
127
128 Your application controller will be responsible for persisting your session. This is my favorite part because it is so easy. I am able to do in 2 methods what used to take 5 to 6 different methods:
129
130 # app/controllers/application.rb
131 class ApplicationController < ActionController::Base
132 filter_parameter_logging :password, :password_confirmation
133 helper_method :current_user_session, :current_user
134
135 private
136 def current_user_session
137 return @current_user_session if defined?(@current_user_session)
138 @current_user_session = UserSession.find
139 end
140
141 def current_user
142 return @current_user if defined?(@current_user)
143 @current_user = current_user_session && current_user_session.user
144 end
145 end
146
147 That's it! You can name these methods anything you want. That's what's great about Authlogic, it doesn't assume things for you, you are in control of the application specific parts of authentication.
148
149 === 7. Restrict Access
150
151 This is application specific. You can do this however you wish. For an example {see the ApplicationController}[http://github.com/binarylogic/authlogic_example/blob/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/controllers/application_controller.rb] in the authlogic example app. Notice the require_user and require_no_user methods. They are enforced via before_filters in the other controllers. Restricting access is as simple as that. There are a million ways to do this, but this seems to be the most common and the simplest.
152
153 === 8. Register users
154
155 Registering users is very simple. Since this is rails 101 I will make this short and sweet.
156
157 Add some routes:
158
159 # config/routes.rb
160 map.resource :account, :controller => "users"
161 map.resources :users
162
163 Create your UsersController:
164
165 script/generate controller users
166
167 {Here is the source for users_controller.rb}[http://github.com/binarylogic/authlogic_example/blob/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/controllers/users_controller.rb].
168
169 {Here are the views for the UsersController}[http://github.com/binarylogic/authlogic_example/tree/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/views/users]
170
171 Pretty straightforward. One thing to note here is that there is nothing going on with the sessions.
172
173 So how does Authlogic log users in after registration? How does authlogic know to update a user's session after they reset their password? This is one of the great things about Authlogic, because the session logic is tucked away down in the model level we can interact with other models. So Authlogic automatically hooks into the related model (User) and does all of this for you. As with all features in Authlogic, if you do not want to use this, you can easily disable it. See Authlogic::ActsAsAuthentic::SessionMaintenance in the {documentation}[[http://github.com/binarylogic/authlogic_example/blob/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/controllers/application_controller.rb]] for more info.
174
175 === 9. Next Steps
176
177 Here are some common next steps. They might or might not apply to you. For a complete list of everything Authlogic can do please read the {documentation}[http://authlogic.rubyforge.org] or see the sub module list above.
178
179 1. Want to use another encryption algorithm, such as BCrypt? See Authlogic::ActsAsAuthentic::Password::Config
180 2. Migrating from restful_authentication? See Authlogic::ActsAsAuthentic::RestfulAuthentication::Config
181 3. Want to timeout sessions after a period if inactivity? See Authlogic::Session::Timeout
182 4. Need to scope your sessions to an account or parent model? See Authlogic::AuthenticatesMany
183 5. Need multiple session types in your app? Check out Authlogic::Session::Id
184 6. Need to reset passwords or activate accounts? Use the perishable token. See Authlogic::ActsAsAuthentic::PerishableToken
185 7. Need to give API access or access to a private feed? Use basic HTTP auth or authentication by params. See Authlogic::Session::HttpAuth or Authlogic::Session::Params
186 8. Need to internationalize your app? See Authlogic::I18n
187 9. Need help testing? See the Authlogic::TestCase
188
189 I've yet to encounter a case that authlogic does not handle. If you have a unique situation glance at the {documentation}(http://authlogic.rubyforge.org). I was very thorough with it, and you can discover all kinds of cool things Authlogic can do for you.
190
191 == Improving this tutorial
192
193 If you find something confusing or encounter a problem with this tutorial please fork this project, make the changes, and send me a pull request. I would really appreciate this and so would successive Authlogic users.
194
195
32f0a63 @binarylogic Fix README links
binarylogic authored
196 Copyright (c) 2008 {Ben Johnson}(http://github.com/binarylogic) of {Binary Logic}(http://www.binarylogic.com), released under the MIT license
Something went wrong with that request. Please try again.