Skip to content

Instantly share code, notes, and snippets.

@biscuitrainbow
Created July 31, 2021 04:36
Show Gist options
  • Save biscuitrainbow/6e722f5c24879d554d2a7b334969d8fa to your computer and use it in GitHub Desktop.
Save biscuitrainbow/6e722f5c24879d554d2a7b334969d8fa to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
class CmuAccountController extends ApiController
{
public function checkRegistered(Request $request)
{
$client = new Client();
$redirectUri = $request->callbackUri;
$clientId = "";
$clientSecret = "";
$grantType = "authorization_code";
$tokenResponse = $client->post('https://oauth.cmu.ac.th/v1/GetToken.aspx', [
'form_params' => [
'code' => $request->code,
'redirect_uri' => $redirectUri,
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => $grantType,
]
]);
$tokenData = json_decode($tokenResponse->getBody()->getContents(), true);
$accessToken = $tokenData['access_token'];
$profileResponse = $client->get('https://misapi.cmu.ac.th/mishr/v1/api/employee/self/basicinfo', [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
],
]);
$profileData = json_decode($profileResponse->getBody()->getContents(), true);
$email = $profileData['Email'];
$user = User::where('email', $email)->first();
if (!$user) {
return $this->respond([
'next' => 'register',
'email' => $profileData['Email'],
'firstname' => $profileData['NameTha'],
'lastname' => $profileData['SurNameTha'],
'organizationName' => $profileData['OrganizationName1'],
]);
}
$token = $user->createToken('cmu-hms');
return $this->respond(['next' => 'login', 'token' => $token->plainTextToken]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment