TripletaiL Japanese Web Application Framework

セッションの利用(1) - チュートリアル

Dセッションを使って認証をしてみましょう。

以下を前提条件とします。

main.cgi

#!/usr/local/bin/perl

use strict;
use warnings;
use Tripletail qw(tl.ini);

$TL->startCgi(
    -Session => 'Session',
    -DB => 'DB',
    -main => \&main,
);

sub main
{
    $TL->dispatch($CGI->get('Command'), default => 'Top');
}

sub DoTop
{
    &DispTop;
}

sub DoLogin
{
    &CheckLogin;

    if (defined($TL->getSession->getValue)) {
        $TL->location($TL->newForm->set(Command => 'LoginAfter')->toLink);
    } else {
        &DispTop;
    }
}

sub DoLoginAfter
{
    &DispLoginAfter;
}

sub DispLoginAfter
{
    my $t = $TL->newTemplate('login_after.html');
    my $userid = $TL->getSession->getValue;
    my $DB = $TL->getDB('DB');
    my $hash = $DB->selectAllHash(q{
        SELECT
            id
        FROM
            TripletaiL_DB_UserData
        WHERE
            userid = ?
        },
        $userid
    );
    if (defined(@$hash[0])) {
        $t->expand(
            ID => @$hash[0]->{id},
        );
        $t->flush;
    } else {
        $TL->location($TL->newForm->set(Command => 'Top')->toLink);
    }
}

sub CheckLogin
{
    if (defined($CGI->get('id')) && defined($CGI->get('pass'))) {
        my $DB = $TL->getDB('DB');
        my $hash = $DB->selectAllHash(q{
            SELECT
                userid
            FROM
                TripletaiL_DB_UserData
            WHERE
                id = ?
            AND
                pass = ?
            LIMIT 1
        }, $CGI->get('id'), $CGI->get('pass'));
        if (defined(@$hash[0])) {
            $TL->getSession->setValue(@$hash[0]->{userid});
        }
    }
}

sub DispTop
{
    #ログアウトしておく
    $TL->getSession->discard;
    my $t = $TL->newTemplate('login.html');
    $t->addHiddenForm($TL->newForm->set(Command => 'Login'));
    $t->flush;
}

tl.ini

[TL]

[DB]
type = mysql
defaultset = SET_Default
SET_Default = CON_DBRW

[CON_DBRW]
host = localhost
user = user
dbname = test
password = pass

[Session]
mode = http
dbgroup = DB
dbset = SET_Default
sessiontable = TripletaiL_Session

login.html

<!DOCTYPE html>
<HTML>
  <BODY>
    <form method="post">
      ID:guest , PASS:guest
      <br>
      ID:<input type="text" name="id">
      <br>
      PASS:<input type="text" name="pass">
      <br>
      <input type="submit" name="submit" value="ログイン">
    </form>
  </BODY>
</HTML>

login_after.html

<!DOCTYPE html>
<HTML>
  <BODY>
    ログインしたID
    <br>
    <&ID>
  </BODY>
</HTML>

一覧へ戻る 次のチュートリアルへ