<?php

Doo::loadClass('auth');
Doo::loadClass('profile');
Doo::loadClass('utoken');
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 welcome()
    {
        $this->render('welcome', $this->data);
    }

    public function Signin()
    {
        $this->data['tips'] = '';
        if (isset($_GET['username'])) {
            $retval = $this->auth->checkLoginWithUserName($_GET['username']);
            if (isset($retval['uid'])) {
                $this->auth->setUid($retval['uid']);
                $this->auth->setUemail($retval['uemail']);
                $_SESSION['token'] = sha1($this->create_randomstr() . $_SESSION['uid']);
                $this->auth->updateToken($retval['uid'],$_SESSION['token'],1);
                setcookie('token', $_SESSION['token'], 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
                return Doo::conf()->APP_URL . 'project/index';
            } else {
                $this->data['tips'] = '<div class="alert alert-danger"><span data-icon="t" aria-hidden="true"></span> 帐号或密码错误，请检查输入是否有误。</div>';
            }
        } else {
            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']);
                        $this->auth->updateToken($retval['uid'],$_SESSION['token'],1);
                        setcookie('token', $_SESSION['token'], 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
                        return Doo::conf()->APP_URL . 'project/index';
                    } else {
                        $this->data['tips'] = '<div class="alert alert-danger"><span data-icon="t" aria-hidden="true"></span> 帐号或密码错误，请检查输入是否有误。</div>';
                    }
                } else {
                    return Doo::conf()->APP_URL;
                }
            }
        }

        $this->getsoftware();
        $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 getsoftware(){
        $StrJson = ($this->aconfig->getOne(array('select' => 'upgradeinfo', 'asArray' => TRUE))['upgradeinfo']);
        $upgradeinfo = json_decode($StrJson, true);
        if ($upgradeinfo) {
            $this->data['version'] = $upgradeinfo['version'];
            $this->data['download'] = $upgradeinfo['download'];
        }
    }

    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');
    }

}

?>