class CGI::Session
session.close
session = CGI::Session.new(cgi, ‘new_session’ => true)
end
rescue ArgumentError # if no old session
session.delete
session = CGI::Session.new(cgi, ‘new_session’ => false)
begin
# from being maliciously hijacked later on.
# not just to free resources, but to prevent the session
# We make sure to delete an old session if one exists,
cgi = CGI.new(“html4”)
require ‘cgi/session’
require ‘cgi’
=== Creating a new session safely<br><br>session.close<br>end<br>session = “guest”
elsif !session[‘user_name’]<br>session = cgi.to_s
# string-like CGI::QueryExtension::Value
# coerce to String: cgi[] returns the
if cgi.has_key?(‘user_name’) and cgi != ”
‘prefix’ => ‘pstore_sid_’) # PStore option
’session_expires’ => Time.now + 30 * 60, # 30 minute timeout
’session_key’ => ‘_rb_sess_id’, # custom session key
’database_manager’ => CGI::Session::PStore, # use PStore
session = CGI::Session.new(cgi,
cgi = CGI.new(“html4”)
require ‘cgi/session/pstore’ # provides CGI::Session::PStore
require ‘cgi/session’
require ‘cgi’
=== Setting the user’s name
== Examples of use
is not automatically handled.
input to HTML forms created by other mechanisms. Also, session expiry
attribute and manually encoding it in URLs and adding it as a hidden
responsible for extracting the session id from the session_id
provided for other mechanisms, such as URL re-writing. The caller is
using the CGI#form() HTML generation method. No built-in support is
add the session id as a hidden input field to all forms generated
CGI::Session class in conjunction with the CGI class will transparently
as a parameter of all requests sent by the client to the server. The
If the client has cookies disabled, the session id must be included
if the client has cookies enabled.
provides transparent support for session id communication via cookies
The simplest way to do this is via cookies. The CGI::Session class
to maintain a reference to this session state.
id must be passed backwards and forwards between client and server
Most session state is maintained on the server. However, a session
== Maintaining the session id.
things will break nastily!
and clients still have old sessions lying around in cookies, then
making sure that filenames will be different
same name. If your application switches from one to the other without
that by default the FileStore and PStore session data files have the
Changing storage type mid-session does not work. Note in particular
delete
close
update
restore # returns hash of session data.
new(session, options)
the following methods:
Custom storage types can also be created by defining a class with
and provides file-locking and transaction support.
cgi/session/pstore.rb. Supports data of any type,
CGI::Session::PStore- stores data in Marshalled format. Provided by
interpreter instance does.
only persists for as long as the current Ruby
CGI::Session::MemoryStore - stores data in an in-memory hash. The data
storage type.
works with String data. This is the default
CGI::Session::FileStore -
stores data as plain text in a flat file. Only
following storage classes are provided as part of the standard library:
data with thedatabase_manager
option to CGI::Session::new. The
The caller can specify what form of storage to use for the session’s
== Storing session state
method.
finishing session processing for this request, call the update()
to store the session’s state to persistent storage without
store the session’s state to persistent storage. If you want
session should be closed using the close() method. This will
When session processing has been completed for a request, the
are not supported).
using ‘[]’, much the same as hashes (although other hash methods
This data can be set and retrieved by indexing the Session instance
The Session class associates data with a session as key-value pairs.
== Setting and retrieving session data.
a new session with the old session’s id.
makes another request with the same id, the effect will be to start
does not however remove the session id from the client. If the client
#delete() deletes a session from session storage. It
never create a new session. See #new() for more details.
exist. Thenew_session
option can be used to either always or
exists, or continue the current session for this client if one does
this CGI::Session instance will start a new session if none currently
A CGI::Session instance is created from a CGI object. By default,
== Lifecycle
HTTP request/response protocol.
to the user. This adds state information to the otherwise stateless
and server with every request and response, transparently
on the server between requests. A session id is passed between client
Information associated with the session is stored
and responses linked together and associated with a single client.
support for CGI scripts. A session is a sequence of HTTP requests
This file provides the CGI::Session class, which provides session
== Overview
- stores data in an in-memory hash. The data
- stores data in Marshalled format. Provided by
def [](key)
def [](key) @data ||= @dbman.restore @data[key] end
def []=(key, val)
def []=(key, val) @write_lock ||= true @data ||= @dbman.restore @data[key] = val end
def close
Store session data on the server and close the session storage.
def close @dbman.close @dbprot.clear end
def create_new_id
a random number, and a constant string. This routine is
if possible, otherwise an SHA512 hash based upon the time,
The session id is a secure random number by SecureRandom
Create a new session id.
def create_new_id require 'securerandom' begin # by OpenSSL, or system provided entropy pool session_id = SecureRandom.hex(16) rescue NotImplementedError # never happens on modern systems require 'digest' d = Digest('SHA512').new now = Time::now d.update(now.to_s) d.update(String(now.usec)) d.update(String(rand(0))) d.update(String($$)) d.update('foobar') session_id = d.hexdigest[0, 32] end session_id end
def delete
Note that the session's data is _not_ automatically deleted
Delete the session from storage. Also closes the storage.
def delete @dbman.delete @dbprot.clear end
def initialize(request, option={})
end
undef_method :fieldset
class << cgi
cgi = CGI.new("html4")
(see https://blade.ruby-lang.org/ruby-list/37805)
use of fieldsets with code similar to the following
is _not_ invisible on many browsers; you may wish to disable the
fields are surrounded by a
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.cookies[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'] option['session_path'] elsif ENV["SCRIPT_NAME"] File::dirname(ENV["SCRIPT_NAME"]) else "" end) ] unless option['no_cookies'] end @dbprot = [@dbman] ObjectSpace::define_finalizer(self, Session::callback(@dbprot)) end
def new_store_file(option={}) # :nodoc:
Defaults to the empty string.
the filename for this session's FileStore file.
suffix:: the prefix to add to the session id when generating
Defaults to "cgi_sid_".
the filename for this session's FileStore file.
prefix:: the prefix to add to the session id when generating
on Unix systems).
file. Defaults to Dir::tmpdir (generally "/tmp"
tmpdir:: the directory to use for storing the FileStore
following options are recognised:
+option+ is a hash of options for the initializer. The
digested session id, and _suffix_.
This path is generated under _tmpdir_ from _prefix_, the
does.
This file will be created if it does not exist, or opened if it
Create a new file to store the session data.
def new_store_file(option={}) # :nodoc: dir = option['tmpdir'] || Dir::tmpdir prefix = option['prefix'] suffix = option['suffix'] require 'digest/md5' md5 = Digest::MD5.hexdigest(session_id)[0,16] path = dir+"/" path << prefix if prefix path << md5 path << suffix if suffix if File::exist? path hash = nil elsif new_session hash = {} else raise NoSession, "uninitialized session" end return path, hash end
def update
Store session data on the server. For some session storage types,
def update @dbman.update end