Reputation: 6165
I'm trying to make a stripped-down user sessions system, and tried to model it to be similar to authlogic.
class UserSession
attr_accessor :username
def initialize(params={})
@username = params[:username]
end
def new_record?
true
end
def self.find
return nil if session[:username].nil?
UserSession.new session[:username]
end
def save
session[:username] = username
session[:username] == username
end
def user
User.find :first, :conditions => { :username => username }
end
def destroy
session[:username] = nil
end
end
I know there's no passwords or anything, but let's put that aside for the moment. My problem is that apparently it is not easy to and bad form to access the session from a model. Which leads me to wonder, how exactly am I supposed to abstract creating user sessions as a model, if I can't access the session?
Upvotes: 1
Views: 332
Reputation: 2640
Normally what I'd do is create a SessionsController, that manages the state of the UserSession (attributes, handling the authentication through the model, etc) and uses the sessions from the app:
class SessionsController < ApplicationController
def new; UserSession.new; end
def create
@user_session = UserSession.new(params)
if id = @user_session.user
session[:current_user] = id
redirect_to session[:last_url]
else
session[:current_user] = nil
render :action => new
end
end
end
def destroy
session[:current_user] = nil
redirect_to root_path
end
A helper ( def current_user; session[:current_user]; end
) could also help. Basically the UserSession allows you to use form_for and similar helpers and act as a authentication strategy holder (when you implement).
Hope this can help you get started :)
Upvotes: 2