Sha256: 53a9c6362b9d00b2feaddb3f08d6a3c34e9cce2ac9bc71be6854183aa80c51ef

Contents?: true

Size: 1.69 KB

Versions: 3

Compression:

Stored size: 1.69 KB

Contents

# * George Moschovitis  <gm@navel.gr>
# (c) 2004-2005 Navel, all rights reserved.
# $Id$

require 'md5'
require 'webrick'

require 'glue/attribute'

require 'nitro/cookie'

module N
	
# A web application session. 
#
# State is a neccessary evil but session variables should
# be avoided as much as possible. Session state is typically
# distributed to many servers so avoid storing complete 
# objects in session variables, only store oids and small
# integer/strings.
# 
# The session should be persistable to survive server 
# shutdowns.

class Session < Hash

	# Session id salt.

	cattr_accessor :session_id_salt, 'SALT'

	# The name of the cookie that stores the session id.

	cattr_accessor :cookie_name, 'nsid'

	# The sessions 

	cattr_accessor :manager; @@manager = {}

	# The unique id of this session.

	attr_reader :session_id

	def self.lookup(context)
		if cookie = context.cookies[Session.cookie_name]
			session = context.sessions[cookie]
		end

		unless session
			session = Session.new(context)
			context.add_cookie(Cookie.new(Session.cookie_name, session.session_id))
			context.sessions[session.session_id] = session
		end
		
		return session
	end

	# Create the session for the given context.

	def initialize(context = nil)
		@session_id = create_id
	end

protected
	
	# Calculates a unique id.
	#
	# The session id must be unique, a monotonically 
	# increasing function like time is appropriate. Random 
	# may produce equal ids? add a prefix (SALT) to stop 
	# hackers from creating session_ids.
	
	def create_id
		now = Time.now
		md5 = Digest::MD5.new
		md5.update(now.to_s)
		md5.update(now.usec.to_s)
		md5.update(rand(0).to_s)
		md5.update(Session.session_id_salt)
		md5.hexdigest
	end

end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nitro-0.10.0 lib/nitro/session.rb
nitro-0.9.3 lib/nitro/session.rb
nitro-0.9.5 lib/nitro/session.rb