Select Git revision
AuthSCHClient.class.php
Forked from an inaccessible project.
AuthSCHClient.class.php 3.54 KiB
<?php
class AuthSCHClient {
private static $host = "https://auth.sch.bme.hu/";
private static $username = ""; // your application's id
private static $password = ""; // your application's password
private static $scope = ""; // wanted data, separated with plus sign. For more information see your website profile on auth.sch.bme.hu.
private $tokens;
public function __construct($tokens = null) {
$this->tokens = new stdClass();
if($tokens === null) {
if(session_id() == '') {
// session isn't started
session_set_cookie_params(3600,"/");
session_start();
}
if(!isset($_SESSION['tokens'])) {
// auth token not exists
// get tokens from auth.sch.bme.hu
$this->authenticate();
//save tokendata to session (if we did authentication -> we have refresh token)
if(isset($this->tokens->refresh_token))
$_SESSION['tokens'] = serialize($this->tokens);
} else {
// load tokendata from session
$this->tokens = unserialize($_SESSION['tokens']);
}
} else {
$this->tokens = $tokens;
}
return $this->tokens;
}
public function __destruct() {
}
private function curlExec($urlPart, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::$host . $urlPart);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($urlPart != "oauth2/resource")
curl_setopt($ch, CURLOPT_USERPWD, self::$username . ":" . self::$password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
private function authenticate() {
// before authentication & authorization
if (!isset($_GET['code'])) {
// get token
$data = array(
'grant_type' => 'client_credentials',
);
$ch = $this->curlExec("oauth2/token", $data);
$data = array(
'access_token' => json_decode($ch)->access_token,
);
$ch = $this->curlExec("oauth2/resource", $data);
$res = json_decode($ch);
// check api access & redirect to auth.sch.bme.hu for authorization
if ($res != null && isset($res->success) && $res->success == true)
header("Location: " . self::$host . "site/login?response_type=code&client_id=". self::$username ."&state=" . sha1($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']) . "&scope=" . self::$scope);
else
throw new Exception("error during api check");
} else {
$data = array(
'grant_type'=>'authorization_code',
'code'=>$_GET['code'],
);
$ch = $this->curlExec("oauth2/token", $data);
$tokens = json_decode($ch);
if($tokens === null || !isset($tokens->access_token) || empty($tokens->access_token))
throw new Exception ("invalid token data");
$this->tokens = $tokens;
$this->tokens->lastUpdate = time();
}
}
}