<?php

session_start(); // starts new or resumes existing session
session_regenerate_id(true); // regenerates SESSIONID to prevent hijacking

Doo::loadModelAt('auser', 'admin');
Doo::loadClass('PasswordHash');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class LoginController extends DooController {

    private $data, $auser, $__ph;

    public function __construct() {
        $this->auser = new AUser();
        $this->__ph = new PasswordHash(8, FALSE);
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

//    function signUp() {
//	$this->render('admin-login', $this->data, TRUE);
//    }

    function signIn() {
        $this->data['tips'] = '';
        // 密码采用PHPASS
        // 防止跨站采用user_agent随机串
        // 重复提交CRSF_FORM
        // 自动登录 可采用登录后生成一个可验证字符串，要求输入密码可通过网上登录查看（从客户端点击）加验证码
//	if ($this->auth->isLoggedIn())
//	    return Doo::conf()->APP_URL . 'project/welcome';
        if (isset($_POST['muser']) && isset($_POST['mpasswd'])) {
            if ($this->isValidFormHash($_POST['tokenform'])) {
                $retval = $this->checkLogin($_POST['muser'], $_POST['mpasswd']);
                if (isset($retval['auid'])) {
                    $_SESSION['auid'] = $retval['auid'];
                    $_SESSION['aname'] = $retval['auname'];
                    $_SESSION['token'] = sha1($this->randomPassword() . $_SESSION['auid']);
                    setcookie('token', $_SESSION['token'], 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
                    return Doo::conf()->APP_URL . 'manage/user/list';
                } else {
                    $this->data['tips'] = '<div class="alert alert-danger">
			    <span data-icon="t" aria-hidden="true"></span> 帐号不存在或者密码错误。
			</div>';
//		    die();
                }
            } else {
                return Doo::conf()->APP_URL . 'manage';
            }
        }
        $this->data['_token_'] = $this->generateFormHash($this->randomPassword());
        $this->render('admin-login', $this->data, TRUE);
    }

    function signOut() {
        session_destroy();
        setcookie('token', '-1', 0, '/', Doo::conf()->APP_URL, FALSE, TRUE);
        return Doo::conf()->APP_URL . 'manage';
    }

    function checkLogin($name, $passwd) {
        $auserArray = $this->auser->getOne(array('where' => 'auname=?', 'param' => array($name), 'asArray' => TRUE));
        if (isset($auserArray) && $auserArray && $this->__ph->CheckPassword($passwd, $auserArray['aupass'])) {
            return $auserArray;
        } else {
            return FALSE;
        }
    }

    public function randomPassword() {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }

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

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

}
