<?php
require_once 'vendor/autoload.php';
session_start();
$mode = $_POST['mode'];
openlog('ACCRED', LOG_PID, LOG_LOCAL0);
if($mode=='logout') {
$mysqli = new mysqli("localhost", "caribanaaccred", "welcome99", "caribanaaccred");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = "INSERT INTO log (uid,name,isadmin,operation) values('".$_SESSION['uid']."','".$_SESSION['name']."',". $_SESSION['admin'].", 'logout')";
$mysqli->query($query);
syslog(LOG_INFO, "Logout ".$_SESSION['uid']." / ". $_SESSION['name']. " from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
$_SESSION['uid']='';
$_SESSION['admin']='';
$_SESSION['name']='';
$_SESSION['allowedit'] = '';

closelog();
die();

}
$id_token = $_POST['idtoken'];

$admins = array('106388451999977183087' => 'Y', // Jess  
		'113391142723644034553' => 'Y' // Lars

);
$client = new Google_Client(['client_id' => '538635499162-g21v86gk87qm863u03er6vnm3q15bl82.apps.googleusercontent.com']);
$payload = $client->verifyIdToken($id_token);
if ($payload) {
  $userid = $payload['sub'];
  // If request specified a G Suite domain:
  $domain = $payload['hd'];

  if($domain=='caribana.ch') {
    // Associate user info to session si we can use it later
    $_SESSION['uid'] = $userid;
    $_SESSION['dom'] = $domain;
    $_SESSION['email'] = $payload['email'];
    $_SESSION['name'] = $payload['name'];
    // Is this user admin 
    $_SESSION['admin'] = '';
    // Set to 1 to allow noramle users to add new entries en edit existing
    $_SESSION['allowedit'] = 1;
    if( array_key_exists($userid, $admins)) {
  	$_SESSION['admin'] = 1;
    }
    echo "SUCCESS: $userid  / DOMAIN: $domain";
    syslog(LOG_INFO, "Authorized login $userid / ". $payload['name']. ",domain: $domain from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
  }
  else {
    syslog(LOG_ERR, "Failed login ". $payload['name']. " from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']}), incorrect domain: $domain");
    echo "FAIL";
  }
} else {
  // Invalid ID token
    syslog(LOG_ERR, "Failed login ". $payload['name']. " from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
    closelog();
  echo "FAIL";
}
closelog();

?>
