1Catalyst::Plugin::SessiUosne(r3)Contributed Perl DocumenCtaattailoynst::Plugin::Session(3)
2
3
4

NAME

6       Catalyst::Plugin::Session - Generic Session plugin - ties together
7       server side storage and client side state required to maintain session
8       data.
9

SYNOPSIS

11           # To get sessions to "just work", all you need to do is use these plugins:
12
13           use Catalyst qw/
14             Session
15             Session::Store::FastMmap
16             Session::State::Cookie
17             /;
18
19           # you can replace Store::FastMmap with Store::File - both have sensible
20           # default configurations (see their docs for details)
21
22           # more complicated backends are available for other scenarios (DBI storage,
23           # etc)
24
25
26           # after you've loaded the plugins you can save session data
27           # For example, if you are writing a shopping cart, it could be implemented
28           # like this:
29
30           sub add_item : Local {
31               my ( $self, $c ) = @_;
32
33               my $item_id = $c->req->param("item");
34
35               # $c->session is a hash ref, a bit like $c->stash
36               # the difference is that it' preserved across requests
37
38               push @{ $c->session->{items} }, $item_id;
39
40               $c->forward("MyView");
41           }
42
43           sub display_items : Local {
44               my ( $self, $c ) = @_;
45
46               # values in $c->session are restored
47               $c->stash->{items_to_display} =
48                 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
49
50               $c->forward("MyView");
51           }
52

DESCRIPTION

54       The Session plugin is the base of two related parts of functionality
55       required for session management in web applications.
56
57       The first part, the State, is getting the browser to repeat back a
58       session key, so that the web application can identify the client and
59       logically string several requests together into a session.
60
61       The second part, the Store, deals with the actual storage of
62       information about the client. This data is stored so that the it may be
63       revived for every request made by the same client.
64
65       This plugin links the two pieces together.
66

RECOMENDED BACKENDS

68       Session::State::Cookie
69           The only really sane way to do state is using cookies.
70
71       Session::Store::File
72           A portable backend, based on Cache::File.
73
74       Session::Store::FastMmap
75           A fast and flexible backend, based on Cache::FastMmap.
76

METHODS

78       sessionid
79           An accessor for the session ID value.
80
81       session
82           Returns a hash reference that might contain unserialized values
83           from previous requests in the same session, and whose modified
84           value will be saved for future requests.
85
86           This method will automatically create a new session and session ID
87           if none exists.
88
89           You can also set session keys by passing a list of key/value pairs
90           or a hashref.
91
92               $c->session->{foo} = "bar";      # This works.
93               $c->session(one => 1, two => 2); # And this.
94               $c->session({ answer => 42 });   # And this.
95
96       session_expires
97       session_expires $reset
98           This method returns the time when the current session will expire,
99           or 0 if there is no current session. If there is a session and it
100           already expired, it will delete the session and return 0 as well.
101
102           If the $reset parameter is true, and there is a session ID the
103           expiry time will be reset to the current time plus the time to live
104           (see "CONFIGURATION"). This is used when creating a new session.
105
106       flash
107           This is like Ruby on Rails' flash data structure. Think of it as a
108           stash that lasts for longer than one request, letting you redirect
109           instead of forward.
110
111           The flash data will be cleaned up only on requests on which
112           actually use $c->flash (thus allowing multiple redirections), and
113           the policy is to delete all the keys which haven't changed since
114           the flash data was loaded at the end of every request.
115
116               sub moose : Local {
117                   my ( $self, $c ) = @_;
118
119                   $c->flash->{beans} = 10;
120                   $c->response->redirect( $c->uri_for("foo") );
121               }
122
123               sub foo : Local {
124                   my ( $self, $c ) = @_;
125
126                   my $value = $c->flash->{beans};
127
128                   # ...
129
130                   $c->response->redirect( $c->uri_for("bar") );
131               }
132
133               sub bar : Local {
134                   my ( $self, $c ) = @_;
135
136                   if ( exists $c->flash->{beans} ) { # false
137
138                   }
139               }
140
141       clear_flash
142           Zap all the keys in the flash regardless of their current state.
143
144       keep_flash @keys
145           If you want to keep a flash key for the next request too, even if
146           it hasn't changed, call "keep_flash" and pass in the keys as
147           arguments.
148
149       delete_session REASON
150           This method is used to invalidate a session. It takes an optional
151           parameter which will be saved in "session_delete_reason" if
152           provided.
153
154           NOTE: This method will also delete your flash data.
155
156       session_delete_reason
157           This accessor contains a string with the reason a session was
158           deleted. Possible values include:
159
160           ·   "address mismatch"
161
162           ·   "session expired"
163
164       session_expire_key $key, $ttl
165           Mark a key to expire at a certain time (only useful when shorter
166           than the expiry time for the whole session).
167
168           For example:
169
170               __PACKAGE__->config('Plugin::Session' => { expires => 1000000000000 }); # forever
171
172               # later
173
174               $c->session_expire_key( __user => 3600 );
175
176           Will make the session data survive, but the user will still be
177           logged out after an hour.
178
179           Note that these values are not auto extended.
180
181       change_session_id
182           By calling this method you can force a session id change while
183           keeping all session data. This method might come handy when you are
184           paranoid about some advanced variations of session fixation attack.
185
186           If you want to prevent this session fixation scenario:
187
188               0) let us have WebApp with anonymous and authenticated parts
189               1) a hacker goes to vulnerable WebApp and gets a real sessionid,
190                  just by browsing anonymous part of WebApp
191               2) the hacker inserts (somehow) this values into a cookie in victim's browser
192               3) after the victim logs into WebApp the hacker can enter his/her session
193
194           you should call change_session_id in your login controller like
195           this:
196
197                 if ($c->authenticate( { username => $user, password => $pass } )) {
198                   # login OK
199                   $c->change_session_id;
200                   ...
201                 } else {
202                   # login FAILED
203                   ...
204                 }
205

INTERNAL METHODS

207       setup
208           This method is extended to also make calls to
209           "check_session_plugin_requirements" and "setup_session".
210
211       check_session_plugin_requirements
212           This method ensures that a State and a Store plugin are also in use
213           by the application.
214
215       setup_session
216           This method populates "$c->config('Plugin::Session')" with the
217           default values listed in "CONFIGURATION".
218
219       prepare_action
220           This method is extended.
221
222           Its only effect is if the (off by default) "flash_to_stash"
223           configuration parameter is on - then it will copy the contents of
224           the flash to the stash at prepare time.
225
226       finalize_headers
227           This method is extended and will extend the expiry time before
228           sending the response.
229
230       finalize_body
231           This method is extended and will call finalize_session before the
232           other finalize_body methods run.  Here we persist the session data
233           if a session exists.
234
235       initialize_session_data
236           This method will initialize the internal structure of the session,
237           and is called by the "session" method if appropriate.
238
239       create_session_id
240           Creates a new session ID using "generate_session_id" if there is no
241           session ID yet.
242
243       validate_session_id SID
244           Make sure a session ID is of the right format.
245
246           This currently ensures that the session ID string is any amount of
247           case insensitive hexadecimal characters.
248
249       generate_session_id
250           This method will return a string that can be used as a session ID.
251           It is supposed to be a reasonably random string with enough bits to
252           prevent collision. It basically takes "session_hash_seed" and
253           hashes it using SHA-1, MD5 or SHA-256, depending on the
254           availability of these modules.
255
256       session_hash_seed
257           This method is actually rather internal to generate_session_id, but
258           should be overridable in case you want to provide more random data.
259
260           Currently it returns a concatenated string which contains:
261
262           ·   A counter
263
264           ·   The current time
265
266           ·   One value from "rand".
267
268           ·   The stringified value of a newly allocated hash reference
269
270           ·   The stringified value of the Catalyst context object
271
272           in the hopes that those combined values are entropic enough for
273           most uses. If this is not the case you can replace
274           "session_hash_seed" with e.g.
275
276               sub session_hash_seed {
277                   open my $fh, "<", "/dev/random";
278                   read $fh, my $bytes, 20;
279                   close $fh;
280                   return $bytes;
281               }
282
283           Or even more directly, replace "generate_session_id":
284
285               sub generate_session_id {
286                   open my $fh, "<", "/dev/random";
287                   read $fh, my $bytes, 20;
288                   close $fh;
289                   return unpack("H*", $bytes);
290               }
291
292           Also have a look at Crypt::Random and the various openssl bindings
293           - these modules provide APIs for cryptographically secure random
294           data.
295
296       finalize_session
297           Clean up the session during "finalize".
298
299           This clears the various accessors after saving to the store.
300
301       dump_these
302           See "dump_these" in Catalyst - ammends the session data structure
303           to the list of dumped objects if session ID is defined.
304
305       calculate_extended_session_expires
306       calculate_initial_session_expires
307       create_session_id_if_needed
308       delete_session_id
309       extend_session_expires
310       extend_session_id
311       get_session_id
312       reset_session_expires
313       session_is_valid
314       set_session_id
315

USING SESSIONS DURING PREPARE

317       The earliest point in time at which you may use the session data is
318       after Catalyst::Plugin::Session's "prepare_action" has finished.
319
320       State plugins must set $c->session ID before "prepare_action", and
321       during "prepare_action" Catalyst::Plugin::Session will actually load
322       the data from the store.
323
324           sub prepare_action {
325               my $c = shift;
326
327               # don't touch $c->session yet!
328
329               $c->NEXT::prepare_action( @_ );
330
331               $c->session;  # this is OK
332               $c->sessionid; # this is also OK
333           }
334

CONFIGURATION

336           $c->config('Plugin::Session' => {
337               expires => 1234,
338           });
339
340       All configuation parameters are provided in a hash reference under the
341       "Plugin::Session" key in the configuration hash.
342
343       expires
344           The time-to-live of each session, expressed in seconds. Defaults to
345           7200 (two hours).
346
347       verify_address
348           When true, "<$c-"request->address>> will be checked at prepare
349           time. If it is not the same as the address that initiated the
350           session, the session is deleted.
351
352           Defaults to false.
353
354       verify_user_agent
355           When true, "<$c-"request->user_agent>> will be checked at prepare
356           time. If it is not the same as the user agent that initiated the
357           session, the session is deleted.
358
359           Defaults to false.
360
361       flash_to_stash
362           This option makes it easier to have actions behave the same whether
363           they were forwarded to or redirected to. On prepare time it copies
364           the contents of "flash" (if any) to the stash.
365

SPECIAL KEYS

367       The hash reference returned by "$c->session" contains several keys
368       which are automatically set:
369
370       __expires
371           This key no longer exists. Use "session_expires" instead.
372
373       __updated
374           The last time a session was saved to the store.
375
376       __created
377           The time when the session was first created.
378
379       __address
380           The value of "$c->request->address" at the time the session was
381           created.  This value is only populated if "verify_address" is true
382           in the configuration.
383
384       __user_agent
385           The value of "$c->request->user_agent" at the time the session was
386           created.  This value is only populated if "verify_user_agent" is
387           true in the configuration.
388

CAVEATS

390   Round the Robin Proxies
391       "verify_address" could make your site inaccessible to users who are
392       behind load balanced proxies. Some ISPs may give a different IP to each
393       request by the same client due to this type of proxying. If addresses
394       are verified these users' sessions cannot persist.
395
396       To let these users access your site you can either disable address
397       verification as a whole, or provide a checkbox in the login dialog that
398       tells the server that it's OK for the address of the client to change.
399       When the server sees that this box is checked it should delete the
400       "__address" special key from the session hash when the hash is first
401       created.
402
403   Race Conditions
404       In this day and age where cleaning detergents and Dutch football (not
405       the American kind) teams roam the plains in great numbers, requests may
406       happen simultaneously. This means that there is some risk of session
407       data being overwritten, like this:
408
409       1.  request a starts, request b starts, with the same session ID
410
411       2.  session data is loaded in request a
412
413       3.  session data is loaded in request b
414
415       4.  session data is changed in request a
416
417       5.  request a finishes, session data is updated and written to store
418
419       6.  request b finishes, session data is updated and written to store,
420           overwriting changes by request a
421
422       If this is a concern in your application, a soon-to-be-developed
423       locking solution is the only safe way to go. This will have a bigger
424       overhead.
425
426       For applications where any given user is only making one request at a
427       time this plugin should be safe enough.
428

AUTHORS

430       Andy Grundman
431
432       Christian Hansen
433
434       Yuval Kogman, "nothingmuch@woobling.org"
435
436       Sebastian Riedel
437
438       Tomas Doran (t0m) "bobtfish@bobtfish.net" (current maintainer)
439
440       Sergio Salvi
441
442       kmx "kmx@volny.cz"
443
444       Florian Ragwitz (rafl) "rafl@debian.org"
445
446       Kent Fredric (kentnl)
447
448       And countless other contributers from #catalyst. Thanks guys!
449
451           Copyright (c) 2005 the aforementioned authors. All rights
452           reserved. This program is free software; you can redistribute
453           it and/or modify it under the same terms as Perl itself.
454
455
456
457perl v5.12.0                      2009-11-04      Catalyst::Plugin::Session(3)
Impressum