Skip to content

Commit

Permalink
Have AmoAPI work
Browse files Browse the repository at this point in the history
  • Loading branch information
luttje committed Jun 10, 2021
1 parent 19bef04 commit c59933a
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 38 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,13 @@ Don't use this in combination with Amoclient.


## AmoAPI

Apart from being the central login-server, _login.amo.rocks_ also exposes an api. Please note this api is currently undocumented, although there are options to explore the api:
* Refer to _amologin_'s [routes/api.php](https://github.com/StudioKaa/amologin/blob/master/routes/api.php) file.
* Play around at [apitest.amo.rocks](https://apitest.amo.rocks/).

### Amoclient API Interface

An example of calling the api through Amoclient;
```
namespace App\Http\Controllers;
Expand All @@ -86,6 +89,8 @@ class MyController extends Controller
```

**Known 'bug':** Currently the AmoAPI class doesn't check if the token expired but just refreshes it anytime you use it.

### `AmoAPI::get($endpoint)`
* Performs an HTTP-request like `GET https://api.amo.rocks/$endpoint`.
* This method relies on a user being authenticated through the amoclient first. Please do call this method only from routes and/or controllers protected by the _auth_ middlware.
Expand Down
20 changes: 12 additions & 8 deletions src/AmoAPI.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php

namespace StudioKaa\Amoclient;
use Lcobucci\JWT\Parser;

use Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
Expand All @@ -26,6 +26,7 @@ public function get($endpoint)
private function call($endpoint = 'user', $method = 'GET')
{
$access_token = session('access_token');

if($access_token == null)
{
abort(401, 'No access token: probably not logged-in');
Expand All @@ -35,15 +36,16 @@ private function call($endpoint = 'user', $method = 'GET')

$this->log('START using access_token');

if($access_token->isExpired())
// TODO: Don't needlesly refresh the token
//if($access_token->isExpired())
{
$this->log('access_token expired, trying to refresh');
$access_token = $this->refresh(session('refresh_token'));
}
else
{
$this->log('Succesfully using current access_token');
}
// else
// {
// $this->log('Succesfully using current access_token');
// }

$response = $this->client->request($method, 'https://api.curio.codes' . $endpoint, [
'headers' => [
Expand All @@ -59,6 +61,8 @@ private function call($endpoint = 'user', $method = 'GET')

private function refresh($refresh_token)
{
$config = AmoclientHelper::getTokenConfig();

try
{
$response = $this->client->post('https://login.curio.codes/oauth/token', [
Expand All @@ -73,8 +77,8 @@ private function refresh($refresh_token)
$this->log('new access_token acquired');

$tokens = json_decode( (string) $response->getBody() );
$access_token = (new Parser())->parse((string) $tokens->access_token);
session()->put('access_token', $access_token);
$access_token = $config->parser()->parse((string) $tokens->access_token)->toString();
session()->put('access_token', $tokens->access_token);
session()->put('refresh_token', $tokens->refresh_token);

return $access_token;
Expand Down
35 changes: 5 additions & 30 deletions src/AmoclientController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,12 @@
use App\Models\User;
use App\Http\Controllers\Controller;

use DateTimeZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Validation\Constraint\ValidAt;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;

class AmoclientController extends Controller
{
private Configuration $config;

public function __construct()
{
$this->config = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::plainText('')
);

$this->config->setValidationConstraints(
new ValidAt(new SystemClock(new DateTimeZone(\date_default_timezone_get()))),
new SignedWith(new Sha256(), InMemory::plainText(config('amoclient.client_secret')))
);
}

public function redirect()
{
$client_id = config('amoclient.client_id');
Expand Down Expand Up @@ -60,17 +38,18 @@ public function callback(Request $request)
]
]);

$config = AmoclientHelper::getTokenConfig();
$tokens = json_decode((string) $response->getBody());

try {
$token = $this->config->parser()->parse($tokens->id_token);
$token = $config->parser()->parse($tokens->id_token);
} catch (\Lcobucci\JWT\Exception $exception) {
abort(400, 'Access token could not be parsed!');
}

try {
$constraints = $this->config->validationConstraints();
$this->config->validator()->assert($token, ...$constraints);
$constraints = $config->validationConstraints();
$config->validator()->assert($token, ...$constraints);
} catch (RequiredConstraintsViolated $exception) {
abort(400, 'Access token could not be verified!');
}
Expand All @@ -97,17 +76,13 @@ public function callback(Request $request)
$user->save();
}

//Login
Auth::login($user);

//Store access- and refresh-token in session
$access_token = $this->config->parser()->parse((string) $tokens->access_token);
$request->session()->put('access_token', $access_token);
$request->session()->put('access_token', $tokens->access_token);
$request->session()->put('refresh_token', $tokens->refresh_token);

//Redirect
return redirect('/amoclient/ready');

} catch (\GuzzleHttp\Exception\BadResponseException $e) {
abort(500, 'Unable to retrieve access token: '. $e->getResponse()->getBody());
}
Expand Down
40 changes: 40 additions & 0 deletions src/AmoclientHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace StudioKaa\Amoclient;

use DateTimeZone;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Validation\Constraint\ValidAt;
use Lcobucci\JWT\Validation\Constraint\SignedWith;

class AmoclientHelper{
private static $cachedConfig = null;

public static function getTokenConfig()
{
if(self::$cachedConfig !== null)
return self::$cachedConfig;

$client_id = config('amoclient.client_secret');

if($client_id == null)
{
abort(500, 'Please set AMO_CLIENT_ID and AMO_CLIENT_SECRET in .env file.');
}

self::$cachedConfig = Configuration::forSymmetricSigner(
new Sha256(),
InMemory::plainText('')
);

self::$cachedConfig->setValidationConstraints(
new ValidAt(new SystemClock(new DateTimeZone(\date_default_timezone_get()))),
new SignedWith(new Sha256(), InMemory::plainText($client_id))
);

return self::$cachedConfig;
}
}

0 comments on commit c59933a

Please sign in to comment.