<?php

class Login extends Vn\Web\JsonRequest
{
	function run ($db)
	{
		try {
			$this->updateCredentials ($db);
			//$this->updateCredentialsLdap ($db);
		}
		catch (Exception $e)
		{
			error_log ($e->getMessage ());
		}

		$token = $this->service->createToken (
			$_SESSION['user'],
			!empty ($_POST['remember'])
		);

		return [
			'login' => TRUE,
			'token' => $token
		];
	}
	
	/**
	 * Updates the user credentials in other user databases like Samba
	 * LDAP .
	 **/
	function updateCredentialsLdap ($db)
	{
		$host = $ldapConf['host'];
	
		if ($ldapConf->secure)
			$ldapHost = "ldaps://$host";
		else
			$ldapHost = "ldap://$host";
	
		$ldap = ldap_connect ($ldapHost, $ldapConf['port']);
		
		if (!ldap_bind ($ldap, $ldapConf['user'], $ldapConf['password']))
			throw new Exception ('LDAP authentication failed');
		
		error_log ('Connected to LDAP!');
	}
	
	/**
	 * Updates the user credentials in other user databases like Samba.
	 **/
	function updateCredentials ($db)
	{
		if (empty ($_POST['password']))
			return;
	
		$hasAccount = $db->getValue (
			'SELECT COUNT(*) > 0
				FROM account.user u
					JOIN account.account a ON u.id = a.id
				WHERE u.name = #',
			[$_SESSION['user']]
		);
		
		if (!$hasAccount)
			return;

		$sshConf = $db->getRow ('SELECT host, user, password FROM ssh_config');
	
		$ssh = ssh2_connect ($sshConf['host']);

		if (!$ssh)
			throw new Exception ("Can't connect to SSH server {$sshConf['host']}");
		
		$sshAuth = ssh2_auth_password ($ssh,
			$sshConf['user'], base64_decode ($sshConf['password']));

		if (!$sshAuth)
			throw new Exception ("SSH authentication failed");
		
		$user = $this->escape ($_SESSION['user']);
		$pass = $this->escape ($_POST['password']);
		$stream = ssh2_exec ($ssh, "samba-tool user create \"$user\" \"$pass\"");
	}
	
	/**
	 * Escapes the double quotes from an string.
	 **/
	function escape ($str)
	{
		return str_replace ('"', '\\"', $str);
	}
}

?>
