<?php

Doo::loadClass('auth');
Doo::loadClass('profile');
Doo::loadModelAt('aconfig', 'admin');

/**
 * MainController
 * Feel free to delete the methods and replace them with your own code.
 *
 * @author NoNZero
 */
class LoginController extends DooController {

    private $data, $auth, $profile,$aconfig;

    public function beforeRun($resource, $action) {
        $uGroups = $this->profile->getUidByname($this->auth->getUid());
        if (!isset($uGroups['groups']))
            $uGroups['groups'] = 'anonymous';
        $falg = Doo::acl()->isAllowed($uGroups['groups'], $resource, $action);
        if (!$falg)
            return Doo::acl()->defaultFailedRoute;
    }

    public function __construct() {
        $this->auth = new Auth();
        $this->profile = new Uprofile();
        $this->aconfig = new AConfig();
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

//    public function Signup() {
//	$this->render('login', $this->data);
//    }
//    public function beforeRun($resource, $action) {
//	$uname = $this->auth->getUname();
//	if ($uname) {
//	    $uGroups = $this->users->getUidByname($this->auth->getUname());
//	} else {
//	    $uGroups['groups'] = 'anonymous';
//	}
//	$falg = Doo::acl()->isAllowed($uGroups['groups'], $resource, $action);
//	if (!$falg)
//	    return Doo::conf()->APP_URL;
//    }

    public function welcome() {
        $this->render('welcome', $this->data);
    }

    public function Signin() {
        $this->data['tips'] = '';
        // 密码采用PHPASS
        // 防止跨站采用user_agent随机串
        // 重复提交CRSF_FORM
        // 自动登录 可采用登录后生成一个可验证字符串，要求输入密码可通过网上登录查看（从客户端点击）加验证码
//	if ($this->auth->isLoggedIn())
//	    return Doo::conf()->APP_URL . 'project/welcome';
        if (isset($_POST['uemail']) && isset($_POST['upasswd'])) {
            if ($this->isValidFormHash($_POST['tokenform'])) {
                $retval = $this->auth->checkLogin($_POST['uemail'], $_POST['upasswd']);
                if (isset($retval['uid'])) {
                    $this->auth->setUid($retval['uid']);
                    $this->auth->setUemail($retval['uemail']);
                    $_SESSION['token'] = sha1($this->create_randomstr() . $_SESSION['uid']);
                    setcookie('token', $_SESSION['token'], 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
//		    $profileArray = $this->profile->getProWithUid($this->auth->getUid());
//		    if (isset($profileArray['userid'])) {
                    return Doo::conf()->APP_URL . 'project/index';
//		    } else {
//			return Doo::conf()->APP_URL . 'project/welcome';
//		    }
//		    die();
                } else {
                    $this->data['tips'] = '<div class="alert alert-error">
			    <span data-icon="t" aria-hidden="true"></span> 帐号不存在或者密码错误
			</div>';
//		    die();
                }
            } else {
                return Doo::conf()->APP_URL;
            }
        }
        $this->data['_token_'] = $this->generateFormHash($this->create_randomstr());
        $this->data['proName'] = $this->aconfig->getOne(array('select' => 'proName', 'asArray' => TRUE))['proName'];
        $this->data['ver'] = DOO::conf()->ver;
        $this->render('login', $this->data);
    }

    function Signout() {
        $this->auth->logout();
        return Doo::conf()->APP_URL;
    }

    function IsSessionHijacking() {
        $string = $_SERVER['HTTP_USER_AGENT'];
        if (!isset($_SESSION['randstr']))
            $_SESSION['randstr'] = $this->create_randomstr();
        $string .= $_SESSION['randstr'];
        $token = md5($string);
        $_SESSION['token'] = $token;
        if ($_SESSION['token'] == md5($_SERVER['HTTP_USER_AGENT'] . $_SESSION['randstr'])) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function isLoggedIn() {
        if (isset($_SESSION['token']) && isset($_COOKIE['token'])) {
            if ($_SESSION['token'] != $_COOKIE['token']) {
                $this->Signout();
                setcookie('token', '-1', 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
            }
            return isset($_SESSION['uid']);
        }
    }

    function generateFormHash($salt) {
        $hash = sha1(mt_rand(1, 1000000) . $salt);
        $_SESSION['csrf_hash'] = $hash;
        return $hash;
    }

    function isValidFormHash($hash) {
        return $_SESSION['csrf_hash'] === $hash;
    }

    /**
     * 随机字符串函数
     * @param $password 密码
     * @param $random 随机数
     */
    function random($length, $chars = '0123456789') {
        $hash = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

    /**
     * 生成随机字符串
     * @param string $lenth 长度
     * @return string 字符串
     */
    function create_randomstr($lenth = 6) {
        return $this->random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    }

}

?>