I’m trying to create a simple authentication system but am failing
miserably. I’m (sort of) following the “Logging In” chapter of the Agile
book. Ideally, any access to http://example.com/publish (and any of its
subdirectories) should redirect to http:/example.com/publish/login when
there is no valid session user_id.
Code so far:
controller
class PublishController < ApplicationController
before_filter :authenticate, :except => [:login, :login_user]
def login
if request.post?
logged_in_user = @user.attempt_login
if logged_in_user
session[:user_id] = logged_in_user.id
redirect_to(:action => ‘index’)
else
flash[:notice] = ‘Invalid username or password. Please try
again’
end
end
end
def self.authenticate
unless session[:user_id]
redirect_to :action => ‘login’
end
end
end
#model
class User < ActiveRecord::Base
require “digest/sha1”
attr_accessor :password
attr_accessible :username, :password, :first_name, :last_name, :email
validates_uniqueness_of :username
validates_presence_of :username, :first_name, :last_name, :email
validates_length_of :password, :within => 5…40, :on => :create
def before_create
self.sha_password = User.encrypt(self.password)
end
def after_create
@password = nil
end
private
def self.encrypt(password)
Digest::SHA1.hexdigest(password)
end
def self.login_user(username, password)
encrypted_password = encrypt(password || “”)
find(:first, :conditions => [“username = ? and sha_password = ?”,
username, encrypted_password])
end
def attempt_login
User.login_user(self.username, self.password)
end
end
If I browse to, say, http://example.com/publish/user/list I get a
NoMethodError in Publish#user:
undefined method `authenticate’ for #PublishController:0x387ab58W
When I browse to http://example.com/publish/login/ I see the login form
but
upon submit I get another NoMethodError in Publish#login:
You have a nil object when you didn’t expect it!
The error occured while evaluating nil.attempt_login
I’m totally stumped and appreciate any help.
Greg