Skip to main content

Basic User Authentication in Rails | Aidan Finn's home page

Popularity Report

Total Popularity Score: 0

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Rank

Public Sticky notes

The rails way seems to be to put as much logic as possible into the models. To think of it another way, you should be able to run your application through all its important processes by calling methods on model objects at the console. More concretely core logic such as authentication and sending a new password should be in the model, not the controller.

Highlighted by joel

We start out by defining validations for the user model. password and login must be within pre-defined length. login and email must be unique. email must match a certain format. validates_confirmation_of ensures that password must be confirmed using password_confirmation. login, email, password, password_confirmation and salt must all be present. When creating a new user or saving an existing one, all these conditions must be met or the save will fail.

Highlighted by draconid

def edit @item=Blog.find(:first, :conditions=>["user_id=? and id=?", current_user.id, params[:id]]) ... end

Highlighted by draconid

Alternatively you could require users to validate using email. This would mean adding a field to the database with a validation key. Put a random unique hash in this field when the user is created. Don’t allow a user to login unless this field is null. Add a controller method and view to validate users using this hash key and email them a link to this with their own key as a parameter when they signup.

Highlighted by draconid

The functions in the

The functions in the application.rb file are very useful, but how does one use them in the views?

For example, if I want to show a link to a user only if logged in, this doesn't work:

<% if current_user -%>
<a href="http://www.aidanf.net/admin">Admin Functions</a>
<% end -%>

because current_user is not available to the view.

Just add:helper_method

Just add:

helper_method :current_user after the ApplicationController#current_user definition:

def current_user
session[:user]
end
helper_method :current_user

I did this to create a logged_in? method (as in acts_as_authenticated) that is available to the views and the controllers:

def logged_in?
return session[:user] ? true : false
end
helper_method :logged_in?

Highlighted by draconid