views:

34

answers:

3

I want to learn how to create my own authentication system, please provide some guidance if am doing this wrong.

  1. I will create a Module in my /lib folder /lib/auth.rb
  2. I will require this module in my ApplicationController.
  3. when a user enters their email + password, I will call a method that will do a lookup in the user's table for a user with the same email, I will then compare the passwords. (i'll add encryption with salt later).
  4. If the user entered the correct credentials, I will create a row in the Sessions table, and then write the session GUID to a cookie.
  5. Now whenever I need to check if the user is logged in, or I need the user object, I will check if the cookie exists, if it does, I will lookup the session table for a row with the same guid, if it exists, I will return the session row and then load the User object.

I realize there are many suggestions one can give, but in a nutshell does this sound like a workable solution?

Now to make this usable, I will have to make some helper methods in my ApplicationController right?

How will I access the current_user from within my views?

P.S I know of other authentication systems, I just want to learn how to create my own.

A: 

You should really check out the authlogic gem on github. http://github.com/binarylogic/authlogic It also has great instructions on how to set up your users.

jtmkrueger
+1  A: 

The basic logic you're following is correct. Of course you can always expand on this with features that you need. For instance, you'll need helper methods for things like "logged_in?" and "current_user". Also, you might want to add session expiry, or session retention as a "remember me" feature.
Go for it, you won't learn authentication systems better than building your own then figuring what's wrong with it.

Faisal
A: 

After Faisal said what I would say, I only give you answer to the last part of your question: "How will I access the current_user from within my views?"

try something like this:

class User < ...
  def self.current=(u)
    @current = u
  end
  def self.current
    @current
  end
end

In your views (or any part of your code) you can call User.current. Your controller has to assign a validated user to User.current. Your filters can react to "if User.current.nil?" and so on.

If you want to be thread safe, you may use a thread variable instead of @current:

Thread.current[:current_user] = u
Arsen7