# -*- cperl -*-
# -----------------------------------------------------------------------------
# $Id: UserInfo.pm,v 1.2 2004/09/30 17:11:03 admin Exp $
# -----------------------------------------------------------------------------
package Celaenito::Httpd::UserInfo;
use strict;
use warnings;
use HTTP::Status;
use Template;
use Celaenito::Config;
use Celaenito::Template;
use Celaenito::StaticFile;
use Celaenito::Permission;
use Celaenito::Httpd;
use Celaenito::DB;
use URI::QueryParam;
use constant COOKIE_EXPIRATION => '+1y';

sub handler {
    my ($req, $resp) = @_;

    my $mode = $req->uri->query_param('mode');

    if ($req->uri->path eq '/-/login') {
	return login_handler(@_);
    }
    elsif ($req->uri->path eq '/-/logout') {
	return logout_handler(@_);
    }
    elsif ($req->uri->path eq '/-/userconf') {
	if ($mode and $mode eq 'action') {
	    return userconf_action_handler(@_);
	}
	else {
	    return userconf_handler(@_);
	}
    }
    else {
	return notfound_handler(@_);
    }
}

sub login_handler {
    my ($req, $resp) = @_;
    my $uid = $req->uri->query_param('uid');
    my $passwd = $req->uri->query_param('passwd');
    my $nosave = $req->uri->query_param('nosave');

    if (SET_LOGIN(
	$resp, $uid, $passwd,
	$nosave ? undef : COOKIE_EXPIRATION)) {
	# ログイン成功。
	return redirect_handler($req, $resp, '/');
    }
    else {
	# 失敗
	return redirect_handler($req, $resp, '/', {login_failure => 1});
    }
}

sub logout_handler {
    my ($req, $resp) = @_;

    UNSET_LOGIN($resp);

    return redirect_handler($req, $resp, '/');
}

sub userconf_handler {
    my ($req, $resp) = @_;

    LOGGED_IN_P($req)
      or need_auth_handler(@_);

    my $t = {};
    $t->{title} = config('ui.title');
    $t->{uid}   = LOGIN_UID($req);
    $t->{name}  = LOGIN_USERNAME($req);

    my $out;
    TMPL->process('userconf.tt', $t, \$out)
      or die Template->error;
    
    $resp->content($out);
    return RC_OK;
}

1;
