<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
// session_write_close();
include_once 'Parameters.php';
include_once 'auth/func.php';
header('Access-Control-Allow-Origin: *');

if (isset($_POST['user']) && isset($_POST['pwd'])) {
	$user_id  = $_POST['user'];
	$password = $_POST['pwd'];
} else {
	Unauthorized();
	exit;
}

try {
	$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource, $DataBase_Alarm);
	$pdo_mssql = new PDO($dsn, $UserID, $Password);

	$sql = "SELECT * FROM dbo.users WHERE user_id = :uid AND enabled = 1 AND password = :pwd";
	$st = $pdo_mssql->prepare($sql);
	$st->execute(array("uid" => $user_id, "pwd" => $password));
	$row = $st->fetch();

	$user    = $row['user_id'];
	$user_name = $row['user_name'];
	$pass    = $row['password'];
	$priv_no = $row['priv_no'];

	//登入授權成功
	if ($user_id == $user) {
		$user_id = $row['user_id'];
	} else {
		Unauthorized();
		exit;
	}
} catch (Exception $e) {
	header("HTTP/1.0 500 Internal Server Error");
	exit;
}
// 登入成功 刷新 session_id for 資安檢測 Session Fixation 攻擊 (高風險)
session_regenerate_id();
// 抓取登入者角色清單
$sql = "SELECT * FROM dbo.v_roles_users WHERE user_id = :uid";
$st = $pdo_mssql->prepare($sql);
$st->execute(array("uid" => $user_id));
$list = $st->fetchAll(PDO::FETCH_ASSOC);
$roles = array();
foreach ($list as $row) {
	array_push($roles, $row["role_id"]);
}
// 抓取登入者menu清單
$sql = "SELECT * FROM dbo.v_roles_users_menus WHERE user_id = :uid";
$st = $pdo_mssql->prepare($sql);
$st->execute(array("uid" => $user_id));
$list = $st->fetchAll(PDO::FETCH_ASSOC);
$menus = array();
foreach ($list as $row) {
	array_push($menus, $row["menu_id"]);
}
$token = createToken($priv_no, $user_id, $user_name, $roles, $menus, _Login_Auto_Logout_Interval, _Login_Key);
$rtn = array("token" => strval($token), "roles" => $roles, "menus" => $menus);
// 回傳 login.js 的值 {"token":"xxx",}
echo json_encode($rtn);

$dt  = date('Y-m-d H:i:s');
$h   = hash("crc32", $token, false);
/*
$sql = sprintf("INSERT INTO %s.dbo.user_login (login_time, user_id, curr_check, ipaddr, token_hash)
				VALUES ('{$dt}', '{$user}', '{$dt}', '{$_SERVER['REMOTE_ADDR']}', '{$h}')", $DataBase_Alarm);
*/
$sql = sprintf("INSERT INTO %s.dbo.user_login (login_time, user_id, curr_check, ipaddr, token_hash)
				VALUES (:datetime, :uid, :datetime, ':addr, :token)", $DataBase_Alarm);
$pdo_mssql->prepare($sql)->execute(array(
	"datetime" => $dt,
	"uid"      => $user,
	"addr"     => $_SERVER['REMOTE_ADDR'],
	"token"    => $h
));
exit;
