3

I'm using Dancer2 and the YAML session engine for my web app. My config.yml contains

engines:
  session:
    YAML:
      ...
      cookie_duration: 5 minutes
      ...

I'd like to display something like "Your session expires in X minutes".

How can I access this value, i.e. how can I access the $session object in my routes?

With the DSL keyword session I can only set and get arbitrary values, like session username => 'Bob'; and $username = session('username'); etc.

Note that I'm not interested in getting the configuration value (settings('engines')->{session}{YAML}{cookie_duration}) because that's a string I'd had to parse and it depends on YAML being my session engine. I'd like to access $session->session_duration.

PerlDuck
  • 5,610
  • 3
  • 20
  • 39
  • 1
    In theory you should do `session->expires`, as `session` just returns the session object when it's used like that. However, in my test that returned `undef`. But I didn't have a full config and it's possible I did something wrong. If you do `p session` via `Data::Printer` you'll see that the Dancer2::Core::Session object that `session` returns has a method `expires`. The `cookie_duration` is not the expiry of the session on the server. See https://metacpan.org/pod/Dancer2::Core::Session#expires – simbabque Jul 03 '17 at 15:32
  • 1
    Hey, cool! That's exactly the solution. In my configuration `session->expires` returns 1514648770 (which is `now + 6 months`, the value I currently have configured as `cookie_duration`). Perfect. My problem was that I couldn't figure out how to access that value and/or convert `session()` to a `$session`. If you write a (short) answer, I'll overwhelm it with upvotes. ;-) – PerlDuck Jul 03 '17 at 15:52

1 Answers1

1

You will get the session object back when you call session without any arguments. Feel free to assign it to a $session variable if that makes it easier to read. To get the expiration time, use the expires method.

my $session = session;
warn $session->expires;

Or simpler:

warn session->expires;
simbabque
  • 53,749
  • 8
  • 73
  • 136