Class: CGI::Session
- Inherits:
-
Object
- Object
- CGI::Session
- Defined in:
- lib/cgi/session.rb,
lib/cgi/session/pstore.rb
Overview
Class representing an HTTP session. See documentation for the file cgi/session.rb for an introduction to HTTP sessions.
Lifecycle
A CGI::Session instance is created from a CGI object. By default, this CGI::Session instance will start a new session if none currently exists, or continue the current session for this client if one does exist. The new_session
option can be used to either always or never create a new session. See #new() for more details.
#delete() deletes a session from session storage. It does not however remove the session id from the client. If the client makes another request with the same id, the effect will be to start a new session with the old session's id.
Setting and retrieving session data.
The Session class associates data with a session as key-value pairs. This data can be set and retrieved by indexing the Session instance using '[]', much the same as hashes (although other hash methods are not supported).
When session processing has been completed for a request, the session should be closed using the close() method. This will store the session's state to persistent storage. If you want to store the session's state to persistent storage without finishing session processing for this request, call the update() method.
Storing session state
The caller can specify what form of storage to use for the session's data with the database_manager
option to CGI::Session::new. The following storage classes are provided as part of the standard library:
- CGI::Session::FileStore
-
stores data as plain text in a flat file. Only works with String data. This is the default storage type.
- CGI::Session::MemoryStore
-
stores data in an in-memory hash. The data only persists for as long as the current ruby interpreter instance does.
- CGI::Session::PStore
-
stores data in Marshalled format. Provided by cgi/session/pstore.rb. Supports data of any type, and provides file-locking and transaction support.
Custom storage types can also be created by defining a class with the following methods:
new(session, )
restore # returns hash of session data.
update
close
delete
Changing storage type mid-session does not work. Note in particular that by default the FileStore and PStore session data files have the same name. If your application switches from one to the other without making sure that filenames will be different and clients still have old sessions lying around in cookies, then things will break nastily!
Maintaining the session id.
Most session state is maintained on the server. However, a session id must be passed backwards and forwards between client and server to maintain a reference to this session state.
The simplest way to do this is via cookies. The CGI::Session class provides transparent support for session id communication via cookies if the client has cookies enabled.
If the client has cookies disabled, the session id must be included as a parameter of all requests sent by the client to the server. The CGI::Session class in conjunction with the CGI class will transparently add the session id as a hidden input field to all forms generated using the CGI#form() HTML generation method. No built-in support is provided for other mechanisms, such as URL re-writing. The caller is responsible for extracting the session id from the session_id attribute and manually encoding it in URLs and adding it as a hidden input to HTML forms created by other mechanisms. Also, session expiry is not automatically handled.
Examples of use
Setting the user's name
require 'cgi'
require 'cgi/session'
require 'cgi/session/pstore' # provides CGI::Session::PStore
cgi = CGI.new("html4")
session = CGI::Session.new(cgi,
'database_manager' => CGI::Session::PStore, # use PStore
'session_key' => '_rb_sess_id', # custom session key
'session_expires' => Time.now + 30 * 60, # 30 minute timeout
'prefix' => 'pstore_sid_') # PStore option
if cgi.has_key?('user_name') and cgi['user_name'] != ''
# coerce to String: cgi[] returns the
# string-like CGI::QueryExtension::Value
session['user_name'] = cgi['user_name'].to_s
elsif !session['user_name']
session['user_name'] = "guest"
end
session.close
Creating a new session safely
require 'cgi'
require 'cgi/session'
cgi = CGI.new("html4")
# We make sure to delete an old session if one exists,
# not just to free resources, but to prevent the session
# from being maliciously hijacked later on.
begin
session = CGI::Session.new(cgi, 'new_session' => false)
session.delete
rescue ArgumentError # if no old session
end
session = CGI::Session.new(cgi, 'new_session' => true)
session.close
Defined Under Namespace
Classes: FileStore, MemoryStore, NoSession, PStore
Instance Attribute Summary collapse
-
#new_session ⇒ Object
readonly
The id of this session.
-
#session_id ⇒ Object
readonly
The id of this session.
Class Method Summary collapse
-
.callback(dbman) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Retrieve the session data for key
key
. -
#[]=(key, val) ⇒ Object
Set the session date for key
key
. -
#close ⇒ Object
Store session data on the server and close the session storage.
-
#delete ⇒ Object
Delete the session from storage.
-
#initialize(request, option = {}) ⇒ Session
constructor
Create a new CGI::Session object for
request
. -
#update ⇒ Object
Store session data on the server.
Constructor Details
#initialize(request, option = {}) ⇒ Session
Create a new CGI::Session object for request
.
request
is an instance of the CGI
class (see cgi.rb). option
is a hash of options for initialising this CGI::Session instance. The following options are recognised:
- session_key
-
the parameter name used for the session id. Defaults to '_session_id'.
- session_id
-
the session id to use. If not provided, then it is retrieved from the
session_key
parameter of the request, or automatically generated for a new session. - new_session
-
if true, force creation of a new session. If not set, a new session is only created if none currently exists. If false, a new session is never created, and if none currently exists and the
session_id
option is not set, an ArgumentError is raised. - database_manager
-
the name of the class providing storage facilities for session state persistence. Built-in support is provided for
FileStore
(the default),MemoryStore
, andPStore
(from cgi/session/pstore.rb). See the documentation for these classes for more details.
The following options are also recognised, but only apply if the session id is stored in a cookie.
- session_expires
-
the time the current session expires, as a
Time
object. If not set, the session will terminate when the user's browser is closed. - session_domain
-
the hostname domain for which this session is valid. If not set, defaults to the hostname of the server.
- session_secure
-
if
true
, this session will only work over HTTPS. - session_path
-
the path for which this session applies. Defaults to the directory of the CGI script.
option
is also passed on to the session storage class initialiser; see the documentation for each session storage class for the options they support.
The retrieved or created session is automatically added to request
as a cookie, and also to its output_hidden
table, which is used to add hidden input elements to forms.
WARNING the output_hidden
fields are surrounded by a <fieldset> tag in HTML 4 generation, which is not invisible on many browsers; you may wish to disable the use of fieldsets with code similar to the following (see blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
cgi = CGI.new("html4")
class << cgi
undef_method :fieldset
end
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'lib/cgi/session.rb', line 245 def initialize(request, option={}) @new_session = false session_key = option['session_key'] || '_session_id' session_id = option['session_id'] unless session_id if option['new_session'] session_id = create_new_id @new_session = true end end unless session_id if request.key?(session_key) session_id = request[session_key] session_id = session_id.read if session_id.respond_to?(:read) end unless session_id session_id, = request.[session_key] end unless session_id unless option.fetch('new_session', true) raise ArgumentError, "session_key `%s' should be supplied"%session_key end session_id = create_new_id @new_session = true end end @session_id = session_id dbman = option['database_manager'] || FileStore begin @dbman = dbman::new(self, option) rescue NoSession unless option.fetch('new_session', true) raise ArgumentError, "invalid session_id `%s'"%session_id end session_id = @session_id = create_new_id unless session_id @new_session = true retry end request.instance_eval do @output_hidden = {session_key => session_id} unless option['no_hidden'] @output_cookies = [ Cookie::new("name" => session_key, "value" => session_id, "expires" => option['session_expires'], "domain" => option['session_domain'], "secure" => option['session_secure'], "path" => if option['session_path'] then option['session_path'] elsif ENV["SCRIPT_NAME"] then File::dirname(ENV["SCRIPT_NAME"]) else "" end) ] unless option['no_cookies'] end @dbprot = [@dbman] ObjectSpace::define_finalizer(self, Session::callback(@dbprot)) end |
Instance Attribute Details
#new_session ⇒ Object (readonly)
The id of this session.
162 163 164 |
# File 'lib/cgi/session.rb', line 162 def new_session @new_session end |
#session_id ⇒ Object (readonly)
The id of this session.
162 163 164 |
# File 'lib/cgi/session.rb', line 162 def session_id @session_id end |
Class Method Details
.callback(dbman) ⇒ Object
:nodoc:
164 165 166 167 168 |
# File 'lib/cgi/session.rb', line 164 def Session::callback(dbman) #:nodoc: Proc.new{ dbman[0].close unless dbman.empty? } end |
Instance Method Details
#[](key) ⇒ Object
Retrieve the session data for key key
.
305 306 307 308 |
# File 'lib/cgi/session.rb', line 305 def [](key) @data ||= @dbman.restore @data[key] end |
#[]=(key, val) ⇒ Object
Set the session date for key key
.
311 312 313 314 315 |
# File 'lib/cgi/session.rb', line 311 def []=(key, val) @write_lock ||= true @data ||= @dbman.restore @data[key] = val end |
#close ⇒ Object
Store session data on the server and close the session storage.
For some session storage types, this is a no-op.
325 326 327 328 |
# File 'lib/cgi/session.rb', line 325 def close @dbman.close @dbprot.clear end |
#delete ⇒ Object
Delete the session from storage. Also closes the storage.
Note that the session's data is not automatically deleted upon the session expiring.
334 335 336 337 |
# File 'lib/cgi/session.rb', line 334 def delete @dbman.delete @dbprot.clear end |
#update ⇒ Object
Store session data on the server. For some session storage types, this is a no-op.
319 320 321 |
# File 'lib/cgi/session.rb', line 319 def update @dbman.update end |