#!/usr/bin/env perl
# ログインページ
#
# http://gms.gdl.jp/~miki/cgi-bin/members/login.pl
#

use strict;
use SimpleAuth;
use Pg;
use CGI;

# DB設定
my $dbname = 'miki';
my $dbuser = 'miki';
my $password = 'pw1gk8103h';
my $host = 'localhost';
my $conn = Pg::connectdb("dbname=$dbname user=$dbuser password=$password host=$host");

# 認証設定
my $user_management_table = 'iuser';
my $user_name_field = 'uname';
my $user_password_field = 'pass';
my $auth = SimpleAuth->new($conn, $user_management_table, $user_name_field, $user_password_field);

# CGI設定
my $query = new CGI;
my $user_name = '';
my $user_password = '';

my $session_id = '';
if ($ENV{'HTTP_COOKIE'}) {
	$session_id = $auth->get_cookie_value('sid');
}
# ログインページのみ
elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
	$user_name = $query->param('user_name');
	$user_password = $query->param('user_password');
	$session_id = $auth->authorize_user($user_name, $user_password);
}

######### ここまでが共通の設定部分 ##########

# ログインページでは
# $session_idが存在すればホームページへリダイレクトする
if ($session_id) {
	my $redirect_url = 'http://gms.gdl.jp/~miki/cgi-bin/members/home.pl';
	print "Set-Cookie: sid=" . $session_id . "; ".
		  "domain=gms.gdl.jp; ".
		  "path=/~miki/cgi-bin/members/;\n";
	print "Location: " . $redirect_url . "\n\n";
}
else {
	print "Set-Cookie: sid=0; ".
		  "expires=Fri, 31-Dec-1999 23:00:00 GMT" . "\n";
	print "Content-Type: text/html; charset=EUC-JP"."\n\n";
	print "<html>\n".
		  "<head>\n".
		  "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-JP\" />\n".
		  "<title>ログイン</title>\n".
		  "</head>\n".
		  "<body>\n".
		  "<form action=\"./login.pl\" method=\"POST\">\n".
		  "ユーザー名：<input type=\"text\" name=\"user_name\" /><br />\n".
		  "パスワード：<input type=\"password\" name=\"user_password\" />\n".
		  "<input type=\"submit\" value=\"ログイン\" />\n".
		  "</form>\n".
		  "$user_name".
		  "</body>\n".
		  "</html>\n";
}

exit(0);