File: sessions-cookie.cgi

package info (click to toggle)
libcgi-tiny-perl 1.003-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 516 kB
  • sloc: perl: 1,307; makefile: 2
file content (74 lines) | stat: -rwxr-xr-x 2,087 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use CGI::Tiny;
use Text::Xslate;
use Data::Section::Simple 'get_data_section';

sub verify_password { my ($user, $pass) = @_; ... }
sub store_new_session { my ($user) = @_; ... }
sub get_session_user { my ($session_id) = @_; ... }
sub invalidate_session { my ($session_id) = @_; ... }

cgi {
  my $cgi = $_;

  my $tx = Text::Xslate->new(path => [get_data_section]);

  my ($authed_user, $session_id);
  if ($cgi->path eq '/login') {
    if ($cgi->method eq 'GET' or $cgi->method eq 'HEAD') {
      $cgi->render(html => $tx->render('login.tx', {login_failed => 0}));
      exit;
    } elsif ($cgi->method eq 'POST') {
      my $user = $cgi->body_param('login_user');
      my $pass = $cgi->body_param('login_pass');
      if (verify_password($user, $pass)) {
        $session_id = store_new_session($user);
        $authed_user = $user;
      } else {
        $cgi->render(html => $tx->render('login.tx', {login_failed => 1}));
        exit;
      }
    }
  } elsif (defined($session_id = $cgi->cookie('myapp_session'))) {
    if ($cgi->path eq '/logout') {
      invalidate_session($session_id);
      # expire session cookie
      $cgi->add_response_cookie(myapp_session => $session_id, 'Max-Age' => 0, Path => '/', HttpOnly => 1);
      $cgi->render(redirect => $cgi->script_name . '/login');
      exit;
    } else {
      $authed_user = get_session_user($session_id);
    }
  }

  unless (defined $authed_user) {
    $cgi->render(redirect => $cgi->script_name . '/login');
    exit;
  }

  # set/refresh session cookie
  $cgi->add_response_cookie(myapp_session => $session_id, 'Max-Age' => 3600, Path => '/', HttpOnly => 1);

  $cgi->render(text => "Welcome, $authed_user!");
};

__DATA__
@@ login.tx
<html>
<head>
  <title>Login</title>
</head>
<body>
  <form method="post">
    <input type="text" name="login_user" placeholder="Username">
    <input type="password" name="login_pass" placeholder="Password">
    <button type="submit">Login</button>
  </form>
  : if $login_failed {
    <p>Login failed</p>
  : }
</body>
</html>