Topic: Restful Authentication with all the bells and whistles (new 9/05/08)

This is a new restful authentication tutorial based the lastest version of the plugin and edge rails as of 9/05/08. The original tutorial can be found at http://railsforum.com/viewtopic.php?pid=74245#p74245

The source code is now available on github.com at http://github.com/activefx/restful_auth … ree/master Since this new tutorial will be less of a step by step instruction guide and more of an overview and description of the files in the application, I suggest you grab the app from github to work with. Currently the tutorial assumes a working knowledge of Git, however I'm almost done with a beginner's tutorial for Git if you don't have an understanding of it yet.

To set up the application from the source code on github, follow these instructions:
  - git clone git://github.com/activefx/restful_authentication_tutorial.git
  - cd restful_authentication_tutorial
  - git submodule init
  - git submodule update
  - Set up database.yml file
  - Set up config.yml file (repeat as necessary for test and production environments)
  - Change the login and password for the admin user in the _set_up_first_admin_user.rb migration
  - Change contact_site method in application.rb to redirect to your site's contact form or info
  - rake db:create:all or db:create
  - rake db:migrate

Current features include:
  - Namespaced admin and user sections
  - Login / Logout
  - OpenID Authentication with support for incomplete OpenID profiles
  - Roles and permissions
  - Administrative user controller
    - Set roles, activate, enable / disable users 
  - Member list and public profiles for logged in users
  - Activation, with option to resend activation code
  - Beta invitation system with easy on/off functionality
  - Forgot Password / Reset Password
  - Change Password
  - Failed login attempts database logging
  - Recaptcha displayed for more than 5 failed logins
  - Helper methods (link_to_user, if_admin?, etc.)
  - Configuration file
  - 404 handling and database logging
  - Yahoo User Interface 3 CSS template
  - Nested layouts
  - Authentication Plugins
    - restful_authentication, open_id_authentication, role_requirement, recaptcha
  - UI Plugins
    - custom-err-msg, permalink_fu, uberkit, will_paginate
  - Debug Plugins
    - exception_logger, rails-footnotes, query_analyzer, query_stats, rows_logger
  - Development Plugins
    - auto_migrations
  - Testing
    - rspec, rspec_rails

This is a very preliminary release of the application and has not been fully tested or security audited. Please feel free to fork and improve, or message me with any feature requests, suggestions, bugs, fixes for the known issues, resources, etc. The Todo list in the readme is listed in order of urgency and I'm going to try and add those features to the application in that order.

There are couple of things you want to do to get started. Generate the rails application, initialize a git repository, install the restful_authentication, open_id_authentication, role_requirement, rspec, rspec_rails, and will_paginate plugins (the other plugins are optional), vendor edge rails, and run the generators for restful_authentication, open_id_authentication, role_requirement, and rspec. (Note that the sample app is locked to certain versions of the plugins and edge rails, so if you're working through the tutorial this way there is a chance everything won't work together properly.)

The rest of the tutorial will be posted soon. I just wanted to get some feedback on the application and make sure it works as expected.

Last edited by activefx (2008-09-12 06:38:57)

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Thanks for the tutorial - looks very good and complete....

One thing that has me a bit confused with these Authentication examples is how to set one up for a public site ( i.e. a social networking site ) and setting one up for a private admin part of a site.

Could you give me a few tips on what the key differences would be.

Thanks - Dave Porter

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Excellent article, I'm sure you'll get a lot of praise as well as queries.

I certainly intend to make use of your article as I think it'll work perfectly with a sub-domain application I'm working on.

Thanks,

Steve.

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Great tutorial makes me want to look at how I'm handle user management in my blog. Thanks for taking the time to post it.

DaveP you may want to look into something like role requirement to handle who can do what. I use it in the blog script that I posted for you to look at. I used the multiple roles for multiple users way but you can also do it where each user only has one role. May be worth looking into.
You can get it at http://code.google.com/p/rolerequirement/

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

@DaveP: It depends how you want to set up your social network. For completely public areas, you just wouldn't use any before filters in your controllers. For the admin section / controller, you would use "before_filter :check_administrator_role".

There are a couple of ways to allow only friends of a user to view their profile. First, you would have to model the friends relationship similar to the roles relationship, where a user has many friends through friendships or relationships, except that you don't generate a friend model as well. First generate a friendship model:

class CreateFriendships < ActiveRecord::Migration
  def self.up
    create_table :friendships do |t|
      t.integer :user_id, :friend_id, :null => false
      t.timestamps
    end
   
  def self.down
      drop_table :friendships
  end
end

Then edit the friendship model:
class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end

Using the class name paramater allows a table to reference itself, so that users can be friends with other users.

Then in the user model:

has_many :friendships
has_many :friends, :through => :friendships

Also in the user model we need a way to check if a user is friends with another user:
def has_friend?(friend)
  self.friends.find(friend) ? true : false
end

Now, if you wanted to completely block a user from viewing a profile they aren't friends with, you could put a conditional in the show action of the controller that handles user's profiles.
def show
  @user = User.find(params[:id])
  unless current_user.has_friend?(@user)
    flash[:errors]...
    redirect_to...
  end
end

If you just wanted to hide portions of the view if the users aren't friends, you could use a similar conditional in the view:
<% if current_user.has_friend?(@user) %>
  show private information
<% else %>
  show nothing or public information
<% end %>

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Hey there!

Great tutorial! Is it possible that you can upload all of the files somewhere?

Thank you so much!

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

With regards to this tutorial, must the version of Rails be 2.0.2 in order for it to work?

I tried this code:
ruby script/generate scaffold Page title:string body:text

and the error is:
wrong constant name Title:stringController

Can someone tell me what's wrong?

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Yep, this is Rails 2 specific...

With 1.2.X you have to go back to the style of migrations used then.

regards, DaveP

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Great tutorial.

Just wanted to point out that you haven't posted your views for the passwords controller. Apart from that everything looks good.

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Also I was wondering why you've nested the password resource inside the user resource?

Surely you need to know the user ID to do this? Which you won't have due to the user not knowing their password?

Hope that makes sense. I could be wrong.

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

jimneath wrote:

Also I was wondering why you've nested the password resource inside the user resource?

Surely you need to know the user ID to do this? Which you won't have due to the user not knowing their password?

Hope that makes sense. I could be wrong.

I have run across this as well as another bug I am getting. Unless I check "remember me" the login system does not work. Any ideas why?

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Here are the password views, I'll add them above as well.

app/views/passwords/edit.html.erb

<% form_tag url_for(:action => "update", :id => params[:id]) do %>
    Password:<br />
    <%= password_field_tag :password %><br />
    Confirm Password:<br />
    <%= password_field_tag :password_confirmation %><br />
    <%= submit_tag "Reset Your Password" %>
<% end %>

app/views/passwords/new.html.erb
<h2>Forgot Password</h2>
<% form_tag url_for(:action => 'create') do %>
    What is the email address used to create your account?<br />
    <%= text_field_tag :email, "", :size => 50 %><br />
    <%= submit_tag 'Reset Password' %>
<% end %>

@jimneath: You're right, it shouldn't be nested. It still worked because the default route was catching it. 

@jstad: Can you post the error message you're getting?

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

I found my own error. It was calling the default session[:user] and not session[:user_id]. I am go glad you posted something like this on here. I am actively modifying your code and it is a pleasure to do! Something like this is a GREAT tool for people to learn the in's and out's of the restful_authenication plugin! smile

Regards,
Justin

PS - I will also actively watch this thread to help out where I can. So if you want something added or changed please let me know smile

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

I keep getting errors about the methods in authenticated_system.rb. Any idea why? I went through the tutorial twice and am getting the same errors. How does rails reference that file in /lib/?

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

etandrib wrote:

I keep getting errors about the methods in authenticated_system.rb. Any idea why? I went through the tutorial twice and am getting the same errors. How does rails reference that file in /lib/?

If you could please post the code for your authenticated_system.rb file. I can take a look. I am also available on IRC in #rubyonrails on freenode smile

Also, to answer how the lib folder is used is for methods that pertain to your rails code. Usually a list of relevant methods will appear there as a 'library' hense the lib name. (This is a quick explanation, hope it helps.)

Last edited by jstad (2008-01-11 20:06:47)

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Super Tutorial. Thanks, this is great!  One thing you may want to consider adding which I did was a simple method for forgot_login which would just send the user.login of the specified email to the given email.  Also I had to add:

<% if flash[:notice] %><div class="notice"><%= flash[:notice] %></div><% end %>
<% if flash[:error] %><div class="error"><%= flash[:error] %></div><% end %>

to the sessions/new.html.erb and passwords/* in order to recieve proper error messages, not sure if that is standard or not but only way I could get notice and error messgaes.

I had one small problem with the forgot_password method. Was able to get everything to work except when a user clicked the reset_password link from the email to reset, then submitted a new password, the controller seemed to think the reset token was invalid but actually did reset the password.  Any idea on this?

One other thing I'm not clear on is the usage of .erb files.  Seems using these as standard .rhtml files works fine but not sure the difference or if this is just 2.0 specific. Can anyone shed any light on that?  Thanks --ken

Last edited by kschroed (2008-01-12 21:08:40)

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

kschroed wrote:

One other thing I'm not clear on is the usage of .erb files.  Seems using these as standard .rhtml files works fine but not sure the difference or if this is just 2.0 specific. Can anyone shed any light on that?  Thanks --ken

.html.erb files is the exact same as .rhtml files. it was just changed to be more clear that it is html files with erb code inside of them. I dunno the rails gods found it necessary. *rolleyes*

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Thanks for this awesome walkthrough!
My question is, shouldnt this:

class Role < ActiveRecord::Base
  has_many :permissions
  has_many :roles, :through => :permissions
end

have the 3rd line changed to
has_many :users, :through => :permissions
?
not sure how the roles-to-roles relationship benefits anyone.

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

austinfromboston wrote:

Thanks for this awesome walkthrough!
My question is, shouldnt this:

class Role < ActiveRecord::Base
  has_many :permissions
  has_many :roles, :through => :permissions
end

have the 3rd line changed to
has_many :users, :through => :permissions
?
not sure how the roles-to-roles relationship benefits anyone.

Yes you are correct. It should be users not roles smile I guess I auto-corrected that typo when i followed his tutorial lol

Re: Restful Authentication with all the bells and whistles (new 9/05/08)

Excellent tutorial, one possible error though , the Application Controller should have the  following to include the functions of AuthenticatedSystem :

include AuthenticatedSystem

Hein Van Der Merwe