DONE: sso into e-vote; WIP: feedback modules

This commit is contained in:
ISMAIL MASSERAN
2026-07-13 12:15:44 +08:00
parent a11b75729a
commit 324b7facf1
53 changed files with 1005 additions and 135 deletions
@@ -1,62 +0,0 @@
<?php
namespace Modules\Auth\Transformers;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;
use Modules\Position\Transformers\PositionResource;
use Modules\Rank\Transformers\RankResource;
use Modules\Unit\Transformers\UnitResource;
class SSOUserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'uuid' => $this->uuid,
'name' => $this->name,
'email' => $this->email,
'army_number' => $this->army_number,
'unit_id' => $this->unit_id,
'rank_id' => $this->rank_id,
'position_id' => $this->position_id,
'phone_number' => $this->phone_number,
'image_url' => $this->image_url ? Storage::disk('public')->url($this->image_url) : null,
'status' => $this->status,
'token' => $this->when(isset($this->token), $this->token),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'roles' => $this->whenLoaded('roles', function () {
return $this->roles->map(function ($role) {
return [
'id' => $role->id,
'name' => $role->name,
'guard_name' => $role->guard_name,
'permissions' => $role->permissions ? $role->permissions->map(function ($permission) {
return [
'id' => $permission->id,
'name' => $permission->name,
'guard_name' => $permission->guard_name,
'route_name' => $permission->route_name ?? null,
'created_at' => $permission->created_at,
'updated_at' => $permission->updated_at,
];
}) : [],
'created_at' => $role->created_at,
'updated_at' => $role->updated_at,
];
});
}),
'unit' => new UnitResource($this->whenLoaded('unit')),
'rank' => new RankResource($this->whenLoaded('rank')),
'position' => new PositionResource($this->whenLoaded('position')),
];
}
}
@@ -0,0 +1,6 @@
<?php
return [
'name' => 'ExternalSystem',
'issuer' => env('EXTERNAL_SYSTEM_SSO_ISSUER', 'mykopkb'),
];
@@ -0,0 +1,65 @@
<?php
namespace Modules\ExternalSystem\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Modules\ExternalSystem\Entities\ExternalSystem;
class GenerateExternalSystemSsoSecretCommand extends Command
{
protected $signature = 'external-system:generate-sso-secret
{code : External system code (e.g. e-vote)}
{--force : Replace an existing SSO secret}
{--length=64 : Secret length in characters}';
protected $description = 'Generate an SSO secret for an external system and store it in the database';
public function handle(): int
{
$code = (string) $this->argument('code');
$length = max(32, (int) $this->option('length'));
$system = ExternalSystem::query()->where('code', $code)->first();
if (! $system) {
$this->components->error("External system [{$code}] not found.");
return self::FAILURE;
}
if (! $system->sso_enabled) {
$this->components->warn("External system [{$code}] does not have SSO enabled.");
}
if (filled($system->sso_secret) && ! $this->option('force')) {
$this->components->error('An SSO secret already exists. Use --force to replace it.');
return self::FAILURE;
}
if (filled($system->sso_secret) && $this->option('force')) {
if (! $this->confirm("Replace the existing SSO secret for [{$code}]?", false)) {
$this->components->info('Aborted.');
return self::SUCCESS;
}
}
$secret = Str::password($length, symbols: true);
$system->sso_secret = $secret;
$system->save();
$this->newLine();
$this->components->info("SSO secret generated for [{$code}].");
$this->newLine();
$this->line('Copy this value into the external system environment:');
$this->newLine();
$this->line(" MYKOPKB_SSO_SECRET={$secret}");
$this->newLine();
$this->components->warn('This secret is shown once. Store it securely before closing this terminal.');
return self::SUCCESS;
}
}
@@ -0,0 +1,45 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('external_systems', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('code')->unique();
$table->string('name');
$table->text('description')->nullable();
$table->string('url');
$table->string('icon')->default('ExternalLink');
$table->boolean('is_active')->default(true);
$table->timestamp('starts_at')->nullable();
$table->timestamp('ends_at')->nullable();
$table->boolean('opens_in_new_tab')->default(true);
$table->boolean('sso_enabled')->default(false);
$table->string('sso_launch_path')->nullable();
$table->text('sso_secret')->nullable();
$table->string('sso_audience')->nullable();
$table->unsignedSmallInteger('sso_token_ttl')->default(120);
$table->boolean('require_onboarding')->default(true);
$table->string('contact_email')->nullable();
$table->text('notes')->nullable();
$table->unsignedInteger('sort_order')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('external_systems');
}
};
@@ -0,0 +1,16 @@
<?php
namespace Modules\ExternalSystem\Database\Seeders;
use Illuminate\Database\Seeder;
class ExternalSystemDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$this->call(ExternalSystemSeeder::class);
}
}
@@ -0,0 +1,53 @@
<?php
namespace Modules\ExternalSystem\Entities;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class ExternalSystem extends Model
{
use HasUuids;
protected $table = 'external_systems';
protected $fillable = [
'code',
'name',
'description',
'url',
'icon',
'is_active',
'starts_at',
'ends_at',
'opens_in_new_tab',
'sso_enabled',
'sso_launch_path',
'sso_secret',
'sso_audience',
'sso_token_ttl',
'require_onboarding',
'contact_email',
'notes',
'sort_order',
];
protected $hidden = [
'sso_secret',
];
protected function casts(): array
{
return [
'is_active' => 'boolean',
'starts_at' => 'datetime',
'ends_at' => 'datetime',
'opens_in_new_tab' => 'boolean',
'sso_enabled' => 'boolean',
'sso_secret' => 'encrypted',
'sso_token_ttl' => 'integer',
'require_onboarding' => 'boolean',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,16 @@
<?php
namespace Modules\ExternalSystem\Exceptions;
use Exception;
class ExternalSystemLaunchException extends Exception
{
public function __construct(
string $message,
public readonly string $errorCode,
public readonly int $status = 422,
) {
parent::__construct($message);
}
}
@@ -0,0 +1,83 @@
<?php
namespace Modules\ExternalSystem\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\ExternalSystem\Entities\ExternalSystem;
use Modules\ExternalSystem\Exceptions\ExternalSystemLaunchException;
use Modules\ExternalSystem\Services\ExternalSystemLaunchService;
use Modules\ExternalSystem\Transformers\ExternalSystemResource;
class ExternalSystemController extends Controller
{
public function __construct(
protected ExternalSystemLaunchService $launchService,
) {}
public function index(): JsonResponse
{
$systems = ExternalSystem::query()
->orderBy('sort_order')
->orderBy('name')
->get();
return response()->json([
'success' => true,
'data' => ExternalSystemResource::collection($systems),
]);
}
public function show(string $id): JsonResponse
{
$system = ExternalSystem::query()->find($id);
if (! $system) {
return response()->json([
'success' => false,
'message' => 'Sistem luaran tidak dijumpai.',
'data' => null,
], 404);
}
return response()->json([
'success' => true,
'data' => new ExternalSystemResource($system),
]);
}
public function launch(Request $request, string $code): JsonResponse
{
try {
$result = $this->launchService->launch($request->user(), $code);
return response()->json([
'success' => true,
'message' => 'SSO berjaya dijana.',
'data' => $result,
]);
} catch (ExternalSystemLaunchException $exception) {
return response()->json([
'success' => false,
'message' => $exception->getMessage(),
'code' => $exception->errorCode,
'data' => null,
], $exception->status);
} catch (\Throwable $exception) {
Log::error('Failed to launch external system SSO.', [
'code' => $code,
'user_id' => $request->user()?->id,
'message' => $exception->getMessage(),
]);
return response()->json([
'success' => false,
'message' => 'Gagal membuka sistem luaran. Sila cuba lagi.',
'code' => 'external_system_launch_failed',
'data' => null,
], 500);
}
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\ExternalSystem\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event handler mappings for the application.
*
* @var array<string, array<int, string>>
*/
protected $listen = [];
/**
* Indicates if events should be discovered.
*
* @var bool
*/
protected static $shouldDiscoverEvents = true;
/**
* Configure the proper event listeners for email verification.
*/
protected function configureEmailVerification(): void {}
}
@@ -0,0 +1,156 @@
<?php
namespace Modules\ExternalSystem\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class ExternalSystemServiceProvider extends ServiceProvider
{
use PathNamespace;
protected string $name = 'ExternalSystem';
protected string $nameLower = 'externalsystem';
/**
* Boot the application events.
*/
public function boot(): void
{
$this->registerCommands();
$this->registerCommandSchedules();
$this->registerTranslations();
$this->registerConfig();
$this->registerViews();
$this->loadMigrationsFrom(module_path($this->name, 'Database/Migrations'));
}
/**
* Register the service provider.
*/
public function register(): void
{
$this->app->register(EventServiceProvider::class);
$this->app->register(RouteServiceProvider::class);
}
/**
* Register commands in the format of Command::class
*/
protected function registerCommands(): void
{
$this->commands([
\Modules\ExternalSystem\Console\GenerateExternalSystemSsoSecretCommand::class,
]);
}
/**
* Register command Schedules.
*/
protected function registerCommandSchedules(): void
{
// $this->app->booted(function () {
// $schedule = $this->app->make(Schedule::class);
// $schedule->command('inspire')->hourly();
// });
}
/**
* Register translations.
*/
public function registerTranslations(): void
{
$langPath = resource_path('lang/modules/'.$this->nameLower);
if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, $this->nameLower);
$this->loadJsonTranslationsFrom($langPath);
} else {
$this->loadTranslationsFrom(module_path($this->name, 'Lang'), $this->nameLower);
$this->loadJsonTranslationsFrom(module_path($this->name, 'Lang'));
}
}
/**
* Register config.
*/
protected function registerConfig(): void
{
$configPath = module_path($this->name, config('modules.paths.generator.config.path'));
if (is_dir($configPath)) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$config = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
$config_key = str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $config);
$segments = explode('.', $this->nameLower.'.'.$config_key);
// Remove duplicated adjacent segments
$normalized = [];
foreach ($segments as $segment) {
if (end($normalized) !== $segment) {
$normalized[] = $segment;
}
}
$key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);
$this->publishes([$file->getPathname() => config_path($config)], 'config');
$this->merge_config_from($file->getPathname(), $key);
}
}
}
}
/**
* Merge config from the given path recursively.
*/
protected function merge_config_from(string $path, string $key): void
{
$existing = config($key, []);
$module_config = require $path;
config([$key => array_replace_recursive($existing, $module_config)]);
}
/**
* Register views.
*/
public function registerViews(): void
{
$viewPath = resource_path('views/modules/'.$this->nameLower);
$sourcePath = module_path($this->name, 'Resources/Views');
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);
Blade::componentNamespace(config('modules.namespace').'\\' . $this->name . '\\View\\Components', $this->nameLower);
}
/**
* Get the services provided by the provider.
*/
public function provides(): array
{
return [];
}
private function getPublishableViewPaths(): array
{
$paths = [];
foreach (config('view.paths') as $path) {
if (is_dir($path.'/modules/'.$this->nameLower)) {
$paths[] = $path.'/modules/'.$this->nameLower;
}
}
return $paths;
}
}
@@ -0,0 +1,50 @@
<?php
namespace Modules\ExternalSystem\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
protected string $name = 'ExternalSystem';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*/
public function boot(): void
{
parent::boot();
}
/**
* Define the routes for the application.
*/
public function map(): void
{
$this->mapApiRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*/
protected function mapWebRoutes(): void
{
Route::middleware('web')->group(module_path($this->name, '/Routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*/
protected function mapApiRoutes(): void
{
Route::middleware('api')->name('api.')->group(module_path($this->name, '/Routes/api.php'));
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\ExternalSystem\Http\Controllers\ExternalSystemController;
Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () {
Route::get('external-systems', [ExternalSystemController::class, 'index'])
->name('external-systems.index');
Route::get('external-systems/{id}', [ExternalSystemController::class, 'show'])
->name('external-systems.show');
Route::post('external-systems/{code}/sso/launch', [ExternalSystemController::class, 'launch'])
->name('external-systems.sso.launch');
});
+8
View File
@@ -0,0 +1,8 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\ExternalSystem\Http\Controllers\ExternalSystemController;
Route::middleware(['auth', 'verified'])->group(function () {
Route::resource('externalsystems', ExternalSystemController::class)->names('externalsystem');
});
@@ -0,0 +1,143 @@
<?php
namespace Modules\ExternalSystem\Services;
use Illuminate\Support\Str;
use Modules\Auth\Entities\User;
use Modules\ExternalSystem\Entities\ExternalSystem;
use Modules\ExternalSystem\Exceptions\ExternalSystemLaunchException;
use Modules\ExternalSystem\Support\JwtSigner;
class ExternalSystemLaunchService
{
/**
* @return array{launch_url: string, expires_at: string}
*/
public function launch(User $user, string $code): array
{
$system = $this->resolveSystem($code);
$this->assertSystemAvailable($system);
$this->assertUserEligible($user, $system);
if (! $system->sso_enabled) {
throw new ExternalSystemLaunchException(
'Sistem luaran tidak menyokong SSO.',
'external_system_sso_disabled',
422,
);
}
if (blank($system->sso_secret)) {
throw new ExternalSystemLaunchException(
'Sistem luaran belum dikonfigurasi untuk SSO.',
'external_system_sso_not_configured',
503,
);
}
$ttl = $system->sso_token_ttl ?: 120;
$issuedAt = now();
$expiresAt = $issuedAt->copy()->addSeconds($ttl);
$payload = [
'iss' => config('externalsystem.issuer', config('app.name', 'mykopkb')),
'aud' => $system->sso_audience ?: $system->code,
'sub' => $user->id,
'jti' => (string) Str::uuid(),
'iat' => $issuedAt->timestamp,
'nbf' => $issuedAt->timestamp,
'exp' => $expiresAt->timestamp,
'ic_number' => $user->ic_number,
'member_number' => $user->member_number,
];
$token = JwtSigner::sign($payload, $system->sso_secret);
$launchPath = $system->sso_launch_path ?: '/sso/login';
$launchUrl = rtrim($system->url, '/').'/'.ltrim($launchPath, '/');
$launchUrl .= '?token='.urlencode($token);
return [
'launch_url' => $launchUrl,
'expires_at' => $expiresAt->toIso8601String(),
];
}
protected function resolveSystem(string $code): ExternalSystem
{
$system = ExternalSystem::query()->where('code', $code)->first();
if (! $system) {
throw new ExternalSystemLaunchException(
'Sistem luaran tidak dijumpai.',
'external_system_not_found',
404,
);
}
return $system;
}
protected function assertSystemAvailable(ExternalSystem $system): void
{
if (! $system->is_active) {
throw new ExternalSystemLaunchException(
'Sistem luaran tidak aktif.',
'external_system_inactive',
403,
);
}
$now = now();
if ($system->starts_at?->isAfter($now)) {
throw new ExternalSystemLaunchException(
'Sistem luaran belum tersedia.',
'external_system_upcoming',
403,
);
}
if ($system->ends_at?->isBefore($now)) {
throw new ExternalSystemLaunchException(
'Tempoh akses sistem luaran telah tamat.',
'external_system_ended',
403,
);
}
}
protected function assertUserEligible(User $user, ExternalSystem $system): void
{
if ($user->status !== 'active') {
throw new ExternalSystemLaunchException(
'Hanya anggota aktif boleh membuka sistem luaran.',
'external_system_user_inactive',
403,
);
}
if (blank($user->ic_number)) {
throw new ExternalSystemLaunchException(
'Nombor kad pengenalan diperlukan sebelum membuka sistem luaran.',
'external_system_ic_required',
422,
);
}
if (blank($user->member_number)) {
throw new ExternalSystemLaunchException(
'Nombor anggota diperlukan sebelum membuka sistem luaran.',
'external_system_member_number_required',
422,
);
}
if ($system->require_onboarding && blank($user->onboarding_completed_at)) {
throw new ExternalSystemLaunchException(
'Sila lengkapkan profil anda sebelum membuka sistem luaran.',
'external_system_profile_incomplete',
422,
);
}
}
}
@@ -0,0 +1,33 @@
<?php
namespace Modules\ExternalSystem\Support;
class JwtSigner
{
/**
* @param array<string, mixed> $payload
*/
public static function sign(array $payload, string $secret): string
{
$header = [
'typ' => 'JWT',
'alg' => 'HS256',
];
$segments = [
self::base64UrlEncode(json_encode($header, JSON_THROW_ON_ERROR)),
self::base64UrlEncode(json_encode($payload, JSON_THROW_ON_ERROR)),
];
$signingInput = implode('.', $segments);
$signature = hash_hmac('sha256', $signingInput, $secret, true);
$segments[] = self::base64UrlEncode($signature);
return implode('.', $segments);
}
protected static function base64UrlEncode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
}
@@ -0,0 +1,30 @@
<?php
namespace Modules\ExternalSystem\Transformers;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class ExternalSystemResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'code' => $this->code,
'name' => $this->name,
'description' => $this->description,
'url' => $this->url,
'icon' => $this->icon,
'is_active' => $this->is_active,
'starts_at' => $this->starts_at?->toIso8601String(),
'ends_at' => $this->ends_at?->toIso8601String(),
'opens_in_new_tab' => $this->opens_in_new_tab,
'sso_enabled' => $this->sso_enabled,
'contact_email' => $this->contact_email,
'notes' => $this->notes,
'created_at' => $this->created_at?->toIso8601String(),
'updated_at' => $this->updated_at?->toIso8601String(),
];
}
}
+30
View File
@@ -0,0 +1,30 @@
{
"name": "nwidart/externalsystem",
"description": "",
"authors": [
{
"name": "Nicolas Widart",
"email": "n.widart@gmail.com"
}
],
"extra": {
"laravel": {
"providers": [],
"aliases": {
}
}
},
"autoload": {
"psr-4": {
"Modules\\ExternalSystem\\": "App",
"Modules\\ExternalSystem\\Database\\Factories\\": "database/factories/",
"Modules\\ExternalSystem\\Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Modules\\ExternalSystem\\Tests\\": "tests/"
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "ExternalSystem",
"alias": "externalsystem",
"description": "",
"keywords": [],
"priority": 0,
"providers": [
"Modules\\ExternalSystem\\Providers\\ExternalSystemServiceProvider"
],
"files": []
}
+15
View File
@@ -0,0 +1,15 @@
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"axios": "^1.1.2",
"laravel-vite-plugin": "^0.7.5",
"sass": "^1.69.5",
"postcss": "^8.3.7",
"vite": "^4.0.0"
}
}