<?php
/*
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Component
 * @package  TRPG Data Bank
 * @version  beta
 * @author   Cake <cake_67@users.sourceforge.jp>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://trpgtools-onweb.sourceforge.jp/
 */

/*
 * 認証コンポーネント拡張
 */

/**
 * The parent component
 */
App::import('Component', 'Auth');

class AuthPlusComponent extends AuthComponent {

/**
 * The name of the model that represents users which will be authenticated.  Defaults to 'User'.
 *
 * @var string
 * @access public
 */
	var $userModel = 'User';

	function initialize(&$controller)
	{
		parent::initialize($controller);

		// ログイン後リダイレクト設定
		if (isset($controller->params["url"]["url"])) {
			$this->loginRedirect = $controller->params["url"]["url"];
		} else {
			$this->loginRedirect = Configure::read('Routing.basePath');
		}

		if ("/".$this->loginRedirect == Router::normalize(Configure::read('Routing.loginPath'))) {
			$this->loginRedirect = Router::normalize(Configure::read('Routing.basePath'));
		}
	}

	function deleteAuth()
	{
		$this->__setDefaults();
		$this->Session->delete($this->sessionKey);

		$this->_loggedIn = false;
		return Router::normalize($this->logoutRedirect);
	}

	function isAuthorized($type = null, $object = null, $user = null) {
		if ($type == 'orig') {
			$user = $this->user();

			// 未ログイン
			if (empty($user)) {
				$valid = false;
			// 管理者
			} elseif (in_array($this->user('group_id'), array(
				Configure::read('Group.admin'), 
				Configure::read('Group.subadmin'), 
				Configure::read('Group.watcher'))
			)) {
				$valid = true;
			// 一般ユーザ
			} elseif ($this->user('group_id') == Configure::read('Group.member')) {
				if (isset($this->params['prefix']) 
					&& $this->params['prefix'] == Configure::read('Routing.base_prefixes')) {
					$valid = false;
				} else {
					$valid = true;

				}
			} else {
				$valid = false;
			}
		
		} else {
			$valid = parent::isAuthorized($type, $object, $user);
		}

		return $valid;
	}

	function login($data = null) {
		parent::login($data);

		if ($this->_loggedIn) {

			$user = $this->user(); 

			// 二重ログイン対策
			if (Configure::read('Session.destroyOldAuth')) {
				$before_sid = $user['User']['sid'];
				$new_sid = $this->Session->id();

				if (!empty($before_sid) && $before_sid != $new_sid) {
					// 新セッションclose
					session_write_close();

					// 前セッション破棄
					$this->Session->__initSession();
					session_id($before_sid);
					session_start();
					session_destroy();

					if (Configure::read('Session.save') == 'database') {
						// session Lib.の__destroy()処理
						$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
						$table = $db->fullTableName(Configure::read('Session.table'));
						$db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $before_sid);
					} else {
						$file = TMP . DS . 'sessions' . DS . "sess_$before_sid";
						@unlink($file);
					}

					// 新セッション再Open
					$this->Session->__initSession();
					session_id($new_sid);
					session_start();
				}
			}

			// ログイン時間更新
			$model =& $this->getModel();
			$model->id = $user['User']['id'];
			$model->save(array(
				'useragent' => $_SERVER["HTTP_USER_AGENT"],
				'host' => gethostbyaddr($_SERVER["REMOTE_ADDR"]),
				'sid' => $this->Session->id(),
				)
			);
		}

		return $this->_loggedIn;
	}

	function logout() {
		$this->Session->destroy();

		return parent::logout();
	}

}


