stateful authentication

I wanted user records in my app to have various statuses. Here's how I modified restful_authentication with acts_as_state_machine to accomplish this. I'll call it stateful_authentication


The idea is to enhance restful_authentication with additional user statuses.

  • :passive - not authorized to log in, but known to the system, such as for mailing lists
  • :pending - user has registered but has not activated his account yet
  • :active - user account is active, user can log in
  • :suspended - user account suspended, not allowed to log in, can be re-enabled
  • :deleted - user id remains valid but account deleted, login name and email can be reused

Passive users may have signed up on the system, given their email and name or whatever, but don't have the right to log in. Passive users can register later with login privileges.

An active user can log in. (As for roles, authorization is handled separately from authentication, see my earlier post ).

Any user can be suspended by the administrator, for whatever reason. Suspended accounts can be re-enabled (un-suspended).

Keeping deleted user records is handy, for example, if some other objects such as a Comment references this user id, you can still retrieve some info about the poster even if he's no longer around. (A separate admin purge action can actually call destroy on deleted users). A deleted user will have its login and email changed with the string "[DELETED datetime]" appended, so they can be reused in a new user record.

"john@gmail.com [DELETED Fri Sep 21 13:35:07 -0400 2007]" 

In restful_authentication, the User model includes columns for login name, email, crypted_password, activation_code (allows user to active the account), and activated_at date (once account is activated). You could say an :active status is implied when activated_at is not blank?; and a :pending status is implied when activation_code is not blank?.

Our case extends this. You could say a :passive status is when both activated_at and activation_code are nil. But any user can be suspended or deleted regardless of these attribute values.


This article assumes you have installed the restful_authentication plugin and the acts_as_state_machine plugin. Note, I generated RA to require user activation (--include-activation).

  $ script/plugin source http://svn.techno-weenie.net/projects/plugins
  $ script/plugin install restful_authentication
  $ script/generate authenticated user sessions --include-activation
  $ rake db:migrate 
add observer to environment.rb 
add named routes to routes.rb
move lines from users_controller.rb to application.rb
edit user_notifier.rb as needed 
  $ script/plugin install http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk/ 

I'll leave other details to others, e.g.









Maybe I should consider making this a whole new plugin, but for now here's instructions to DIY (do it yourself).

User model

Make the User a state-machine. First, add a status attribute to the User model (we'll call it status rather than state)

$ script/generate migration add_status_to_users

edit with

add_column :users, :status, :string, :null => :no, :default => "passive" 

and then

$ rake db:migrate 


To models/user.rb, add:

  acts_as_state_machine :initial => :passive, :column => :status
state :passive
state :pending, :enter => :make_activation_code
state :active, :enter => :do_activate
state :suspended
state :deleted, :enter => :do_delete

Add the state machine transition events:

  event :register do
transitions :from => :passive, :to => :pending, :guard => Proc.new {|u| !u.crypted_password.blank? }

event :activate do
transitions :from => :pending, :to => :active

event :suspend do
transitions :from => [:passive, :pending, :active], :to => :suspended

event :delete do
transitions :from => [:passive, :pending, :active, :suspended], :to => :deleted

event :unsuspend do
transitions :from => :suspended, :to => :active, :guard => Proc.new {|u| !u.activated_at.blank? }
transitions :from => :suspended, :to => :pending, :guard => Proc.new {|u| !u.activation_code.blank? }
transitions :from => :suspended, :to => :passive

Thus when a new user is created, it's :passive. Then, user.register! will move a user from :passive to :pending (provided it has a password), and an activation_code is generated).

user.activate! will activate the account. To avoid confusion with the original #activate method, rename the old one to #do_activate. And make a small change to preserve the activated_at date (like when transitioning from suspended back to active).

  # rename old activate to do_activate
def do_activate
    @activated = true
    self.activated_at ||= Time.now.utc
    self.activation_code = nil

Also, now the activated? method is handled by our new active? method:

  # retain for compatibility, redundant with active?
  def activated?

Add a do_delete method (can be in protected)

    def do_delete
t = Time.now.to_s
      self.login += " [DELETED #{t}]"
      self.email += " [DELETED #{t}]"

Comment out the following because a new passive user doesn't need an activation code. Rather, this gets called in the :pending :enter callback:

#before_create :make_activation_code

When is password required? In original RA, it was always required if the crypted_password attribute is blank (new user) or if the password is being changed. Now, users don't need a password unless they're going to be activating an account, and guard that in the :register event transition. So the password (and password_confirmation) is validated only if it is present, thus, change password_required to

    def password_required?

One last thing, we only want to authenticate users who are active. Change self.authenticate to check:

  def self.authenticate(login, password)
    u = find :first, :conditions => ['login = ? and status = "active"', login]
    u && u.authenticated?(password) ? u : nil

Note that anywhere in your code that you do a Users.find, you now need to scope that by the requested state, such as

users = User.find_all_by_status(:active)



Okeydokey, next is the controller...

In users_controller.rb, the create action can now create either a passive or pending user. We'll use the presence of a password field to signal a new registration otherwise its a passive signup. Note, create does double duty, if the user exists as passive, it still moves ahead (or you could add an update action if this disturbs your REST, see this ).

  def create
    @user = User.find_by_email_and_status(params[:user][:email], :passive) if params[:user][:email]
    if @user.nil?
      @user = User.new(params[:user])
    @user.register! if params[:password]
    self.current_user = @user if @user.pending? # lets user be logged in before activating
    flash[:notice] = "Thanks for signing up!"
  rescue ActiveRecord::RecordInvalid
    render :action => 'new'

(Notes: I decided to key off a unique email rather than login name, seems more intuitive. Could be either. #create must fail if there's no params[:email]; we let the User.new handle that validation and rescue).

In the activate action, the only change is call the new #activate! rather than #activate

  def activate
    self.current_user = User.find_by_activation_code(params[:activation_code])
    if logged_in? && !current_user.activated?
      flash[:notice] = "Signup complete!"

If you've included the forgot password stuff then in #forgot_password, change this line:

    #if @user = User.find_by_email(params[:user][:email])
    if @user = User.find_by_email_and_status(params[:user][:email], "active") 

Finally, we can add #suspend, #unsuspend, #destroy and #purge actions (which should be available only to authorized admin users-- you'll need your own :admin_required helper for this).

before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]
  # PUT /users/1/suspend
def suspend
@user = User.find(params[:id])

# PUT /users/1/unsuspend
def unsuspend
@user = User.find(params[:id])

# DELETE /users/1
def destroy
@user = User.find(params[:id])

# DELETE /users/1/purge
def purge
@user = User.find(params[:id])
Make sure the corresponding routes are mapped in routes.rb. This is how I'm doing it,
    map.resources :users, 
:member => { :suspend => :put,
:unsuspend => :put,
:purge => :delete }

along with all the other named routes for the RA plugin (e.g. map.signup, map.activate, etc).

Observer / Notifier

The signup notification email (with activation_code) should be sent only when the user is pending. In user_observer.rb, remove the entire after_create method and add the following line to after_save

UserNotifier.deliver_signup_notification(user) if user.pending?


You could also adjust your views, but basically now a user can sign up with or without a password. When password is omitted, a passive user is captured (say, for subscription to a newsletter). When password is provided, he goes through full registration. Passive users can register later by supplying his email and a new password.


To get the restful_authentication tests to work with our changes, do the following:

in users.yml,

add "status: active" to the quentin user record

add "status: pending" to the aaron user record

in user_test.rb:

remove the test_should_require_password, since its not required

in users_controller_test.rb:

remove the test_should_require_password_on_signup, since its not required

To extend the tests for our new features... well, yes you should do that. Here's a handful that'd go into user_test.rb, certainly not full coverage.

    def test_should_create_passive_user
      assert_difference User, :count do
        user = create_user(:password => nil, :password_confirmation => nil)
        assert !user.new_record?, "#{user.errors.full_messages.to_sentence}"
        assert user.passive?
    def test_should_register_passive_user
        user = create_user(:password => nil, :password_confirmation => nil)
        assert user.passive?
        user.update_attributes(:password => 'new password', :password_confirmation => 'new password')
        assert user.pending?
    def test_should_suspend_user
      assert users(:quentin).suspended?
    def test_suspended_user_should_not_authenticate
      assert_not_equal users(:quentin), User.authenticate('quentin', 'test')
    def test_should_unsuspend_user
      assert users(:quentin).suspended?
      assert users(:quentin).active?
    def test_should_delete_user
      assert_not_equal users(:quentin).login, 'quentin'
      assert_not_equal users(:quentin).email, 'quentin@example.com'
      assert users(:quentin).deleted?




by Hendy Irawan on Nov 06, 2007


I would suggest using a datetime column "deleted_at" rather than modifying the fields directly (appending string datetime) if state is deleted.

Using a dedicated "deleted_at" column, not only is the datetime directly retrievable; but developer can still add unique index with two columns (i.e. email and deleted_at). So there can only be one active user with that email, but there can be many deleted users with exact same email. (i.e. the email is reusable if deleted)

by admin on Nov 06, 2007


Hendy, I agree that seems cleaner. We'd also need to change the email validation, perhaps something like (I havent tried this yet)

validates_uniqueness_of :email , :if => Proc.new { |u| !u.deleted_at.blank? }

by admin on Nov 06, 2007


maybe also override find_by_email to actually call find_by_email_and_deleted_at( email, nil )

by rick on Dec 08, 2007


Just so you know, I'm adding this to restful auth with a few tweaks (using the deleted_at suggestion, and keeping the aasm default column name 'state'.

by Harry on Dec 11, 2007


Thanks for doing this.

One note: I think the user_observer should be changed to UserMailer.deliver_activation(user) if user.active?

Otherwise, since 'pending' is the default, you get the signup email and the activation email both at the same time even though the user hasn't activated the account yet.

by Harry on Dec 11, 2007


Sorry, spoke too soon. Rick, it's in your user_observer.rb for the restful authentication plugin.

by codepope on Dec 13, 2007


If you change to "UserMailer.deliver_activation(user) if user.active?" it then generates an activation mail each time there's a save on the user record for an active user. This is not good.

Taking the observer out of the equation and wiring the UserMailer calls into the User model kinda works.... (generates 2 activation mails currently... working on that)...

by xavier on Dec 17, 2007


I am keeping 'UserMailer.deliver_activation(user) if user.pending?' (out of the box config) but receive both at the same time notification and activation mails automatically. Where is the user.save that triggers the activation mail before the user really activates through the notification link?

by Harry on Dec 18, 2007


In case you're interested, I think I have a solution to the activation email problem: http://harrylove.org/2007/12/17/activation-emails-with-restful-authentication-an d-acts_as_state_machine

by jonson on Jan 06, 2008


i tried figuring this out. it didn't work for me. the authentication code was never sent to users, becuase you deleted the before_save. adding that code back into this, helped there. but in my app, passive is useless. i guess i can change wherever you have passive to pending and see what happens. I mean, in my app, no matter how i tried to authenticate a user, the database had my users as passive. always. thanks

by Jamie Kaplan on Jan 09, 2008


Seems to me that acts_as_state_machine is somewhat lacking since it doesn't trigger the code associated with the initial state until AFTER it's saved. Shouldn't it call said logic on the model just after it's created, but before it's saved? (I'm trying to sort out the details of what's described above as well (changing active? to pending?, replacing the observer with all-state-machine code, etc.)). Things are definitely not working as they are. (of course, thanks to all of those who've gotten us this far!)

by emil tin on Jan 25, 2008


In my view, the fundamental problem here is that UserObserver is triggered by things like after_save, etc, but what we really want to observe is changes in the state of the state machine. That's why things get complicated and stop working. Acts_as_state_machine already gives us the mechanism to listen for state changes. So a better solution might to send emails directly User, or create a new type of observer class that listens for state changes in acts_as_state_machine model like User. (Although I'm not sure how this would be done technically.) It seems this is in line with that Jamie said above.

by Ches on Feb 28, 2008


I shared this on Harry's blog linked above, where emil posted some code for eliminating the Observer (which is a much cleaner and more sensible approach, thanks!), but for those landing here from Google or Rick Olson's README:


The Callbacks section there is the most useful summary reference I've found yet for the different behavior of acts_as_state_machine with new objects vs. existing (saved) records. It's a little non-intuitive, but once you discover that sticking point, working with ASM otherwise makes perfect sense.

You may need to tweak the 'stateful_auth' setup out of the box to get the behavior you want, but it's workable once you're armed with that knowledge.

by 57 on Mar 15, 2009

Re: stateful authentication


by samsu on Jan 27, 2015

Samsung Galaxy S5 (копия)!

Samsung Galaxy S5 (копия)! не отличимая от оригинала с логотипами Samsung на корпусе спереди и сзади, при включении телефона фирменная заставка Samsung. Функции оригинала : управление жестами http://www.big-butik.ru

by SexcamsDoub on Feb 28, 2015

amateur cams mit huren aus deiner nachbarschaft

Versaute Teens ab 18 live vor der privaten livecam. Willst du es ihnen besorgen? Melde dich jetzt unverbindlich an und du bekommst sofort 50 Coins für die liveshow kostenlos! Geniesse tabulose <b><a href=http://sexcam-live.co/>gratis sexcams</a></b> <a href=http://amateur--sex.info><img>http://6sx.org/sexbilder/anal-sex-besorgs-mir-von-hinten.jpg</img></a> ficken mit lesben aus deiner umgebung

by SexcamsDoub on Mar 05, 2015

live cams mit girls aus deiner stadt

Versaute Teens ab 18 live vor der privaten sexcam. Willst du ein erotisches treffen erleben? Melde dich jetzt umsonnst an und du bekommst gleich 50 Coins für die liveshows kostenlos! Schau geile <b><a href=http://cam--live.com/>sex filme</a></b> <a href=http://amateur--sex.info><img>http://6sx.org/sexbilder/free-sexcam-sex-dating.jpg</img></a> bumsen mit lesben aus deiner nachbarschaft

http://nyou.animegirldesp.org/forum2/index.php?action=profile;u=173178 http://gsm-extreme.net/showthread.php?p=542156#post542156 http://www.kuwaitcricket.com/BB2/viewtopic.php?p=67498#67498 http://bbs.155.cn/space-uid-3346028.html http://openbookprogram.org/bbs/messages/6642.html

by CamsexDoub on Mar 08, 2015

live cams mit huren aus deiner nachbarschaft

Heisse Teenies ab 18 live vor der privaten sexcam. Willst du ein erotisches treffen erleben? Melde dich jetzt unverbindlich an und du erhälst gleich 50 Coins für die liveshows gratis! Betrachte versaute [b][url=http://sexcam.s-3-x.com]sex filme[/url][/b] [url=http://amateur--sex.info][img]http://6sx.org/sexbilder/sexy-girl.jpg[/img][/url] treffen mit frauen aus deiner nähe

http://www.myjellybean.com/chat/member.php?738078-Sexcamshix http://vbulletin.123flashchat.com/member.php?255285-Sexcamson http://satelitski.forumcircle.com/viewtopic.php?p=1798#1798 http://enccom.net/bbs/view.php?id=jubu&page=4&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=vote&desc=asc&no=23 http://www.palsprogram.org/about-us/board-of-directors/item/62-richard-ross-esq.html

by oferifh on Mar 18, 2015

Правильный выбор - наш интернет магазин

Правильный выбор - наш интернет магазин Воспользуйтесь уникальным предложением! http://offer.moscow/

by miuoj on Mar 23, 2015

В нашем интернет-магазине

В нашем интернет-магазине лучший ассортимент и лучшие цены http://miraclefairy.ru/

by SexcamDoub on Mar 24, 2015

bumsen mit frauen aus Essen

Versaute Teenies ab 18 gerade live vor der eigenen webcam. Willst du es ihnen besorgen? Melde dich jetzt gratis an und du erhälst gleich 50 Coins für die sexcams kostenlos! Beobachte geile [b][url=http://2-cam.com]gratis camsex[/url][/b] ! Gay Sexcam spermaspritzen zofenausbildung Gratis Cam to studentinnen sex ebony bitch Private Clips lustvoll Erotik livecam wichsen miniroecke amateur shot Asian Cum Shot. [url=http://amateur--sex.info][img]http://6sx.org/sexbilder/geile-amateure-free-sexcam.jpg[/img][/url] livesex mit girls aus deiner nachbarschaft

http://fine-w.com/bbs/view.php?desc=asc&divpage=1&id=gallery&no=41&page=1&sc=on&select_arrange=headnum&sn=off&sn1=&ss=on http://www.dentway.kr/bbs/view.php?id=contact&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=234 http://www.ikastetiket.dk/support/forum/spoergsmaal/mine-strygemaerker-falder-af-hvad-goer-jeg-forkert/#post-217 http://www.c7carbon.com/forum/1997-2004-chevrolet-corvette-c5/ficken-mit-lesben-aus-deiner-stadt/new/ http://bbs.wulin2.wanmei.com/home.php?mod=space&uid=15789744

by bigybx on Mar 25, 2015

Рекомендуем наш интернет-магазин

Рекомендуем наш интернет-магазин http://www.big-butik.ru/

by SexcamDoub on Mar 28, 2015

sex mit frauen aus Württemberg

Süsse Teens ab 18 gerade live hinter der privaten sex cam. Willst du mit ihnen chatten? Melde dich jetzt kostenlos an und du bekommst sofort 50 Coins für die liveshow umsonnst! Beobachte tabulose [b][url=http://www.teen-sex.me/]free cams[/url][/b] ; Hausfrauen Sex gratis cam teen parkplatz treffen live webcam chat gaychat sexcam topliste topcams Affaire daily free porn handschellen grosse moepse amateur luder telefonsex und cam.

mature fucking live gay sex livejasmine girls free porn gallery topcams Hausfrau webcam adult free live webcam chat bukkake gaychat bumstreffen sexcam topliste .

http://yeunjigonji.com/bbs/view.php?id=order&no=6890 http://www.edumarathon.pl/index.php/blog/15-biegiem-przez-ycie/46-will-smith-bieganie-i-czytanie-klucz-do-ycia.html http://forum.proita.com/forum/home.php?mod=space&uid=119043 http://almatyregion-onko.kz/index.php/ru/item/eeiusmod-tempor.html#comment-1134 http://www.gfchocolate.com/discussion/amateur-cams-mit-frauen-aus-deiner-nachbarschaft

by SexcamDoub on Mar 30, 2015

amateur cams mit huren aus Augsburg

Versaute Teens ab 18 immer live vor der eigenen web cam. Willst du es ihnen besorgen? Melde dich jetzt gratis an und du bekommst sofort 50 Coins für die liveshow gratis! Schau tabulose [b][url=http://www.camsex-kostenlos.com/]sex cams[/url][/b] ; WebcamSex ebony porn amateur live cams fkk hard free porn gallery nachbarin sabrina Flirt Liebe ebony porn sex lexikon gaychat amateur luder kostenlos webcam geile webcam private. [url=http://freesexcam23.info][img]http://6sx.org/sexbilder/free-sexcam-sex-dating.jpg[/img][/url] sex treffen mit lesben aus deiner stadt

http://artesmarciales.cl/foro/showthread.php?tid=47869&pid=190428#pid190428 http://heart-place.com/sample/log/eid1.html? http://www.nwhelicopters.com/nwh/phpBB2/profile.php?mode=viewprofile&u=1136827 http://www.lostcircuits.com/forum/viewtopic.php?f=2&t=23340 http://www.omgroceries.com/forum/showthread.php?tid=4076&pid=72448#pid72448

New Comment

markdown formatting permitted