Skip to content

Commit

Permalink
staging Implement demo app
Browse files Browse the repository at this point in the history
  • Loading branch information
latheesan-k committed Nov 18, 2024
1 parent 48cb966 commit bba2a2e
Show file tree
Hide file tree
Showing 7 changed files with 256 additions and 5 deletions.
7 changes: 5 additions & 2 deletions application/app/Http/Controllers/API/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@ public function init(string $publicApiKey, string $authProvider, Request $reques
// Handle wallet auth provider
if ($authProvider === AuthProviderType::WALLET->value) {
// TODO: Handle wallet auth differently
exit('TODO');
return response()->json([
'error' => __('Not Implemented'),
'reason' => __('Wallet is not supported yet'),
], 400);
}

// Handle social auth provider
Expand Down Expand Up @@ -123,7 +126,7 @@ public function check(string $publicApiKey, Request $request): JsonResponse
);

// Check if this request should be geo-blocked
if ($this->isGEOBlocked($project, $request)) {
if ($isAuthenticated && $this->isGEOBlocked($project, $request)) {

// Invalidate the isAuthenticated state
$isAuthenticated = false;
Expand Down
34 changes: 34 additions & 0 deletions application/config/cors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

return [

/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/

'paths' => ['*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

];
28 changes: 28 additions & 0 deletions application/database/factories/ProjectFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Database\Factories;

use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* @extends Factory<Project>
*/
class ProjectFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'user_id' => 0,
'name' => 'Hydra Doom Testing',
'public_api_key' => '067d20be-8baa-49cb-b501-e004af358870',
'private_api_key' => 'f200599d-5d54-4883-b53d-318a00a055e2',
'geo_blocked_countries' => 'CU, IR, KP, SY, UA', // Cuba, Iran, North Korea, Syria, Ukraine
];
}
}
4 changes: 2 additions & 2 deletions application/database/factories/UserFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
* @extends Factory<User>
*/
class UserFactory extends Factory
{
Expand Down
8 changes: 7 additions & 1 deletion application/database/seeders/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Database\Seeders;

use App\Models\Project;
use App\Models\User;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
Expand All @@ -17,11 +18,16 @@ public function run(): void
if (app()->environment('local', 'staging')) {

// Seed test user
User::factory()->create([
$user = User::factory()->create([
'name' => 'Test User',
'email' => '[email protected]',
]);

// Seed test project
Project::factory()->create([
'user_id' => $user->id,
]);

}
}
}
179 changes: 179 additions & 0 deletions application/resources/views/demo.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RewardEngine Auth Demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
html,
body {
height: 100%;
}
.form-sign-in {
max-width: 600px;
padding: 1rem;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body class="d-flex align-items-center py-4 bg-body-tertiary">

<main class="form-sign-in w-100 m-auto bg-secondary-subtle">

<div id="status" style="display: none;">...</div>

<div id="demo">
<div class="mb-3">
<label class="form-label">API Base URL</label>
<input id="apiBaseUrl" value="{{ url('') }}/api/v1" type="text" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">Public API Key</label>
<input id="apiPublicKey" value="067d20be-8baa-49cb-b501-e004af358870" placeholder="e.g. 067d20be-8baa-49cb-b501-e004af358870" type="text" class="form-control">
</div>
<button id="loadAvailableAuthProvidersButton" type="button" class="btn btn-sm btn-primary">Load Available Auth Providers</button>
</div>

<div id="authContainer" style="display: none;">...</div>

</main>

<script type="text/javascript">
// References
const $status = $('div#status');
const $demo = $('div#demo');
const $authContainer = $('div#authContainer');
let apiBaseUrl, publicApiKey, reference;
// Auth init helper
const signIn = (target) => {
const redirectUrl = $(target).data('redirect-url');
$authContainer.hide();
$status.html('Waiting for you to sign-in...').show();
startPolling();
window.open(redirectUrl, '_blank').focus();
};
// Auth check helper
let timer = null;
const startPolling = () => {
timer = setInterval(() => {
$.ajax({
type: 'get',
url: `${apiBaseUrl}/auth/check/${ publicApiKey }/?reference=${ reference }`,
success: function (authState) {
if (authState && authState.authenticated === true) {
clearInterval(timer);
$status.html(`
<h1>Successfully Signed In</h1>
<hr>
<strong>Account</strong>
<div class="mb-1">
<label class="form-label">Auth Provider</label>
<input value="${ authState.account.auth_provider }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Auth Provider ID</label>
<input value="${ authState.account.auth_provider_id }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Auth Name</label>
<input value="${ authState.account.auth_name }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Auth Email</label>
<input value="${ authState.account.auth_email }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Auth Avatar</label>
<br>
<img src="${ authState.account.auth_avatar }" width="128" alt="" class="rounded-circle" />
</div>
<hr>
<strong>Session</strong>
<div class="mb-1">
<label class="form-label">Reference (e.g. Ephemeral Key)</label>
<input value="${ authState.session.reference }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Session Id</label>
<input value="${ authState.session.session_id }" type="text" class="form-control form-control-sm" disabled>
</div>
<div class="mb-1">
<label class="form-label">Auth Country Code</label>
<input value="${ authState.session.auth_country_code }" type="text" class="form-control form-control-sm" disabled>
</div>
<div>
<label class="form-label">Authenticated At (UTC)</label>
<input value="${ authState.session.authenticated_at }" type="text" class="form-control form-control-sm" disabled>
</div>
`);
}
},
error: function (request) {
alert(`Error: ${request.responseJSON.error}\n\nReason: ${request.responseJSON.reason}`)
},
});
}, (10 * 1000));
};
// When page loads
$(document).ready(function()
{
// Helpers
const capitalize = s => (s && String(s[0]).toUpperCase() + String(s).slice(1)) || '';
const randomString = () => Math.random().toString(36).slice(2);
// Load available sign-in methods
$('button#loadAvailableAuthProvidersButton').click(function() {
// Remember api base url & public api key
apiBaseUrl = $('input#apiBaseUrl').val();
publicApiKey = $('input#apiPublicKey').val();
if (!publicApiKey || publicApiKey.length <= 0) {
alert('Please specify your public api key');
return;
}
// Fetch available sign in methods
$demo.hide();
$status.html('Loading available auth providers...').show();
$.ajax({
type: 'get',
url: `${ apiBaseUrl }/auth/providers`,
success: function (authProviders) {
reference = randomString();
let authUI = `
<h1>Sign In</h1>
<div class="mb-3">
<label class="form-label">Reference (e.g. Ephemeral Key)</label>
<input id="reference" value="${ reference }" type="text" class="form-control" disabled>
</div>
`;
authProviders.forEach(authProvider => {
if (authProvider !== 'wallet') { // Not yet implemented
authUI += `
<div class="mb-3">
<button type="button" onclick="signIn(this)" data-redirect-url="${ apiBaseUrl }/auth/init/${ publicApiKey }/${ authProvider }/?reference=${ reference }" class="btn col-12 btn-primary">
${ capitalize(authProvider) }
</button>
</div>
`;
}
});
$status.hide();
$authContainer.html(authUI).show();
},
error: function (request) {
alert(`Error: ${request.responseJSON.error}\n\nReason: ${request.responseJSON.reason}`)
},
});
});
});
</script>

</body>
</html>
1 change: 1 addition & 0 deletions application/routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Facades\Route;

Route::get('/', [WelcomeController::class, 'index']);
Route::get('demo', fn() => view('demo'));
Route::get('social-auth-callback/{authProvider}', [SocialAuthCallbackController::class, 'handle']);

Route::middleware(['auth', 'verified'])->group(static function () {
Expand Down

0 comments on commit bba2a2e

Please sign in to comment.