12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- session_start();
- //demo https://aroz.alanyeung.co/oauth.php
- //please go to https://github.com/settings/applications/ to get the client_id and client_secret, pleae remind that the redirect_uri must be same as github.com
- $baselink = "https://github.com/login/oauth"; //do not change it
- // CHNAGE HERE
- $client_id = "8757b82f0e4c52d34ec8"; //Client ID
- $client_secret = "96cfe75be2a9ffb6b8fca3811d76ebef63a17bbd"; //Client Secret
- $redirect_uri = "https://aroz.alanyeung.co/AOB/oauthgithub.php"; //Authorization callback URL
- // CHANGE HERE
- if(isset($_GET["code"])){
- //we use the one time code ($_GET["code"]) to get the access_token
- $fields = array(
- 'grant_type' => 'authorization_code',
- 'client_id' => $client_id,
- 'client_secret' => $client_secret,
- 'redirect_uri' => $redirect_uri,
- 'code' => $_GET["code"],
- );
- $postvars = http_build_query($fields);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $baselink."/access_token");
- curl_setopt($ch, CURLOPT_POST, count($fields));
- curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array(
- 'Accept: application/json'
- ));
- $result = curl_exec($ch);
- curl_close($ch);
- $data = json_decode($result,true);
- //$data had access_token,token_type,scope inside, but only access_token needed.
- //print_r($data);
-
- //obtain the userinfo here due to github had their own OAuth implementions
- $chs = curl_init();
- curl_setopt($chs, CURLOPT_URL, "https://api.github.com/user");
- curl_setopt($chs,CURLOPT_RETURNTRANSFER, true);
- curl_setopt($chs, CURLOPT_HTTPHEADER, array(
- "Authorization: token ".$data["access_token"],
- "User-Agent: Test"
- ));
- $result = curl_exec($chs);
- curl_close($chs);
- $userinfo = [];
- $userinfo = json_decode($result,true);
- if($userinfo == []){
- echo "Error!";
- }else{
- $_SESSION["method"] = "Github";
- $_SESSION["login"] = $userinfo["login"];
- setcookie("username",$userinfo["login"],time()+ 172800 );
- setcookie("password","OAuthGithub",time()+ 172800 );
- echo '<script>localStorage.ArOZusername = "'.$userinfo["login"].'";window.location = "./index.php"</script>';
- }
- }
|