active_url 0.1.4

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ README.textile
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
@@ -0,0 +1,5 @@
1
+ *.sw?
2
+ .DS_Store
3
+ coverage
4
+ rdoc
5
+ pkg
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Matthew Hollingworth
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,454 @@
1
+ h1. ActiveUrl
2
+
3
+ Like many Rails websites, my first production "Rails site":http://things.toswap.com.au needed user sign-ups. I wanted to have this work in a way that allowed a user to register only after confirming their email address.
4
+
5
+ The way to do this is with _secret URLs_.These are URLs that contain an encrypted string and are effectively impossible to guess. By sending a secret URL to an email address, if the URL is subsequently accessed, that's pretty much a guarantee that the email was received, since there's no other way that URL could have been obtained. (Check out the ??Rails Recipes?? book, which has a good chapter explaining secret URLs.)
6
+
7
+ h2. Introducing the ActiveUrl Gem
8
+
9
+ As a first attempt at contributing to the Rails community, I've extracted my site's secret URL functionality into a gem. Since it's used in a similar fashion to <code:ruy>ActiveRecord</code>, I've called it <code>ActiveUrl</code>.
10
+
11
+ How is my implementation distinctive? Basically, it's database-free. You don't need any new database tables or fields to use it, since all the relevant information is persisted in the URL itself. All you need to do to hide a page behind a secret URL is to nest its route beneath an ActiveUrl object that the library provides. Neat!
12
+
13
+ h2. Installation & Usage
14
+
15
+ First, install the gem:
16
+
17
+ <pre>
18
+ gem sources -a http://gems.github.com
19
+ sudo gem install mholling-active_url
20
+ </pre>
21
+
22
+ In your Rails app, make sure to specify the gem dependency in environment.rb:
23
+
24
+ <pre>
25
+ config.gem "mholling-active_url", :lib => "active_url", :source => "http://gems.github.com"
26
+ </pre>
27
+
28
+ Specify a secret passphrase for the library to perform its encryption. You can set this by adding an initializer (say active_url.rb) in your config/initializers directory. This will just set the secret passphrase for your app (you might not want to check this into your source control):
29
+
30
+ <pre>
31
+ ActiveUrl::Config.secret = "my-app-encryption-secret"
32
+ </pre>
33
+
34
+ To generate secret URLs in your Rails application, simply inherit a model from <code>ActiveUrl::Base</code>, in the same way you would normally inherit from <code>ActiveRecord::Base</code>. These objects won't be stored in your database; instead they will be persisted as an encrypted ID and placed in an URL given only to that user (typically by email).
35
+
36
+ <pre>
37
+ class Secret < ActiveUrl::Base
38
+ ...
39
+ end
40
+ </pre>
41
+
42
+ The following class methods are available for your model:
43
+
44
+ * <code>attribute(*attribute_names)</code> [sets attributes on your model];
45
+ * <code>belongs_to(model_name)</code> [sets a "foreign key" attribute and an association method];
46
+ * <code>attr_accessible(*attribute_names)</code> [allows mass-assignment of attributes]
47
+ * validations: most of the ActiveRecord validations are available on the attributes you set;
48
+ * <code>after_save(callback_name)</code> [sets a callback to be run after the object is persisted];
49
+ * <code>find(id)</code> [finds an object from the specified ID, which will be extracted from an URL].
50
+
51
+ Save your object by using the <code>ActiveUrl::Base#save</code> method--this will run any validations and generate the encrypted ID if the validations pass. (You will usually use this method in your model's controller.)
52
+
53
+ In your controllers which deal with ActiveUrl models, you'll want to deal with the case of an invalid URL; usually just to render a 404. This is easily done using <code>rescue_from</code> in your application controller:
54
+
55
+ <pre>
56
+ rescue_from ActiveUrl::RecordNotFound do
57
+ render :file => "#{Rails.root}/public/404.html", :status => 404
58
+ end
59
+ </pre>
60
+
61
+ h2. Example: Confirming an Email Address
62
+
63
+ The typical use case for this example is the verification of an email address provided by a someone signing up to your website. You want to check that the address is valid by sending an email to that address; the user must follow a secret URL in the email to confirm they received the email.
64
+
65
+ h3. Registration Model
66
+
67
+ We don't want to create a User model until the email is confirmed, so instead we'll use a <code>ActiveUrl::Base</code> model. This is what will be created when a user registers:
68
+
69
+ <pre>
70
+ class Registration < ActiveUrl::Base
71
+ attribute :email, :accessible => true
72
+ validates_format_of :email, :with => /^[\w\.=-]+@[\w\.-]+\.[a-zA-Z]{2,4}$/ix
73
+ validate :email_not_taken
74
+
75
+ after_save :send_registration_email
76
+
77
+ protected
78
+
79
+ def email_not_taken
80
+ if User.find_by_email(email)
81
+ errors.add(:email, "is already in use")
82
+ end
83
+ end
84
+
85
+ def send_registration_email
86
+ Mailer.deliver_registration(self)
87
+ end
88
+ end
89
+ </pre>
90
+
91
+ Going through this step-by-step:
92
+
93
+ # First, we set our email attribute using <code>attribute :email</code>, which generates setter and getter methods for the attribute.
94
+ # Next, validate the email address so it at least looks right (<code>validates_format_of :email</code>).
95
+ # We also want to check that a user has not already signed up with that email address, so we add a custom validation (<code>email_not_taken</code>) which adds an error if a User with that email address is found.
96
+ # Finally, we set an <code>after_save</code> callback to actually send the registration email when the model is saved. In the mailer method, we pass in the object so that we know what email address to send to and what secret URL to use.
97
+
98
+ h3. Routes
99
+
100
+ Next, let's set up our routes to allow user creation only via an email confirmation. In routes.rb the relevant routes would be:
101
+
102
+ <pre>
103
+ map.resources :registrations, :only => [ :new, :create ] do |registration|
104
+ registration.resources :users, :only => [ :new, :create ]
105
+ end
106
+ </pre>
107
+
108
+ h3. Registrations Controller
109
+
110
+ To allow a user to register, create a registrations controller with just two REST actions, <code>new</code> and <code>create</code>. The controller is entirely generic, as it should be:
111
+
112
+ <pre>
113
+ class RegistrationsController < ApplicationController
114
+ def new
115
+ @registration = Registration.new
116
+ end
117
+
118
+ def create
119
+ @registration = Registration.new(params[:registration])
120
+ if @registration.save
121
+ flash[:notice] = "Please check your email to complete the registration."
122
+ redirect_to root_path # or wherever...
123
+ else
124
+ flash.now[:error] = "There were problems with that email address."
125
+ render :action => "new"
126
+ end
127
+ end
128
+ end
129
+ </pre>
130
+
131
+ When the <code>create</code> action succeeds, the registration object is saved and the registration email sent automatically by its <code>after_save</code> callback.
132
+
133
+ h3. Registration View
134
+
135
+ In the new.html.erb view, the registration form would look something like:
136
+
137
+ <pre>
138
+ <% form_for @registration do |form| %>
139
+ <div>
140
+ <%= form.label :email %>
141
+ <%= form.text_field :email %>
142
+ </div>
143
+ <div>
144
+ <%= form.submit "Register" %>
145
+ </div>
146
+ <% end %>
147
+ </pre>
148
+
149
+ h3. Mailer
150
+
151
+ Finally, we set the mailer to deliver a registration email to the supplied email address:
152
+
153
+ <pre>
154
+ class Mailer < ActionMailer::Base
155
+ def registration(registration)
156
+ subject "Registration successful"
157
+ recipients registration.email
158
+ from "admin@website.com"
159
+
160
+ body :registration => registration
161
+ end
162
+ end
163
+ </pre>
164
+
165
+ The registration object is passed through to the email template, where we use it to get the email address and also to generate the new user URL. Since the URL is secret, if it is subsequently accessed then we know that whoever is accessing it was able to read that email. Thus we have confirmed the email address as a real one, which is what we wanted.
166
+
167
+ The email template might look something like:
168
+
169
+ <pre>
170
+ Hi <%= @registration.email %>,
171
+
172
+ Thanks for registering! Please follow this link to complete your
173
+ registration process:
174
+
175
+ <%= new_registration_user_url(@registration, :host => "website.com") %>
176
+
177
+ Thanks!
178
+ website.com
179
+ </pre>
180
+
181
+ The secret URL generated in the email would look something like:
182
+
183
+ <pre>
184
+ http://website.com/registrations/yAfxbJIeUFKX9YiY6Pqv0UAwufcacnYabEYS7TxTgZY/users/new
185
+ </pre>
186
+
187
+ h3. User Model
188
+
189
+ In our <code>User</code> model, we want to make sure the email address cannot be mass-assigned, so be sure to use <code>attr_protected</code> (or even better, <code>attr_accessible</code>) to prevent this:
190
+
191
+ <pre>
192
+ class User < ActiveRecord::Base
193
+ ...
194
+ attr_protected :email
195
+ ...
196
+ end
197
+ </pre>
198
+
199
+ h3. Users Controller
200
+
201
+ Now let's turn our attention to the users controller. We access the <code>new</code> and <code>create</code> actions only via the nested routes, so that we can load our <code>Registration</code> object from the controller parameters. We'll use the <code>ActiveUrl::Base.find</code> method to retrieve the registration object, and then set the user's email address from it:
202
+
203
+ <pre>
204
+ class UsersController < ApplicationController
205
+ def new
206
+ @registration = Registration.find(params[:registration_id])
207
+ @user = User.new
208
+ @user.email = @registration.email
209
+ end
210
+
211
+ def create
212
+ @registration = Registration.find(params[:registration_id])
213
+ @user = User.new(params[:user])
214
+ @user.email = @registration.email
215
+ if @user.save
216
+ flash[:notice] = "Thanks for registering!"
217
+ redirect_to @user # or wherever...
218
+ else
219
+ flash.now[:error] = "There were problems with your information."
220
+ render :action => "new"
221
+ end
222
+ end
223
+ end
224
+ </pre>
225
+
226
+ h3. New User View
227
+
228
+ The exact contents of the user creation form will depend on our User model, among other things. Notably however,it will *not* include a field for the email address, since we've already obtained the email address from the registration object and we don't want the user to be able to subsequently change it. (It's probably advisable to include the email address in the form's text though, for the sake of clarity.)
229
+
230
+ The new user form might look something like this:
231
+
232
+ <pre>
233
+ <% form_for [ @registration, @user ] do |form| %>
234
+ <div>
235
+ Please enter new user details for <% @user.email %>.
236
+ </div>
237
+ <div>
238
+ <%= form.label :name %>
239
+ <%= form.text_field :name %>
240
+ </div>
241
+ <!-- ... other user fields here ... -->
242
+ <div>
243
+ <%= form.submit "OK" %>
244
+ </div>
245
+ <% end %>
246
+ </pre>
247
+
248
+ h2. Example: Resetting a Lost Password
249
+
250
+ Let's take a look at another application of the library - implementing a "reset password" function. Basically, we want to allow an user to change his/her password without logging in. We'll achieve this by sending the secret URL to the user when they submit a "forgot your password?" form.
251
+
252
+ Again, the basic idea is to hide the password-editing page behind the secret URL. The password-editing page will not be protected by the usual authentication requirements; instead, the knowledge of the secret URL is what authenticates the user.
253
+
254
+ h3. Model
255
+
256
+ Let's first take a look at an ActiveUrl model for the secret URL. We want to create an instance from an email address, which is what the user will still know once the password is forgotten. We could declare an email attribute as in the previous article, but the only thing our model really needs is a reference to a user, which we can derive from the email.
257
+
258
+ For this purpose, we'll use the <code>belongs_to</code> feature of ActiveUrl. This is a quick-and-dirty mirror of the corresponding ActiveRecord feature. (Its only purpose though is to relate a secret URL to an existing database record, so it's only got the bare minimum of functionality.) Let's use it:
259
+
260
+ <pre>
261
+ class Secret < ActiveUrl::Base
262
+ belongs_to :user
263
+ validates_presence_of :user
264
+
265
+ attr_reader :email
266
+ attr_accessible :email
267
+
268
+ def email=(email)
269
+ @email = email
270
+ self.user = User.find_by_email(email)
271
+ end
272
+
273
+ after_save :send_email
274
+
275
+ protected
276
+
277
+ def send_email
278
+ Mailer.deliver_secret(self)
279
+ end
280
+ end
281
+ </pre>
282
+
283
+ h4. Attributes
284
+
285
+ We've set the email as a _virtual attribute_, just as we might for a normal ActiveRecord object. In addition to setting an instance variable, the email setter method also sets the user. The <code>Secret#user=</code> method is generated by the <code>belongs_to</code> association. (<code>user_id=</code>, <code>user</code> and <code>user_id</code> methods are also generated.)
286
+
287
+ We can see what attributes are stored in the model, and what can be written by mass-assignment:
288
+
289
+ <pre>
290
+ Secret.attribute_names
291
+ # => #<Set: {:user_id}>
292
+
293
+ Secret.accessible_attributes
294
+ # => #<Set: {:email}>
295
+ </pre>
296
+
297
+ In other words, the only attribute stored in the model is the user id, but that id can only be set by setting the email.
298
+
299
+ <pre>
300
+ User.first
301
+ # => #<User id: 1, email: "name@example.com", ... >
302
+
303
+ secret = Secret.new(:user_id => 1)
304
+ secret.user_id
305
+ # => nil
306
+
307
+ secret = Secret.new(:email => "name@example.com")
308
+ secret.user_id
309
+ # => 1
310
+ </pre>
311
+
312
+ h4. Validations
313
+
314
+ A validation, <code>validates_presence_of :user</code>, ensures that an existing user is found for the given email address. The object won't save (and the email won't get sent) if there's no user with that email address.
315
+
316
+ (n.b. If you want to use the Rails error markup in your form, you might want to set an error on <code>email</code> instead.)
317
+
318
+ h4. Callbacks
319
+
320
+ Finally, note the <code>after_save</code> callback. It's a method which sends the secret URL to the user in an email, and it will get called when the controller successfully saves the object.
321
+
322
+ h3. Routes
323
+
324
+ Our routes are pretty simple. We only want to be able to create secrets, so we'll just have <code>new</code> and <code>create</code> routes. Nested under a secret, we want some routes for changing the user's password. This could be arranged in a few different ways, but let's put the password-changing actions in their own controller:
325
+
326
+ <pre>
327
+ map.resources :secrets, :only => [ :new, :create ] do |secret|
328
+ secret.resources :passwords, :only => [ :new, :create ]
329
+ end
330
+ </pre>
331
+
332
+ h3. Controller
333
+
334
+ As always, we strive for generic controllers, and we pretty much get one here:
335
+
336
+ <pre>
337
+ class SecretsController < ApplicationController
338
+ def new
339
+ @secret = Secret.new
340
+ end
341
+
342
+ def create
343
+ @secret = Secret.new(params[:secret])
344
+ if @secret.save
345
+ flash[:notice] = "Please check your email for a link to change your password."
346
+ redirect_to root_path # or wherever...
347
+ else
348
+ flash.now[:error] = "Unrecognised email address" # if you want to disclose this...
349
+ render :action => "new"
350
+ end
351
+ end
352
+ end
353
+ </pre>
354
+
355
+ Of course, there's also a <code>PasswordController</code>, which will contain the actions for changing the user's password. (The user to edit will be obtained from the secret, which in turn will be found from <code>params[:secret_id]</code>.) Its implementation will depend on the <code>User</code> model. Since these actions are hidden behind the secret URL, we'd want to skip the normal user authentication filters for the actions.
356
+
357
+ h3. View
358
+
359
+ How does the user actually request a password reset? By submitting his/her email address in a form. Link to this form on the login page:
360
+
361
+ <pre>
362
+ <%= link_to "I forgot my password", new_secret_path %>
363
+ </pre>
364
+
365
+ The form itself just asks for an email address:
366
+
367
+ <pre>
368
+ <% form_for @secret do |form| %>
369
+ <p>
370
+ OK, so you forgot your password.
371
+ No problems! Just enter your email address.
372
+ We'll send you a link to change your password.
373
+ </p>
374
+ <div>
375
+ <%= form.label :email %>
376
+ <%= form.text_field :email %>
377
+ </div>
378
+ <div>
379
+ <%= form.submit "OK" %>
380
+ </div>
381
+ <% end %>
382
+ </pre>
383
+
384
+ h3. Mailer
385
+
386
+ In our mailer we want to send an email containing the secret URL for the password edit action. The ActiveUrl object obtained from the URL contains all we need to know, so we just pass it through to the email template. We send the email to the secret's associated user:
387
+
388
+ <pre>
389
+ class Mailer < ActionMailer::Base
390
+ def secret(secret)
391
+ subject "Change password requested"
392
+ recipients secret.user.email
393
+ from "admin@website.com"
394
+
395
+ body :secret => secret
396
+ end
397
+ end
398
+ </pre>
399
+
400
+ The email template might look something like:
401
+
402
+ <pre>
403
+ Hi <%= @secret.user.first_name %>,
404
+
405
+ To change your password, please visit the following link:
406
+
407
+ <%= new_secret_password_url(@secret, :host => "website.com") %>
408
+
409
+ (If you did not request a password change, just ignore this email.)
410
+
411
+ Thanks!
412
+ website.com
413
+ </pre>
414
+
415
+ h3. Expiring the URL
416
+
417
+ There's a potential problem with the above implementation though. As it stands, the secret URL is static - the password reset URL for any given user will always be the same. This may or may not be a problem, depending on your security requirements.
418
+
419
+ It would be nice to have the URL expire once the password has been changed - in effect, to have a single-use URL. This is easily done. We add an attribute to the model containing the current password hash (or the cleartext password, if you store your user passwords in the clear - you shouldn't):
420
+
421
+ <pre>
422
+ attribute :password_hash
423
+
424
+ def email=(email)
425
+ @email = email
426
+ self.user = User.find_by_email(email)
427
+ self.password_hash = user.password_hash if user
428
+ end
429
+ </pre>
430
+
431
+ Then, simply validate the password hash to ensure it's the same as the user's:
432
+
433
+ <pre>
434
+ validate :password_hash_is_current, :if => :user
435
+
436
+ def password_hash_is_current
437
+ errors.add(:password_hash) unless user.password_hash == password_hash
438
+ end
439
+ </pre>
440
+
441
+ Since <code>ActiveUrl::Base.find</code> only finds valid objects, once the password has been changed, the secret URL won't validate and an <code>ActiveUrl::RecordNotFound</code> error will be raised. The controller will then drop through to a 404. Easy!
442
+
443
+ h2. Benefits of ActiveUrl
444
+
445
+ In other email confirmation schemes, whenever a registration process is initiated, a new user object is created, even before the email address is confirmed. This causes a couple of problems:
446
+
447
+ * The user model will need some form of state (to distinguish between confirmed and unconfirmed users).
448
+ * If a registration is initiated but not completed, the unconfirmed record will remain in the database, and will need to be manually removed at a later date.
449
+
450
+ The ActiveUrl gem overcomes both these problems by persisting all the relevant data to the URL itself, in encrypted form. No database table is needed.
451
+
452
+ One potential problem with this approach? The URL may become quite long if you store much data in the model. Keep the number of attributes and the length of their names to a minimum to avoid this. Typically, a single attribute or a <code>belongs_to</code> reference is all that's needed, and produces URLs of modest length.
453
+
454
+ Copyright (c) 2009 Matthew Hollingworth. See LICENSE for details.