Search code examples
perlsessiondancer

How to access Dancer2's session object?


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.


Solution

  • 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;