Feature/phone register (#11)
Co-authored-by: ISMAIL MASSERAN <topaz@ISMAILs-Macbook.local> Co-authored-by: ISMAIL MASSERAN <topaz@Mac.dlinkrouter.local> Reviewed-on: #11
This commit was merged in pull request #11.
This commit is contained in:
@@ -5,15 +5,15 @@
|
|||||||
## Improvement
|
## Improvement
|
||||||
[ ] mesyuarat anggota tertinggi
|
[ ] mesyuarat anggota tertinggi
|
||||||
[ ] penyata anggota
|
[ ] penyata anggota
|
||||||
[ ] daftar anggota
|
[x] daftar anggota
|
||||||
[ ] baki pinjaman - transaction history: tarik dari ubs
|
[ ] baki pinjaman - transaction history: tarik dari ubs
|
||||||
[ ] pembiayaan anggota
|
[ ] pembiayaan anggota
|
||||||
[ ] sumbangan
|
[ ] sumbangan
|
||||||
[ ] wasi/penama
|
[x] wasi/penama
|
||||||
[ ] pendaftaran anggota/meneruskan anggota/pencen
|
[ ] pendaftaran anggota/meneruskan anggota/pencen
|
||||||
[ ] daftar lembaga (backdated)
|
[x] daftar lembaga (backdated)
|
||||||
[ ] boleh print semua borang
|
[x] boleh print semua borang
|
||||||
[ ] jana surat lepas lulus anggota
|
[x] jana surat lepas lulus anggota
|
||||||
|
|
||||||
## Present to Boss (2/7/2026)
|
## Present to Boss (2/7/2026)
|
||||||
[x] discuss logo baru MyKOPKB
|
[x] discuss logo baru MyKOPKB
|
||||||
@@ -29,4 +29,4 @@
|
|||||||
[ ] syer maksima silap tukar jadi rm50.00
|
[ ] syer maksima silap tukar jadi rm50.00
|
||||||
[x] letak sign digital
|
[x] letak sign digital
|
||||||
[x] running no anggota dalam surat dan masa.
|
[x] running no anggota dalam surat dan masa.
|
||||||
[ ] tukar logo di surat offer
|
[x] tukar logo di surat offer
|
||||||
@@ -3,6 +3,7 @@ APP_ENV=local
|
|||||||
APP_KEY=
|
APP_KEY=
|
||||||
APP_DEBUG=true
|
APP_DEBUG=true
|
||||||
APP_URL=http://localhost
|
APP_URL=http://localhost
|
||||||
|
FRONTEND_URL=http://localhost:5173
|
||||||
|
|
||||||
APP_LOCALE=en
|
APP_LOCALE=en
|
||||||
APP_FALLBACK_LOCALE=en
|
APP_FALLBACK_LOCALE=en
|
||||||
@@ -87,3 +88,20 @@ AUTH_COOKIE_EXPOSE_TOKEN=false
|
|||||||
ACTIVE_ROLE_PREFER_MEMBER=true
|
ACTIVE_ROLE_PREFER_MEMBER=true
|
||||||
ACTIVE_ROLE_MEMBER_REDIRECT=/profile
|
ACTIVE_ROLE_MEMBER_REDIRECT=/profile
|
||||||
ACTIVE_ROLE_ADMIN_REDIRECT=/profile
|
ACTIVE_ROLE_ADMIN_REDIRECT=/profile
|
||||||
|
|
||||||
|
PUBLIC_PROFILE_TOKEN_TTL_DAYS=7
|
||||||
|
|
||||||
|
EMAIL_VERIFICATION_EXPIRE_MINUTES=60
|
||||||
|
EMAIL_VERIFICATION_REDIRECT_PATH=/profile-overview-2
|
||||||
|
|
||||||
|
PHONE_VERIFICATION_OTP_EXPIRY_MINUTES=10
|
||||||
|
PHONE_VERIFICATION_TOKEN_EXPIRY_MINUTES=30
|
||||||
|
PHONE_VERIFICATION_OTP_MAX_ATTEMPTS=5
|
||||||
|
|
||||||
|
SMS_DRIVER=log # onewaysms
|
||||||
|
ONEWAYSMS_BASE_URL=http://gateway.onewaysms.com.my:10001/api.aspx
|
||||||
|
ONEWAYSMS_API_USERNAME=
|
||||||
|
ONEWAYSMS_API_PASSWORD=
|
||||||
|
ONEWAYSMS_SENDER_ID=
|
||||||
|
|
||||||
|
EXTERNAL_SYSTEM_SSO_ISSUER=mykopkb
|
||||||
+18
-14
@@ -54,7 +54,6 @@ REDIS_PORT=6379
|
|||||||
REDIS_PASSWORD=mykopkb_redis@2025
|
REDIS_PASSWORD=mykopkb_redis@2025
|
||||||
REDIS_DB=0
|
REDIS_DB=0
|
||||||
|
|
||||||
# only change this to smtp if is deployed to public server
|
|
||||||
MAIL_MAILER=smtp
|
MAIL_MAILER=smtp
|
||||||
MAIL_SCHEME=smtp
|
MAIL_SCHEME=smtp
|
||||||
MAIL_HOST=mail.koppkb.com
|
MAIL_HOST=mail.koppkb.com
|
||||||
@@ -80,18 +79,6 @@ VITE_APP_NAME="${APP_NAME}"
|
|||||||
EXTERNAL_API_TOKEN=""
|
EXTERNAL_API_TOKEN=""
|
||||||
EXTERNAL_API_BASE_URL=
|
EXTERNAL_API_BASE_URL=
|
||||||
|
|
||||||
# SSO_SECRET=""
|
|
||||||
# SSO_VALIDATION_URL="https://saktitd.army.mil.my/api/sso-validate"
|
|
||||||
# SSO_MAX_ATTEMPTS=5
|
|
||||||
# SSO_TOKEN_EXPIRATION=300
|
|
||||||
# SSO_AUTO_ACTIVATE_USERS=true
|
|
||||||
# SSO_LOG_ACTIVITIES=true
|
|
||||||
# SSO_CONNECTION_TIMEOUT=10
|
|
||||||
# SSO_RESPONSE_TIMEOUT=30
|
|
||||||
# SSO_PROXY_URL=
|
|
||||||
# SSO_ENABLE_FALLBACK=true
|
|
||||||
# SSO_PROXY_ENABLED=true
|
|
||||||
|
|
||||||
SANCTUM_STATEFUL_DOMAINS=api.koppkb.com
|
SANCTUM_STATEFUL_DOMAINS=api.koppkb.com
|
||||||
|
|
||||||
BLOCK_API_TOOLS_IN_PRODUCTION=true
|
BLOCK_API_TOOLS_IN_PRODUCTION=true
|
||||||
@@ -106,4 +93,21 @@ API_LOG_KEY_USAGE=true
|
|||||||
|
|
||||||
PUBLIC_PROFILE_TOKEN_TTL_DAYS=7
|
PUBLIC_PROFILE_TOKEN_TTL_DAYS=7
|
||||||
FRONTEND_URL=https://mykopkb.koppkb.com
|
FRONTEND_URL=https://mykopkb.koppkb.com
|
||||||
BROWSERSHOT_NO_SANDBOX=true
|
BROWSERSHOT_NO_SANDBOX=true
|
||||||
|
|
||||||
|
PUBLIC_PROFILE_TOKEN_TTL_DAYS=7
|
||||||
|
|
||||||
|
EMAIL_VERIFICATION_EXPIRE_MINUTES=60
|
||||||
|
EMAIL_VERIFICATION_REDIRECT_PATH=/profile-overview-2
|
||||||
|
|
||||||
|
PHONE_VERIFICATION_OTP_EXPIRY_MINUTES=10
|
||||||
|
PHONE_VERIFICATION_TOKEN_EXPIRY_MINUTES=30
|
||||||
|
PHONE_VERIFICATION_OTP_MAX_ATTEMPTS=5
|
||||||
|
|
||||||
|
SMS_DRIVER=onewaysms
|
||||||
|
ONEWAYSMS_BASE_URL=http://gateway.onewaysms.com.my:10001/api.aspx
|
||||||
|
ONEWAYSMS_API_USERNAME=API7LO0ELJTAU
|
||||||
|
ONEWAYSMS_API_PASSWORD=API7LO0ELJTAU7LO0E
|
||||||
|
ONEWAYSMS_SENDER_ID=INFO
|
||||||
|
|
||||||
|
EXTERNAL_SYSTEM_SSO_ISSUER=mykopkb
|
||||||
@@ -10,23 +10,25 @@ use Illuminate\Support\Str;
|
|||||||
use Illuminate\Validation\Rule;
|
use Illuminate\Validation\Rule;
|
||||||
use Laravel\Fortify\Contracts\CreatesNewUsers;
|
use Laravel\Fortify\Contracts\CreatesNewUsers;
|
||||||
use Modules\Auth\Entities\User;
|
use Modules\Auth\Entities\User;
|
||||||
|
use Modules\Auth\Services\PhoneVerificationOtpService;
|
||||||
use Modules\Role\Entities\Role;
|
use Modules\Role\Entities\Role;
|
||||||
use Modules\User\Notifications\UserActivationNotification;
|
use Modules\User\Notifications\UserActivationNotification;
|
||||||
use Modules\Auth\Services\EmailVerificationOtpService;
|
use Modules\User\Policies\UserPolicy;
|
||||||
use Exception;
|
use Exception;
|
||||||
|
|
||||||
class CreateNewUser implements CreatesNewUsers
|
class CreateNewUser implements CreatesNewUsers
|
||||||
{
|
{
|
||||||
use PasswordValidationRules, NotifiesAdmins;
|
use PasswordValidationRules, NotifiesAdmins;
|
||||||
|
|
||||||
/**
|
public function __construct(
|
||||||
* Validate and create a newly registered user.
|
protected PhoneVerificationOtpService $phoneVerificationOtpService,
|
||||||
*
|
) {}
|
||||||
* @param array<string, string> $input
|
|
||||||
*/
|
|
||||||
public function create(array $input): User
|
public function create(array $input): User
|
||||||
{
|
{
|
||||||
Validator::make($input, [
|
$phoneNumber = $this->phoneVerificationOtpService->normalizePhoneNumber($input['phone_number'] ?? '');
|
||||||
|
|
||||||
|
Validator::make(array_merge($input, ['phone_number' => $phoneNumber]), [
|
||||||
'name' => ['required', 'string', 'max:255'],
|
'name' => ['required', 'string', 'max:255'],
|
||||||
'email' => [
|
'email' => [
|
||||||
'required',
|
'required',
|
||||||
@@ -36,15 +38,32 @@ class CreateNewUser implements CreatesNewUsers
|
|||||||
Rule::unique(User::class),
|
Rule::unique(User::class),
|
||||||
],
|
],
|
||||||
'ic_number' => ['required', 'string', 'max:255'],
|
'ic_number' => ['required', 'string', 'max:255'],
|
||||||
|
'phone_number' => [
|
||||||
|
...$this->phoneVerificationOtpService->phoneNumberRules(),
|
||||||
|
Rule::unique(User::class),
|
||||||
|
],
|
||||||
|
'phone_verification_token' => ['required', 'string', 'size:64'],
|
||||||
'password' => ['required', 'string', 'min:8'],
|
'password' => ['required', 'string', 'min:8'],
|
||||||
|
], [
|
||||||
|
'phone_number.required' => 'Nombor telefon diperlukan.',
|
||||||
|
'phone_number.regex' => 'Format nombor telefon tidak sah.',
|
||||||
|
'phone_number.unique' => 'Nombor telefon ini telah didaftarkan.',
|
||||||
|
'phone_verification_token.required' => 'Pengesahan nombor telefon diperlukan.',
|
||||||
])->validate();
|
])->validate();
|
||||||
|
|
||||||
|
$this->phoneVerificationOtpService->consumeRegistrationToken(
|
||||||
|
$phoneNumber,
|
||||||
|
$input['phone_verification_token'],
|
||||||
|
);
|
||||||
|
|
||||||
$user = User::create([
|
$user = User::create([
|
||||||
'name' => $input['name'],
|
'name' => $input['name'],
|
||||||
'uuid' => Str::uuid(),
|
'uuid' => Str::uuid(),
|
||||||
'email' => $input['email'],
|
'email' => $input['email'],
|
||||||
'password' => Hash::make($input['password']),
|
'password' => Hash::make($input['password']),
|
||||||
'ic_number' => $input['ic_number'],
|
'ic_number' => $input['ic_number'],
|
||||||
|
'phone_number' => $phoneNumber,
|
||||||
|
'phone_verified_at' => now(),
|
||||||
'status' => 'pending',
|
'status' => 'pending',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -54,9 +73,6 @@ class CreateNewUser implements CreatesNewUsers
|
|||||||
$user->assignRole($role);
|
$user->assignRole($role);
|
||||||
}
|
}
|
||||||
|
|
||||||
app(EmailVerificationOtpService::class)->send($user);
|
|
||||||
|
|
||||||
// Send notification to admins if user requires activation
|
|
||||||
if ($user->status === 'pending') {
|
if ($user->status === 'pending') {
|
||||||
$this->notifyAdminsForActivation($user);
|
$this->notifyAdminsForActivation($user);
|
||||||
}
|
}
|
||||||
@@ -65,21 +81,19 @@ class CreateNewUser implements CreatesNewUsers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Notify admins about new user requiring activation
|
* Notify users who can kemaskini pengguna about new user requiring activation.
|
||||||
*/
|
*/
|
||||||
private function notifyAdminsForActivation(User $newUser): void
|
private function notifyAdminsForActivation(User $newUser): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$adminRoles = ['PENTADBIR', 'PS 2 KJC', 'PS 2 ALAT'];
|
$recipients = $this->getUsersWithPermission(UserPolicy::PERMISSION_UPDATE)
|
||||||
|
->where('id', '!=', $newUser->id);
|
||||||
// Get users with specific roles plus admins (PENTADBIR and DEVELOPER)
|
|
||||||
$adminUsers = $this->getUsersWithRolesAndAdmins($adminRoles);
|
|
||||||
|
|
||||||
$sender = auth()->user() ?? $newUser; // Use current user as sender, or new user if no auth
|
$sender = auth()->user() ?? $newUser;
|
||||||
|
|
||||||
foreach ($adminUsers as $admin) {
|
foreach ($recipients as $recipient) {
|
||||||
try {
|
try {
|
||||||
$admin->notify(new UserActivationNotification($newUser, $sender));
|
$recipient->notify(new UserActivationNotification($newUser, $sender));
|
||||||
} catch (Exception $e) {
|
} catch (Exception $e) {
|
||||||
Log::error('Failed to send user activation notification: '.$e->getMessage());
|
Log::error('Failed to send user activation notification: '.$e->getMessage());
|
||||||
}
|
}
|
||||||
@@ -88,4 +102,5 @@ class CreateNewUser implements CreatesNewUsers
|
|||||||
Log::error('Failed to notify admins for user activation: '.$e->getMessage());
|
Log::error('Failed to notify admins for user activation: '.$e->getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,39 +3,19 @@
|
|||||||
namespace Modules\Auth\Actions\Fortify;
|
namespace Modules\Auth\Actions\Fortify;
|
||||||
|
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use Laravel\Fortify\Contracts\LoginResponse as ContractsLoginResponse;
|
use Laravel\Fortify\Contracts\LoginResponse as ContractsLoginResponse;
|
||||||
use Modules\Auth\Services\AuthSessionService;
|
use Modules\Auth\Services\AuthSessionService;
|
||||||
use Modules\Auth\Services\EmailVerificationOtpService;
|
|
||||||
|
|
||||||
class LoginResponse implements ContractsLoginResponse
|
class LoginResponse implements ContractsLoginResponse
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
protected AuthSessionService $authSession,
|
protected AuthSessionService $authSession,
|
||||||
protected EmailVerificationOtpService $otpService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function toResponse($request): JsonResponse
|
public function toResponse($request): JsonResponse
|
||||||
{
|
{
|
||||||
$user = $request->user();
|
|
||||||
|
|
||||||
if (! $user->hasVerifiedEmail()) {
|
|
||||||
$this->otpService->send($user);
|
|
||||||
|
|
||||||
Auth::guard(config('fortify.guard'))->logout();
|
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'success' => true,
|
|
||||||
'message' => 'Sila semak e-mel anda untuk kod pengesahan 6 digit.',
|
|
||||||
'data' => [
|
|
||||||
'email' => $user->email,
|
|
||||||
'requires_email_verification' => true,
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->authSession->createAuthResponse(
|
return $this->authSession->createAuthResponse(
|
||||||
$user,
|
$request->user(),
|
||||||
'Login successful'
|
'Login successful'
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,24 +3,21 @@
|
|||||||
namespace Modules\Auth\Actions\Fortify;
|
namespace Modules\Auth\Actions\Fortify;
|
||||||
|
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
|
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
|
||||||
|
use Modules\Auth\Services\AuthSessionService;
|
||||||
|
|
||||||
class RegisterResponse implements RegisterResponseContract
|
class RegisterResponse implements RegisterResponseContract
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected AuthSessionService $authSession,
|
||||||
|
) {}
|
||||||
|
|
||||||
public function toResponse($request): JsonResponse
|
public function toResponse($request): JsonResponse
|
||||||
{
|
{
|
||||||
$email = $request->user()?->email;
|
return $this->authSession->createAuthResponse(
|
||||||
|
$request->user(),
|
||||||
Auth::guard(config('fortify.guard'))->logout();
|
'Pendaftaran berjaya. Akaun anda sedang menunggu pengaktifan daripada pentadbir sistem.',
|
||||||
|
201
|
||||||
return response()->json([
|
);
|
||||||
'success' => true,
|
|
||||||
'message' => 'Pendaftaran berjaya. Sila semak e-mel anda untuk kod pengesahan 6 digit.',
|
|
||||||
'data' => [
|
|
||||||
'email' => $email,
|
|
||||||
'requires_email_verification' => true,
|
|
||||||
],
|
|
||||||
], 201);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Contracts;
|
||||||
|
|
||||||
|
interface SmsSender
|
||||||
|
{
|
||||||
|
public function send(string $phoneNumber, string $message): void;
|
||||||
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Auth\Emails;
|
|
||||||
|
|
||||||
use App\Notifications\Concerns\BuildsMailMessage;
|
|
||||||
use Illuminate\Bus\Queueable;
|
|
||||||
use Illuminate\Notifications\Messages\MailMessage;
|
|
||||||
use Illuminate\Notifications\Notification;
|
|
||||||
|
|
||||||
class EmailVerificationOtpEmail extends Notification
|
|
||||||
{
|
|
||||||
use BuildsMailMessage;
|
|
||||||
use Queueable;
|
|
||||||
|
|
||||||
public function __construct(
|
|
||||||
protected string $otp
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function via(object $notifiable): array
|
|
||||||
{
|
|
||||||
return ['mail'];
|
|
||||||
}
|
|
||||||
|
|
||||||
public function toMail(object $notifiable): MailMessage
|
|
||||||
{
|
|
||||||
$minutes = (int) config('auth.email_verification.expiry_minutes', 10);
|
|
||||||
|
|
||||||
return $this->mailMessage(
|
|
||||||
subject: 'Pengesahan E-mel - Kod OTP',
|
|
||||||
view: 'auth::emails.verification-otp',
|
|
||||||
data: [
|
|
||||||
'name' => $notifiable->name,
|
|
||||||
'otp' => $this->otp,
|
|
||||||
'minutes' => $minutes,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+15
-10
@@ -4,19 +4,21 @@ namespace Modules\Auth\Entities;
|
|||||||
|
|
||||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
||||||
|
|
||||||
class EmailVerificationOtp extends Model
|
class PhoneVerificationOtp extends Model
|
||||||
{
|
{
|
||||||
use HasUuids;
|
use HasUuids;
|
||||||
|
|
||||||
protected $table = 'email_verification_otps';
|
protected $table = 'phone_verification_otps';
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'user_id',
|
'phone_number',
|
||||||
'code',
|
'code',
|
||||||
'expires_at',
|
'expires_at',
|
||||||
'attempts',
|
'attempts',
|
||||||
|
'verified_at',
|
||||||
|
'verification_token',
|
||||||
|
'verification_token_expires_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
@@ -24,14 +26,11 @@ class EmailVerificationOtp extends Model
|
|||||||
return [
|
return [
|
||||||
'expires_at' => 'datetime',
|
'expires_at' => 'datetime',
|
||||||
'attempts' => 'integer',
|
'attempts' => 'integer',
|
||||||
|
'verified_at' => 'datetime',
|
||||||
|
'verification_token_expires_at' => 'datetime',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function user(): BelongsTo
|
|
||||||
{
|
|
||||||
return $this->belongsTo(User::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function isExpired(): bool
|
public function isExpired(): bool
|
||||||
{
|
{
|
||||||
return $this->expires_at->isPast();
|
return $this->expires_at->isPast();
|
||||||
@@ -39,6 +38,12 @@ class EmailVerificationOtp extends Model
|
|||||||
|
|
||||||
public function hasExceededMaxAttempts(): bool
|
public function hasExceededMaxAttempts(): bool
|
||||||
{
|
{
|
||||||
return $this->attempts >= (int) config('auth.email_verification.max_attempts', 5);
|
return $this->attempts >= (int) config('auth.phone_verification.max_attempts', 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isVerificationTokenExpired(): bool
|
||||||
|
{
|
||||||
|
return $this->verification_token_expires_at === null
|
||||||
|
|| $this->verification_token_expires_at->isPast();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
namespace Modules\Auth\Entities;
|
namespace Modules\Auth\Entities;
|
||||||
|
|
||||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait;
|
||||||
|
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
@@ -22,12 +23,13 @@ use Modules\Role\Entities\Role;
|
|||||||
use Modules\User\Entities\Address;
|
use Modules\User\Entities\Address;
|
||||||
use Modules\User\Entities\BankDetail;
|
use Modules\User\Entities\BankDetail;
|
||||||
use Modules\User\Entities\Employment;
|
use Modules\User\Entities\Employment;
|
||||||
|
use Modules\Auth\Notifications\VerifyEmailNotification;
|
||||||
use Modules\User\Entities\Heir;
|
use Modules\User\Entities\Heir;
|
||||||
|
|
||||||
class User extends Authenticatable
|
class User extends Authenticatable implements MustVerifyEmail
|
||||||
{
|
{
|
||||||
/** @use HasFactory<\Modules\Auth\Database\Factories\UserFactory> */
|
/** @use HasFactory<\Modules\Auth\Database\Factories\UserFactory> */
|
||||||
use HasApiTokens, HasFactory, HasPermissions, HasRoles, HasUuids, Impersonate, LogsActivity, Notifiable, SoftDeletes;
|
use HasApiTokens, HasFactory, HasPermissions, HasRoles, HasUuids, Impersonate, LogsActivity, MustVerifyEmailTrait, Notifiable, SoftDeletes;
|
||||||
|
|
||||||
protected $table = 'users';
|
protected $table = 'users';
|
||||||
|
|
||||||
@@ -43,6 +45,7 @@ class User extends Authenticatable
|
|||||||
'ic_number',
|
'ic_number',
|
||||||
'position',
|
'position',
|
||||||
'phone_number',
|
'phone_number',
|
||||||
|
'phone_verified_at',
|
||||||
'image_url',
|
'image_url',
|
||||||
'status',
|
'status',
|
||||||
'two_factor_secret',
|
'two_factor_secret',
|
||||||
@@ -129,6 +132,7 @@ class User extends Authenticatable
|
|||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'email_verified_at' => 'datetime',
|
'email_verified_at' => 'datetime',
|
||||||
|
'phone_verified_at' => 'datetime',
|
||||||
'password' => 'hashed',
|
'password' => 'hashed',
|
||||||
'status' => 'string',
|
'status' => 'string',
|
||||||
'gender' => 'string',
|
'gender' => 'string',
|
||||||
@@ -301,9 +305,9 @@ class User extends Authenticatable
|
|||||||
return $currentUser->hasPermissionTo('menyamar pengguna');
|
return $currentUser->hasPermissionTo('menyamar pengguna');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function hasVerifiedEmail(): bool
|
public function sendEmailVerificationNotification(): void
|
||||||
{
|
{
|
||||||
return $this->email_verified_at !== null;
|
$this->notify(new VerifyEmailNotification);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -315,15 +319,11 @@ class User extends Authenticatable
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Whether credentials are valid for issuing a session (includes verified pending users).
|
* Whether credentials are valid for issuing a session (includes pending users awaiting admin activation).
|
||||||
*/
|
*/
|
||||||
public function canAuthenticate(): bool
|
public function canAuthenticate(): bool
|
||||||
{
|
{
|
||||||
if ($this->canLogin()) {
|
return in_array($this->status, ['active', 'pending'], true);
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->hasVerifiedEmail() && $this->status === 'pending';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -3,60 +3,66 @@
|
|||||||
namespace Modules\Auth\Http\Controllers;
|
namespace Modules\Auth\Http\Controllers;
|
||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Auth\Events\Verified;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\URL;
|
||||||
use Modules\Auth\Entities\User;
|
use Modules\Auth\Entities\User;
|
||||||
use Modules\Auth\Services\AuthSessionService;
|
|
||||||
use Modules\Auth\Services\EmailVerificationOtpService;
|
|
||||||
|
|
||||||
class EmailVerificationController extends Controller
|
class EmailVerificationController extends Controller
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function verify(Request $request, string $id, string $hash): RedirectResponse
|
||||||
protected EmailVerificationOtpService $otpService,
|
|
||||||
protected AuthSessionService $authSession
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function verify(Request $request): JsonResponse
|
|
||||||
{
|
{
|
||||||
$validated = $request->validate([
|
if (! URL::hasValidSignature($request)) {
|
||||||
'email' => ['required', 'string', 'email'],
|
return $this->redirectToFrontend('invalid');
|
||||||
'otp' => ['required', 'string', 'digits:6'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$user = User::where('email', $validated['email'])->first();
|
|
||||||
|
|
||||||
if (! $user) {
|
|
||||||
return response()->json([
|
|
||||||
'success' => false,
|
|
||||||
'message' => 'Kod OTP tidak sah.',
|
|
||||||
], 422);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->otpService->verify($user, $validated['otp']);
|
$user = User::find($id);
|
||||||
|
|
||||||
$user->refresh();
|
if (! $user || ! hash_equals($hash, sha1($user->getEmailForVerification()))) {
|
||||||
|
return $this->redirectToFrontend('invalid');
|
||||||
|
}
|
||||||
|
|
||||||
return $this->authSession->createAuthResponse(
|
if ($user->hasVerifiedEmail()) {
|
||||||
$user,
|
return $this->redirectToFrontend('already');
|
||||||
'E-mel anda telah berjaya disahkan. Akaun anda sedang menunggu pengaktifan daripada pentadbir sistem.'
|
}
|
||||||
);
|
|
||||||
|
$user->markEmailAsVerified();
|
||||||
|
|
||||||
|
event(new Verified($user));
|
||||||
|
|
||||||
|
return $this->redirectToFrontend('success', $user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function resend(Request $request): JsonResponse
|
public function send(Request $request): JsonResponse
|
||||||
{
|
{
|
||||||
$validated = $request->validate([
|
$user = $request->user();
|
||||||
'email' => ['required', 'string', 'email'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$user = User::where('email', $validated['email'])->first();
|
if ($user->hasVerifiedEmail()) {
|
||||||
|
return response()->json([
|
||||||
if ($user && ! $user->hasVerifiedEmail()) {
|
'success' => true,
|
||||||
$this->otpService->send($user);
|
'message' => 'E-mel anda telah disahkan.',
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$user->sendEmailVerificationNotification();
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'message' => 'Jika e-mel wujud dan belum disahkan, kod OTP baharu telah dihantar.',
|
'message' => 'Pautan pengesahan e-mel telah dihantar.',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function redirectToFrontend(string $status, ?User $user = null): RedirectResponse
|
||||||
|
{
|
||||||
|
$baseUrl = rtrim(config('user.frontend_url'), '/');
|
||||||
|
$path = config('auth.verification.frontend_redirect_path', '/profile');
|
||||||
|
|
||||||
|
if ($user?->status === 'pending') {
|
||||||
|
$path = '/register?registered=success';
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect()->away("{$baseUrl}{$path}?verified={$status}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Modules\Auth\Services\PhoneVerificationOtpService;
|
||||||
|
use Modules\Auth\Transformers\UserResource;
|
||||||
|
|
||||||
|
class PhoneVerificationController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected PhoneVerificationOtpService $phoneVerificationOtpService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function send(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'phone_number' => $this->phoneVerificationOtpService->phoneNumberRules(),
|
||||||
|
], [
|
||||||
|
'phone_number.required' => 'Nombor telefon diperlukan.',
|
||||||
|
'phone_number.regex' => 'Format nombor telefon tidak sah.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->phoneVerificationOtpService->send($validated['phone_number']);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'message' => 'Kod OTP telah dihantar ke nombor telefon anda.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function verify(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$validated = $request->validate([
|
||||||
|
'phone_number' => $this->phoneVerificationOtpService->phoneNumberRules(),
|
||||||
|
'otp' => ['required', 'string', 'digits:6'],
|
||||||
|
], [
|
||||||
|
'phone_number.required' => 'Nombor telefon diperlukan.',
|
||||||
|
'phone_number.regex' => 'Format nombor telefon tidak sah.',
|
||||||
|
'otp.required' => 'Kod OTP diperlukan.',
|
||||||
|
'otp.digits' => 'Kod OTP mestilah 6 digit.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->phoneVerificationOtpService->verify(
|
||||||
|
$validated['phone_number'],
|
||||||
|
$validated['otp'],
|
||||||
|
);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'message' => 'Nombor telefon berjaya disahkan.',
|
||||||
|
'data' => [
|
||||||
|
'phone_number' => $result['phone_number'],
|
||||||
|
'verification_token' => $result['verification_token'],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendForAuthenticatedUser(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
$validated = $request->validate([
|
||||||
|
'phone_number' => $this->phoneVerificationOtpService->phoneNumberRules(),
|
||||||
|
], [
|
||||||
|
'phone_number.required' => 'Nombor telefon diperlukan.',
|
||||||
|
'phone_number.regex' => 'Format nombor telefon tidak sah.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->phoneVerificationOtpService->sendForUser($user, $validated['phone_number']);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'message' => 'Kod OTP telah dihantar ke nombor telefon anda.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function verifyForAuthenticatedUser(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$user = $request->user();
|
||||||
|
$wasVerified = (bool) $user->phone_verified_at;
|
||||||
|
|
||||||
|
$validated = $request->validate([
|
||||||
|
'phone_number' => $this->phoneVerificationOtpService->phoneNumberRules(),
|
||||||
|
'otp' => ['required', 'string', 'digits:6'],
|
||||||
|
], [
|
||||||
|
'phone_number.required' => 'Nombor telefon diperlukan.',
|
||||||
|
'phone_number.regex' => 'Format nombor telefon tidak sah.',
|
||||||
|
'otp.required' => 'Kod OTP diperlukan.',
|
||||||
|
'otp.digits' => 'Kod OTP mestilah 6 digit.',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$verifiedUser = $this->phoneVerificationOtpService->verifyForUser(
|
||||||
|
$user,
|
||||||
|
$validated['phone_number'],
|
||||||
|
$validated['otp'],
|
||||||
|
);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'message' => $wasVerified
|
||||||
|
? 'Nombor telefon berjaya dikemas kini.'
|
||||||
|
: 'Nombor telefon berjaya disahkan.',
|
||||||
|
'data' => new UserResource($verifiedUser),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Notifications;
|
||||||
|
|
||||||
|
use App\Notifications\Concerns\BuildsMailMessage;
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Notifications\Messages\MailMessage;
|
||||||
|
use Illuminate\Notifications\Notification;
|
||||||
|
use Illuminate\Support\Carbon;
|
||||||
|
use Illuminate\Support\Facades\URL;
|
||||||
|
use Modules\Auth\Entities\User;
|
||||||
|
|
||||||
|
class VerifyEmailNotification extends Notification
|
||||||
|
{
|
||||||
|
use BuildsMailMessage;
|
||||||
|
use Queueable;
|
||||||
|
|
||||||
|
public function via(object $notifiable): array
|
||||||
|
{
|
||||||
|
return ['mail'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function toMail(object $notifiable): MailMessage
|
||||||
|
{
|
||||||
|
$expireMinutes = (int) config('auth.verification.expire_minutes', 60);
|
||||||
|
|
||||||
|
return $this->mailMessage(
|
||||||
|
subject: 'Pengesahan E-mel - MyKOPKB',
|
||||||
|
view: 'auth::emails.verify-email',
|
||||||
|
data: [
|
||||||
|
'name' => $notifiable->name,
|
||||||
|
'verificationUrl' => $this->verificationUrl($notifiable),
|
||||||
|
'expireMinutes' => $expireMinutes,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function verificationUrl(User $notifiable): string
|
||||||
|
{
|
||||||
|
$expireMinutes = (int) config('auth.verification.expire_minutes', 60);
|
||||||
|
|
||||||
|
return URL::temporarySignedRoute(
|
||||||
|
'verification.verify',
|
||||||
|
Carbon::now()->addMinutes($expireMinutes),
|
||||||
|
[
|
||||||
|
'id' => $notifiable->getKey(),
|
||||||
|
'hash' => sha1($notifiable->getEmailForVerification()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,9 @@ use Modules\Auth\Actions\Fortify\CreateNewUser;
|
|||||||
use Modules\Auth\Actions\Fortify\ResetUserPassword;
|
use Modules\Auth\Actions\Fortify\ResetUserPassword;
|
||||||
use Modules\Auth\Actions\Fortify\UpdateUserPassword;
|
use Modules\Auth\Actions\Fortify\UpdateUserPassword;
|
||||||
use Modules\Auth\Actions\Fortify\UpdateUserProfileInformation;
|
use Modules\Auth\Actions\Fortify\UpdateUserProfileInformation;
|
||||||
|
use Modules\Auth\Contracts\SmsSender;
|
||||||
|
use Modules\Auth\Services\LogSmsSender;
|
||||||
|
use Modules\Auth\Services\OneWaySmsSender;
|
||||||
use Nwidart\Modules\Traits\PathNamespace;
|
use Nwidart\Modules\Traits\PathNamespace;
|
||||||
use RecursiveDirectoryIterator;
|
use RecursiveDirectoryIterator;
|
||||||
use RecursiveIteratorIterator;
|
use RecursiveIteratorIterator;
|
||||||
@@ -42,6 +45,13 @@ class AuthServiceProvider extends ServiceProvider
|
|||||||
{
|
{
|
||||||
$this->app->register(EventServiceProvider::class);
|
$this->app->register(EventServiceProvider::class);
|
||||||
$this->app->register(RouteServiceProvider::class);
|
$this->app->register(RouteServiceProvider::class);
|
||||||
|
|
||||||
|
$this->app->bind(SmsSender::class, function () {
|
||||||
|
return match (config('onewaysms.driver')) {
|
||||||
|
'log' => $this->app->make(LogSmsSender::class),
|
||||||
|
default => $this->app->make(OneWaySmsSender::class),
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -3,18 +3,23 @@
|
|||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Modules\Auth\Http\Controllers\EmailVerificationController;
|
use Modules\Auth\Http\Controllers\EmailVerificationController;
|
||||||
use Modules\Auth\Http\Controllers\PasswordResetController;
|
use Modules\Auth\Http\Controllers\PasswordResetController;
|
||||||
|
use Modules\Auth\Http\Controllers\PhoneVerificationController;
|
||||||
use Modules\Auth\Http\Controllers\SessionController;
|
use Modules\Auth\Http\Controllers\SessionController;
|
||||||
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
|
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
|
||||||
use Laravel\Fortify\Http\Controllers\RegisteredUserController;
|
use Laravel\Fortify\Http\Controllers\RegisteredUserController;
|
||||||
|
|
||||||
// Auth
|
// Auth
|
||||||
|
Route::post('/phone-verification/send', [PhoneVerificationController::class, 'send'])
|
||||||
|
->middleware('throttle:phone-verification-send');
|
||||||
|
Route::post('/phone-verification/verify', [PhoneVerificationController::class, 'verify'])
|
||||||
|
->middleware('throttle:phone-verification-verify');
|
||||||
|
|
||||||
Route::post('/register', [RegisteredUserController::class, 'store']);
|
Route::post('/register', [RegisteredUserController::class, 'store']);
|
||||||
Route::post('/login', [AuthenticatedSessionController::class, 'store'])->middleware('block.api.tools');
|
Route::post('/login', [AuthenticatedSessionController::class, 'store'])->middleware('block.api.tools');
|
||||||
|
|
||||||
Route::post('/verify-email', [EmailVerificationController::class, 'verify'])
|
Route::get('/email/verify/{id}/{hash}', [EmailVerificationController::class, 'verify'])
|
||||||
->middleware('throttle:email-verification');
|
->middleware('throttle:email-verification')
|
||||||
Route::post('/verify-email/resend', [EmailVerificationController::class, 'resend'])
|
->name('verification.verify');
|
||||||
->middleware('throttle:email-verification-resend');
|
|
||||||
|
|
||||||
Route::post('/forgot-password', [PasswordResetController::class, 'requestOtp'])
|
Route::post('/forgot-password', [PasswordResetController::class, 'requestOtp'])
|
||||||
->middleware('throttle:password-reset-request');
|
->middleware('throttle:password-reset-request');
|
||||||
@@ -30,4 +35,14 @@ Route::middleware(['auth:sanctum'])->prefix('v1')->group(function () {
|
|||||||
|
|
||||||
// logout
|
// logout
|
||||||
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy']);
|
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy']);
|
||||||
|
|
||||||
|
// optional email verification (post-login)
|
||||||
|
Route::post('/email/verification-notification', [EmailVerificationController::class, 'send'])
|
||||||
|
->middleware('throttle:email-verification-resend');
|
||||||
|
|
||||||
|
// optional phone verification (post-login)
|
||||||
|
Route::post('/phone-verification/send', [PhoneVerificationController::class, 'sendForAuthenticatedUser'])
|
||||||
|
->middleware('throttle:phone-verification-send');
|
||||||
|
Route::post('/phone-verification/verify', [PhoneVerificationController::class, 'verifyForAuthenticatedUser'])
|
||||||
|
->middleware('throttle:phone-verification-verify');
|
||||||
});
|
});
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Modules\Auth\Services;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Hash;
|
|
||||||
use Illuminate\Validation\ValidationException;
|
|
||||||
use Modules\Auth\Entities\EmailVerificationOtp;
|
|
||||||
use Modules\Auth\Entities\User;
|
|
||||||
use Modules\Auth\Emails\EmailVerificationOtpEmail;
|
|
||||||
|
|
||||||
class EmailVerificationOtpService
|
|
||||||
{
|
|
||||||
public function send(User $user): void
|
|
||||||
{
|
|
||||||
if ($user->hasVerifiedEmail()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$otp = $this->generateOtp();
|
|
||||||
|
|
||||||
EmailVerificationOtp::query()
|
|
||||||
->where('user_id', $user->id)
|
|
||||||
->delete();
|
|
||||||
|
|
||||||
EmailVerificationOtp::create([
|
|
||||||
'user_id' => $user->id,
|
|
||||||
'code' => Hash::make($otp),
|
|
||||||
'expires_at' => now()->addMinutes($this->expiryMinutes()),
|
|
||||||
'attempts' => 0,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$user->notify(new EmailVerificationOtpEmail($otp));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function verify(User $user, string $otp): void
|
|
||||||
{
|
|
||||||
if ($user->hasVerifiedEmail()) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'email' => ['E-mel anda telah disahkan.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$record = EmailVerificationOtp::query()
|
|
||||||
->where('user_id', $user->id)
|
|
||||||
->latest()
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (! $record) {
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'otp' => ['Kod OTP tidak dijumpai. Sila minta kod baharu.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($record->isExpired()) {
|
|
||||||
$record->delete();
|
|
||||||
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'otp' => ['Kod OTP telah tamat tempoh. Sila minta kod baharu.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($record->hasExceededMaxAttempts()) {
|
|
||||||
$record->delete();
|
|
||||||
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'otp' => ['Terlalu banyak percubaan. Sila minta kod baharu.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (! Hash::check($otp, $record->code)) {
|
|
||||||
$record->increment('attempts');
|
|
||||||
|
|
||||||
if ($record->fresh()->hasExceededMaxAttempts()) {
|
|
||||||
$record->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
throw ValidationException::withMessages([
|
|
||||||
'otp' => ['Kod OTP tidak sah.'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$user->forceFill(['email_verified_at' => now()])->save();
|
|
||||||
|
|
||||||
EmailVerificationOtp::query()
|
|
||||||
->where('user_id', $user->id)
|
|
||||||
->delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function generateOtp(): string
|
|
||||||
{
|
|
||||||
return str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function expiryMinutes(): int
|
|
||||||
{
|
|
||||||
return (int) config('auth.email_verification.expiry_minutes', 10);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Modules\Auth\Contracts\SmsSender;
|
||||||
|
|
||||||
|
class LogSmsSender implements SmsSender
|
||||||
|
{
|
||||||
|
public function send(string $phoneNumber, string $message): void
|
||||||
|
{
|
||||||
|
Log::info('SMS sent (log driver)', [
|
||||||
|
'phone_number' => $phoneNumber,
|
||||||
|
'message' => $message,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Http;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Modules\Auth\Contracts\SmsSender;
|
||||||
|
use RuntimeException;
|
||||||
|
|
||||||
|
class OneWaySmsSender implements SmsSender
|
||||||
|
{
|
||||||
|
public function send(string $phoneNumber, string $message): void
|
||||||
|
{
|
||||||
|
$baseUrl = (string) config('onewaysms.base_url');
|
||||||
|
$username = (string) config('onewaysms.api_username');
|
||||||
|
$password = (string) config('onewaysms.api_password');
|
||||||
|
$senderId = (string) config('onewaysms.sender_id');
|
||||||
|
|
||||||
|
if ($baseUrl === '' || $username === '' || $password === '' || $senderId === '') {
|
||||||
|
throw new RuntimeException('OneWaySMS credentials are not configured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$mobileNo = $this->toInternationalMobileNumber($phoneNumber);
|
||||||
|
|
||||||
|
$response = Http::timeout((int) config('http.timeout', 30))
|
||||||
|
->connectTimeout((int) config('http.connect_timeout', 10))
|
||||||
|
->get($baseUrl, [
|
||||||
|
'apiusername' => $username,
|
||||||
|
'apipassword' => $password,
|
||||||
|
'senderid' => $senderId,
|
||||||
|
'mobileno' => $mobileNo,
|
||||||
|
'message' => $message,
|
||||||
|
'languagetype' => 1,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (! $response->successful()) {
|
||||||
|
Log::error('OneWaySMS HTTP request failed', [
|
||||||
|
'status' => $response->status(),
|
||||||
|
'body' => $response->body(),
|
||||||
|
'phone_number' => $mobileNo,
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw new RuntimeException('Failed to send SMS via OneWaySMS.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$mtId = trim($response->body());
|
||||||
|
|
||||||
|
// Positive MT ID = success; zero/negative = gateway error codes.
|
||||||
|
if (! is_numeric($mtId) || (int) $mtId <= 0) {
|
||||||
|
Log::error('OneWaySMS gateway rejected SMS', [
|
||||||
|
'mt_id' => $mtId,
|
||||||
|
'phone_number' => $mobileNo,
|
||||||
|
]);
|
||||||
|
|
||||||
|
throw new RuntimeException('OneWaySMS gateway rejected the SMS request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
Log::info('OneWaySMS sent successfully', [
|
||||||
|
'mt_id' => $mtId,
|
||||||
|
'phone_number' => $mobileNo,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function toInternationalMobileNumber(string $phoneNumber): string
|
||||||
|
{
|
||||||
|
$phoneNumber = preg_replace('/[\s\-]/', '', trim($phoneNumber)) ?? '';
|
||||||
|
|
||||||
|
if (str_starts_with($phoneNumber, '+')) {
|
||||||
|
$phoneNumber = substr($phoneNumber, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (str_starts_with($phoneNumber, '0')) {
|
||||||
|
$phoneNumber = '60'.substr($phoneNumber, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phoneNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Auth\Services;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Modules\Auth\Contracts\SmsSender;
|
||||||
|
use Modules\Auth\Entities\PhoneVerificationOtp;
|
||||||
|
use Modules\Auth\Entities\User;
|
||||||
|
|
||||||
|
class PhoneVerificationOtpService
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected SmsSender $smsSender,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function send(string $phoneNumber): void
|
||||||
|
{
|
||||||
|
$phoneNumber = $this->normalizePhoneNumber($phoneNumber);
|
||||||
|
|
||||||
|
if ($this->phoneNumberBelongsToAnotherUser($phoneNumber)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'phone_number' => ['Nombor telefon ini telah didaftarkan.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->dispatchOtp($phoneNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendForUser(User $user, string $phoneNumber): void
|
||||||
|
{
|
||||||
|
$phoneNumber = $this->normalizePhoneNumber($phoneNumber);
|
||||||
|
|
||||||
|
$this->assertPhoneNumberAvailableForUser($user, $phoneNumber);
|
||||||
|
|
||||||
|
if ($user->phone_verified_at && $user->phone_number === $phoneNumber) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'phone_number' => ['Nombor telefon ini sama dengan nombor sedia ada.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->dispatchOtp($phoneNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function verifyForUser(User $user, string $phoneNumber, string $otp): User
|
||||||
|
{
|
||||||
|
$phoneNumber = $this->normalizePhoneNumber($phoneNumber);
|
||||||
|
|
||||||
|
$this->assertPhoneNumberAvailableForUser($user, $phoneNumber);
|
||||||
|
|
||||||
|
$record = $this->validateOtpRecord($phoneNumber, $otp);
|
||||||
|
$record->delete();
|
||||||
|
|
||||||
|
$user->forceFill([
|
||||||
|
'phone_number' => $phoneNumber,
|
||||||
|
'phone_verified_at' => now(),
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return $user->fresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{verification_token: string, phone_number: string}
|
||||||
|
*/
|
||||||
|
public function verify(string $phoneNumber, string $otp): array
|
||||||
|
{
|
||||||
|
$phoneNumber = $this->normalizePhoneNumber($phoneNumber);
|
||||||
|
|
||||||
|
$record = $this->validateOtpRecord($phoneNumber, $otp);
|
||||||
|
|
||||||
|
$verificationToken = Str::random(64);
|
||||||
|
|
||||||
|
$record->forceFill([
|
||||||
|
'verified_at' => now(),
|
||||||
|
'verification_token' => Hash::make($verificationToken),
|
||||||
|
'verification_token_expires_at' => now()->addMinutes($this->tokenExpiryMinutes()),
|
||||||
|
])->save();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'verification_token' => $verificationToken,
|
||||||
|
'phone_number' => $phoneNumber,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function consumeRegistrationToken(string $phoneNumber, string $verificationToken): void
|
||||||
|
{
|
||||||
|
$phoneNumber = $this->normalizePhoneNumber($phoneNumber);
|
||||||
|
|
||||||
|
$record = PhoneVerificationOtp::query()
|
||||||
|
->where('phone_number', $phoneNumber)
|
||||||
|
->whereNotNull('verified_at')
|
||||||
|
->latest()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $record || $record->isVerificationTokenExpired()) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'phone_verification_token' => ['Pengesahan nombor telefon tidak sah atau telah tamat tempoh. Sila sahkan semula.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! Hash::check($verificationToken, (string) $record->verification_token)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'phone_verification_token' => ['Pengesahan nombor telefon tidak sah atau telah tamat tempoh. Sila sahkan semula.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$record->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function dispatchOtp(string $phoneNumber): void
|
||||||
|
{
|
||||||
|
$otp = $this->generateOtp();
|
||||||
|
|
||||||
|
PhoneVerificationOtp::query()
|
||||||
|
->where('phone_number', $phoneNumber)
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
PhoneVerificationOtp::create([
|
||||||
|
'phone_number' => $phoneNumber,
|
||||||
|
'code' => Hash::make($otp),
|
||||||
|
'expires_at' => now()->addMinutes($this->otpExpiryMinutes()),
|
||||||
|
'attempts' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->smsSender->send(
|
||||||
|
$phoneNumber,
|
||||||
|
$this->buildOtpMessage($otp),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function validateOtpRecord(string $phoneNumber, string $otp): PhoneVerificationOtp
|
||||||
|
{
|
||||||
|
$record = PhoneVerificationOtp::query()
|
||||||
|
->where('phone_number', $phoneNumber)
|
||||||
|
->latest()
|
||||||
|
->first();
|
||||||
|
|
||||||
|
if (! $record) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'otp' => ['Kod OTP tidak dijumpai. Sila minta kod baharu.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($record->isExpired()) {
|
||||||
|
$record->delete();
|
||||||
|
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'otp' => ['Kod OTP telah tamat tempoh. Sila minta kod baharu.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($record->hasExceededMaxAttempts()) {
|
||||||
|
$record->delete();
|
||||||
|
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'otp' => ['Terlalu banyak percubaan. Sila minta kod baharu.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! Hash::check($otp, $record->code)) {
|
||||||
|
$record->increment('attempts');
|
||||||
|
|
||||||
|
if ($record->fresh()->hasExceededMaxAttempts()) {
|
||||||
|
$record->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'otp' => ['Kod OTP tidak sah.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function assertPhoneNumberAvailableForUser(User $user, string $phoneNumber): void
|
||||||
|
{
|
||||||
|
if ($this->phoneNumberBelongsToAnotherUser($phoneNumber, $user->id)) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'phone_number' => ['Nombor telefon ini telah digunakan oleh akaun lain.'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function phoneNumberBelongsToAnotherUser(string $phoneNumber, ?string $exceptUserId = null): bool
|
||||||
|
{
|
||||||
|
return User::query()
|
||||||
|
->where('phone_number', $phoneNumber)
|
||||||
|
->when($exceptUserId, fn ($query) => $query->where('id', '!=', $exceptUserId))
|
||||||
|
->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function normalizePhoneNumber(string $phoneNumber): string
|
||||||
|
{
|
||||||
|
$phoneNumber = preg_replace('/[\s\-]/', '', trim($phoneNumber)) ?? '';
|
||||||
|
|
||||||
|
if (str_starts_with($phoneNumber, '+60')) {
|
||||||
|
$phoneNumber = '0'.substr($phoneNumber, 3);
|
||||||
|
} elseif (str_starts_with($phoneNumber, '60') && strlen($phoneNumber) > 10) {
|
||||||
|
$phoneNumber = '0'.substr($phoneNumber, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $phoneNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function phoneNumberRules(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'required',
|
||||||
|
'string',
|
||||||
|
'max:20',
|
||||||
|
'regex:/^(\+?60|0)1[0-9]{8,9}$/',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function generateOtp(): string
|
||||||
|
{
|
||||||
|
return str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function buildOtpMessage(string $otp): string
|
||||||
|
{
|
||||||
|
$template = (string) config('auth.phone_verification.message');
|
||||||
|
|
||||||
|
return str_replace(
|
||||||
|
[':otp', ':minutes'],
|
||||||
|
[$otp, (string) $this->otpExpiryMinutes()],
|
||||||
|
$template,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function otpExpiryMinutes(): int
|
||||||
|
{
|
||||||
|
return (int) config('auth.phone_verification.otp_expiry_minutes', 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tokenExpiryMinutes(): int
|
||||||
|
{
|
||||||
|
return (int) config('auth.phone_verification.token_expiry_minutes', 30);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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')),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -26,6 +26,7 @@ class UserResource extends JsonResource
|
|||||||
'ic_number' => $this->ic_number,
|
'ic_number' => $this->ic_number,
|
||||||
'position' => $this->position,
|
'position' => $this->position,
|
||||||
'phone_number' => $this->phone_number,
|
'phone_number' => $this->phone_number,
|
||||||
|
'phone_verified_at' => $this->phone_verified_at,
|
||||||
'image_url' => $this->image_url ? Storage::disk('public')->url($this->image_url) : null,
|
'image_url' => $this->image_url ? Storage::disk('public')->url($this->image_url) : null,
|
||||||
'status' => $this->status,
|
'status' => $this->status,
|
||||||
'two_factor_secret' => $this->two_factor_secret,
|
'two_factor_secret' => $this->two_factor_secret,
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
@component('mail::message')
|
|
||||||
@include('emails.partials.header')
|
|
||||||
|
|
||||||
# Pengesahan E-mel
|
|
||||||
|
|
||||||
Assalamualaikum **{{ $name }}**,
|
|
||||||
|
|
||||||
Terima kasih kerana mendaftar. Gunakan kod OTP di bawah untuk mengesahkan alamat e-mel anda.
|
|
||||||
|
|
||||||
@component('mail::panel')
|
|
||||||
<div style="text-align: center; font-size: 28px; font-weight: bold; letter-spacing: 6px;">
|
|
||||||
{{ $otp }}
|
|
||||||
</div>
|
|
||||||
@endcomponent
|
|
||||||
|
|
||||||
Kod ini akan tamat tempoh dalam **{{ $minutes }} minit**.
|
|
||||||
|
|
||||||
Jika anda tidak membuat pendaftaran ini, abaikan e-mel ini.
|
|
||||||
|
|
||||||
@include('emails.partials.footer')
|
|
||||||
@endcomponent
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
@component('mail::message')
|
||||||
|
@include('emails.partials.header')
|
||||||
|
|
||||||
|
# Pengesahan E-mel
|
||||||
|
|
||||||
|
Assalamualaikum **{{ $name }}**,
|
||||||
|
|
||||||
|
Terima kasih kerana mendaftar dengan MyKOPKB. Sila sahkan alamat e-mel anda dengan mengklik butang di bawah.
|
||||||
|
|
||||||
|
@component('mail::button', ['url' => $verificationUrl])
|
||||||
|
Sahkan E-mel
|
||||||
|
@endcomponent
|
||||||
|
|
||||||
|
Pautan ini akan tamat tempoh dalam **{{ $expireMinutes }} minit**.
|
||||||
|
|
||||||
|
Jika anda tidak membuat permintaan ini, abaikan e-mel ini.
|
||||||
|
|
||||||
|
@include('emails.partials.footer')
|
||||||
|
@endcomponent
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -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'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
@@ -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(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "ExternalSystem",
|
||||||
|
"alias": "externalsystem",
|
||||||
|
"description": "",
|
||||||
|
"keywords": [],
|
||||||
|
"priority": 0,
|
||||||
|
"providers": [
|
||||||
|
"Modules\\ExternalSystem\\Providers\\ExternalSystemServiceProvider"
|
||||||
|
],
|
||||||
|
"files": []
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'name' => 'Feedback',
|
||||||
|
];
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
// Create ENUM types for PostgreSQL
|
||||||
|
DB::statement("CREATE TYPE feedback_type_enum AS ENUM ('bug', 'feature_request', 'general_feedback', 'ui_issue', 'performance_issue')");
|
||||||
|
DB::statement("CREATE TYPE feedback_priority_enum AS ENUM ('low', 'medium', 'high', 'critical')");
|
||||||
|
DB::statement("CREATE TYPE feedback_status_enum AS ENUM ('open', 'in_progress', 'resolved', 'closed', 'rejected')");
|
||||||
|
|
||||||
|
Schema::create('feedback', function (Blueprint $table) {
|
||||||
|
$table->uuid('id')->primary();
|
||||||
|
$table->foreignUuid('user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->string('title');
|
||||||
|
$table->text('description');
|
||||||
|
$table->string('page_url')->nullable(); // URL where the issue occurred
|
||||||
|
$table->json('browser_info')->nullable(); // Browser, OS, screen resolution etc.
|
||||||
|
$table->text('steps_to_reproduce')->nullable(); // Steps to reproduce the issue
|
||||||
|
$table->text('expected_behavior')->nullable(); // What should happen
|
||||||
|
$table->text('actual_behavior')->nullable(); // What actually happened
|
||||||
|
$table->text('additional_notes')->nullable(); // Any additional information
|
||||||
|
$table->foreignUuid('assigned_to')->nullable()->constrained('users')->nullOnDelete();
|
||||||
|
$table->text('admin_notes')->nullable(); // Internal notes for admins
|
||||||
|
$table->timestamp('resolved_at')->nullable();
|
||||||
|
$table->timestamps();
|
||||||
|
$table->softDeletes();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add ENUM columns
|
||||||
|
DB::statement("ALTER TABLE feedback ADD COLUMN type feedback_type_enum NOT NULL DEFAULT 'general_feedback'");
|
||||||
|
DB::statement("ALTER TABLE feedback ADD COLUMN priority feedback_priority_enum NOT NULL DEFAULT 'medium'");
|
||||||
|
DB::statement("ALTER TABLE feedback ADD COLUMN status feedback_status_enum NOT NULL DEFAULT 'open'");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('feedback');
|
||||||
|
DB::statement("DROP TYPE IF EXISTS feedback_type_enum");
|
||||||
|
DB::statement("DROP TYPE IF EXISTS feedback_priority_enum");
|
||||||
|
DB::statement("DROP TYPE IF EXISTS feedback_status_enum");
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Database\Seeders;
|
||||||
|
|
||||||
|
use Illuminate\Database\Seeder;
|
||||||
|
|
||||||
|
class FeedbackDatabaseSeeder extends Seeder
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the database seeds.
|
||||||
|
*/
|
||||||
|
public function run(): void
|
||||||
|
{
|
||||||
|
// $this->call([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Entities;
|
||||||
|
|
||||||
|
use App\Traits\HasDocuments;
|
||||||
|
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||||||
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
use Spatie\Activitylog\Traits\LogsActivity;
|
||||||
|
use Spatie\Activitylog\LogOptions;
|
||||||
|
use Modules\Auth\Entities\User;
|
||||||
|
|
||||||
|
class Feedback extends Model
|
||||||
|
{
|
||||||
|
use HasDocuments, HasUuids, SoftDeletes, LogsActivity;
|
||||||
|
|
||||||
|
public const IMAGE_DOCUMENT_TYPE = 'image';
|
||||||
|
|
||||||
|
public const VIDEO_DOCUMENT_TYPE = 'video';
|
||||||
|
|
||||||
|
protected $table = 'feedback';
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'user_id',
|
||||||
|
'type',
|
||||||
|
'title',
|
||||||
|
'description',
|
||||||
|
'page_url',
|
||||||
|
'browser_info',
|
||||||
|
'steps_to_reproduce',
|
||||||
|
'expected_behavior',
|
||||||
|
'actual_behavior',
|
||||||
|
'additional_notes',
|
||||||
|
'priority',
|
||||||
|
'status',
|
||||||
|
'assigned_to',
|
||||||
|
'admin_notes',
|
||||||
|
'resolved_at',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'browser_info' => 'array',
|
||||||
|
'resolved_at' => 'datetime',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function getActivitylogOptions(): LogOptions
|
||||||
|
{
|
||||||
|
return LogOptions::defaults()
|
||||||
|
->logAll()
|
||||||
|
->logOnlyDirty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the user who submitted the feedback
|
||||||
|
*/
|
||||||
|
public function user()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'user_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the admin assigned to handle this feedback
|
||||||
|
*/
|
||||||
|
public function assignedUser()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, 'assigned_to');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function images(): MorphMany
|
||||||
|
{
|
||||||
|
return $this->documents()->where('type', self::IMAGE_DOCUMENT_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function videos(): MorphMany
|
||||||
|
{
|
||||||
|
return $this->documents()->where('type', self::VIDEO_DOCUMENT_TYPE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope for filtering by type
|
||||||
|
*/
|
||||||
|
public function scopeOfType($query, $type)
|
||||||
|
{
|
||||||
|
return $query->where('type', $type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope for filtering by status
|
||||||
|
*/
|
||||||
|
public function scopeOfStatus($query, $status)
|
||||||
|
{
|
||||||
|
return $query->where('status', $status);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope for filtering by priority
|
||||||
|
*/
|
||||||
|
public function scopeOfPriority($query, $priority)
|
||||||
|
{
|
||||||
|
return $query->where('priority', $priority);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope for open feedback
|
||||||
|
*/
|
||||||
|
public function scopeOpen($query)
|
||||||
|
{
|
||||||
|
return $query->whereIn('status', ['open', 'in_progress']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope for resolved feedback
|
||||||
|
*/
|
||||||
|
public function scopeResolved($query)
|
||||||
|
{
|
||||||
|
return $query->whereIn('status', ['resolved', 'closed']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Http\Controllers\BaseCrudController;
|
||||||
|
use App\Models\Document;
|
||||||
|
use Exception;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
use Modules\Feedback\Http\Requests\FeedbackRequest;
|
||||||
|
use Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface;
|
||||||
|
use Modules\Feedback\Transformers\FeedbackResource;
|
||||||
|
use Modules\Feedback\Notifications\FeedbackNotification;
|
||||||
|
use Modules\Auth\Entities\User;
|
||||||
|
use Laravel\Sanctum\PersonalAccessToken;
|
||||||
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
|
|
||||||
|
class FeedbackController extends BaseCrudController
|
||||||
|
{
|
||||||
|
protected $modelClass = Feedback::class;
|
||||||
|
protected $resourceClass = FeedbackResource::class;
|
||||||
|
protected $requestClass = FeedbackRequest::class;
|
||||||
|
protected $resourceName = 'maklum balas';
|
||||||
|
protected $resourceNamePlural = 'maklum balas';
|
||||||
|
|
||||||
|
public function __construct(FeedbackRepositoryInterface $repository)
|
||||||
|
{
|
||||||
|
parent::__construct($repository);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Override getIndexData to handle filters
|
||||||
|
*/
|
||||||
|
protected function getIndexData(Request $request, int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc')
|
||||||
|
{
|
||||||
|
// Extract filter parameters from request
|
||||||
|
$filters = [
|
||||||
|
'type' => $request->get('type'),
|
||||||
|
'status' => $request->get('status'),
|
||||||
|
'priority' => $request->get('priority'),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Always try paginated methods first when perPage is specified
|
||||||
|
if ($perPage > 0) {
|
||||||
|
if (method_exists($this->repository, 'getAllWithRelationsPaginated')) {
|
||||||
|
return $this->repository->getAllWithRelationsPaginated($perPage, $search, $sortBy, $sortOrder, $filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (method_exists($this->repository, 'getAllPaginated')) {
|
||||||
|
return $this->repository->getAllPaginated($perPage, $search, $sortBy, $sortOrder, $filters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to non-paginated methods
|
||||||
|
if (method_exists($this->repository, 'getAllWithRelations')) {
|
||||||
|
return $this->repository->getAllWithRelations($search, $sortBy, $sortOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->repository->all($search, $sortBy, $sortOrder);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store a newly created resource in storage (public access)
|
||||||
|
*/
|
||||||
|
public function store(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
// Skip authorization for public feedback submission
|
||||||
|
try {
|
||||||
|
$validated = $this->validateRequest($request);
|
||||||
|
$data = $this->prepareStoreData($validated);
|
||||||
|
|
||||||
|
$item = $this->repository->create($data);
|
||||||
|
|
||||||
|
$this->uploadAttachments($item, $request);
|
||||||
|
|
||||||
|
// Load relationships
|
||||||
|
$item->load(['user', 'documents']);
|
||||||
|
|
||||||
|
// Send notification to admins
|
||||||
|
$this->notifyAdminsForNewFeedback($item);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'data' => new $this->resourceClass($item),
|
||||||
|
'message' => 'Maklum balas berjaya dihantar. Terima kasih!',
|
||||||
|
], 201);
|
||||||
|
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::error("Error creating {$this->resourceName}: ".$e->getMessage());
|
||||||
|
|
||||||
|
return $this->errorResponse($this->getErrorMessage('store').': '.$e->getMessage(), 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare data for store method
|
||||||
|
*/
|
||||||
|
protected function prepareStoreData(array $validated): array
|
||||||
|
{
|
||||||
|
$data = $validated;
|
||||||
|
|
||||||
|
// Check if user is authenticated by looking for the Authorization header
|
||||||
|
$authHeader = request()->header('Authorization');
|
||||||
|
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
|
||||||
|
// Try to authenticate the user manually
|
||||||
|
$token = str_replace('Bearer ', '', $authHeader);
|
||||||
|
$personalAccessToken = PersonalAccessToken::findToken($token);
|
||||||
|
|
||||||
|
if ($personalAccessToken) {
|
||||||
|
$data['user_id'] = $personalAccessToken->tokenable_id;
|
||||||
|
} else {
|
||||||
|
$data['user_id'] = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// User is not authenticated
|
||||||
|
$data['user_id'] = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data['browser_info'] = $this->getBrowserInfo(request());
|
||||||
|
|
||||||
|
unset($data['images'], $data['videos']);
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upload image and video attachments via HasDocuments.
|
||||||
|
*/
|
||||||
|
protected function uploadAttachments(Feedback $feedback, Request $request): void
|
||||||
|
{
|
||||||
|
if ($request->hasFile('images')) {
|
||||||
|
foreach ($request->file('images') as $image) {
|
||||||
|
$feedback->uploadDocument($image, Feedback::IMAGE_DOCUMENT_TYPE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->hasFile('videos')) {
|
||||||
|
foreach ($request->file('videos') as $video) {
|
||||||
|
$feedback->uploadDocument($video, Feedback::VIDEO_DOCUMENT_TYPE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare data for update method
|
||||||
|
*/
|
||||||
|
protected function prepareUpdateData(array $validated, $feedback): array
|
||||||
|
{
|
||||||
|
$data = $validated;
|
||||||
|
|
||||||
|
unset($data['images'], $data['videos']);
|
||||||
|
|
||||||
|
// Set resolved_at timestamp when status changes to resolved
|
||||||
|
if (isset($data['status']) && $data['status'] === 'resolved') {
|
||||||
|
$data['resolved_at'] = now();
|
||||||
|
} elseif (isset($data['status']) && $data['status'] !== 'resolved') {
|
||||||
|
$data['resolved_at'] = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the specified resource in storage.
|
||||||
|
*/
|
||||||
|
public function update(Request $request, string $id): JsonResponse
|
||||||
|
{
|
||||||
|
$this->authorize('update', $this->modelClass);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$item = $this->repository->findById($id);
|
||||||
|
|
||||||
|
if (! $item) {
|
||||||
|
return $this->errorResponse($this->getNotFoundMessage(), 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
$validated = $this->validateRequest($request);
|
||||||
|
$data = $this->prepareUpdateData($validated, $item);
|
||||||
|
|
||||||
|
$item->update($data);
|
||||||
|
$item->load(['user', 'assignedUser', 'documents']);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'data' => new $this->resourceClass($item),
|
||||||
|
'message' => $this->getSuccessMessage('update'),
|
||||||
|
]);
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::error("Error updating {$this->resourceName}: ".$e->getMessage());
|
||||||
|
|
||||||
|
return $this->errorResponse($this->getErrorMessage('update').': '.$e->getMessage(), 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load relations for show method
|
||||||
|
*/
|
||||||
|
protected function loadShowRelations($item)
|
||||||
|
{
|
||||||
|
return $item->load(['user', 'assignedUser', 'documents']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check dependencies before deletion
|
||||||
|
*/
|
||||||
|
protected function checkDependencies($feedback): ?\Illuminate\Http\JsonResponse
|
||||||
|
{
|
||||||
|
foreach ($feedback->documents as $document) {
|
||||||
|
$feedback->deleteDocument($document->id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stream a feedback attachment inline (image/video preview).
|
||||||
|
*/
|
||||||
|
public function serveDocument(string $id, string $documentId): BinaryFileResponse
|
||||||
|
{
|
||||||
|
$this->authorize('view', $this->modelClass);
|
||||||
|
|
||||||
|
$feedback = Feedback::findOrFail($id);
|
||||||
|
$document = $feedback->documents()->findOrFail($documentId);
|
||||||
|
|
||||||
|
$disk = Storage::disk(Document::STORAGE_DISK);
|
||||||
|
|
||||||
|
if (! $disk->exists($document->path)) {
|
||||||
|
abort(404, 'File not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->file($disk->path($document->path), [
|
||||||
|
'Content-Type' => $document->mime_type ?? 'application/octet-stream',
|
||||||
|
'Content-Disposition' => 'inline; filename="'.$document->name.'"',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get feedback statistics
|
||||||
|
*/
|
||||||
|
public function statistics(): JsonResponse
|
||||||
|
{
|
||||||
|
$stats = [
|
||||||
|
'total' => Feedback::count(),
|
||||||
|
'open' => Feedback::open()->count(),
|
||||||
|
'resolved' => Feedback::resolved()->count(),
|
||||||
|
'by_type' => Feedback::selectRaw('type, COUNT(*) as count')
|
||||||
|
->groupBy('type')
|
||||||
|
->pluck('count', 'type'),
|
||||||
|
'by_priority' => Feedback::selectRaw('priority, COUNT(*) as count')
|
||||||
|
->groupBy('priority')
|
||||||
|
->pluck('count', 'priority'),
|
||||||
|
'by_status' => Feedback::selectRaw('status, COUNT(*) as count')
|
||||||
|
->groupBy('status')
|
||||||
|
->pluck('count', 'status'),
|
||||||
|
];
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'data' => $stats
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user's own feedback
|
||||||
|
*/
|
||||||
|
public function myFeedback(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$query = Feedback::where('user_id', auth()->id())
|
||||||
|
->with(['assignedUser', 'documents'])
|
||||||
|
->orderBy('created_at', 'desc');
|
||||||
|
|
||||||
|
// Apply filters
|
||||||
|
if ($request->has('status') && $request->status) {
|
||||||
|
$query->ofStatus($request->status);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->has('type') && $request->type) {
|
||||||
|
$query->ofType($request->type);
|
||||||
|
}
|
||||||
|
|
||||||
|
$perPage = $request->get('per_page', 15);
|
||||||
|
$feedback = $query->paginate($perPage);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'success' => true,
|
||||||
|
'data' => FeedbackResource::collection($feedback->items()),
|
||||||
|
'meta' => [
|
||||||
|
'current_page' => $feedback->currentPage(),
|
||||||
|
'last_page' => $feedback->lastPage(),
|
||||||
|
'per_page' => $feedback->perPage(),
|
||||||
|
'total' => $feedback->total(),
|
||||||
|
]
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get browser information from request
|
||||||
|
*/
|
||||||
|
private function getBrowserInfo(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user_agent' => $request->userAgent(),
|
||||||
|
'ip_address' => $request->ip(),
|
||||||
|
'referer' => $request->header('referer'),
|
||||||
|
'accept_language' => $request->header('accept-language'),
|
||||||
|
'screen_resolution' => $request->input('screen_resolution'),
|
||||||
|
'viewport_size' => $request->input('viewport_size'),
|
||||||
|
'timezone' => $request->input('timezone'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify admins about new feedback submission
|
||||||
|
*/
|
||||||
|
private function notifyAdminsForNewFeedback(Feedback $feedback): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$adminRoles = ['PENTADBIR', 'PS 2 KJC', 'PS 2 ALAT'];
|
||||||
|
|
||||||
|
// Get users with specific roles plus admins (PENTADBIR and DEVELOPER)
|
||||||
|
$adminUsers = $this->getUsersWithRolesAndAdmins($adminRoles);
|
||||||
|
|
||||||
|
$sender = auth()->user() ?? $feedback->user; // Use current user as sender, or feedback submitter if no auth
|
||||||
|
|
||||||
|
foreach ($adminUsers as $admin) {
|
||||||
|
try {
|
||||||
|
$admin->notify(new FeedbackNotification($feedback, $sender));
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::error('Failed to send feedback notification: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception $e) {
|
||||||
|
Log::error('Failed to notify admins for new feedback: '.$e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Http\Requests;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
|
||||||
|
class FeedbackRequest extends FormRequest
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine if the user is authorized to make this request.
|
||||||
|
*/
|
||||||
|
public function authorize(): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the validation rules that apply to the request.
|
||||||
|
*
|
||||||
|
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
|
||||||
|
*/
|
||||||
|
public function rules(): array
|
||||||
|
{
|
||||||
|
$rules = [
|
||||||
|
'type' => 'required|in:bug,feature_request,general_feedback,ui_issue,performance_issue',
|
||||||
|
'title' => 'required|string|max:255',
|
||||||
|
'description' => 'required|string',
|
||||||
|
'priority' => 'required|in:low,medium,high,critical',
|
||||||
|
'page_url' => 'nullable|url',
|
||||||
|
'steps_to_reproduce' => 'nullable|string',
|
||||||
|
'expected_behavior' => 'nullable|string',
|
||||||
|
'actual_behavior' => 'nullable|string',
|
||||||
|
'additional_notes' => 'nullable|string',
|
||||||
|
'images' => 'nullable|array',
|
||||||
|
'images.*' => 'file|mimes:jpeg,png,jpg,gif,webp|max:10240', // 10MB max
|
||||||
|
'videos' => 'nullable|array',
|
||||||
|
'videos.*' => 'file|mimes:mp4,mov,webm|max:51200', // 50MB max
|
||||||
|
];
|
||||||
|
|
||||||
|
// For update operations, add admin-specific fields
|
||||||
|
if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
|
||||||
|
$rules = [
|
||||||
|
'type' => 'sometimes|in:bug,feature_request,general_feedback,ui_issue,performance_issue',
|
||||||
|
'title' => 'sometimes|string|max:255',
|
||||||
|
'description' => 'sometimes|string',
|
||||||
|
'priority' => 'sometimes|in:low,medium,high,critical',
|
||||||
|
'page_url' => 'nullable|url',
|
||||||
|
'steps_to_reproduce' => 'nullable|string',
|
||||||
|
'expected_behavior' => 'nullable|string',
|
||||||
|
'actual_behavior' => 'nullable|string',
|
||||||
|
'additional_notes' => 'nullable|string',
|
||||||
|
'status' => 'sometimes|in:open,in_progress,resolved,closed,rejected',
|
||||||
|
'assigned_to' => 'nullable|exists:users,id',
|
||||||
|
'admin_notes' => 'nullable|string',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get custom messages for validator errors.
|
||||||
|
*/
|
||||||
|
public function messages(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'type.required' => 'Jenis maklum balas diperlukan.',
|
||||||
|
'type.in' => 'Jenis maklum balas tidak sah.',
|
||||||
|
'title.required' => 'Tajuk diperlukan.',
|
||||||
|
'title.max' => 'Tajuk tidak boleh melebihi 255 aksara.',
|
||||||
|
'description.required' => 'Penerangan diperlukan.',
|
||||||
|
'priority.required' => 'Keutamaan diperlukan.',
|
||||||
|
'priority.in' => 'Keutamaan tidak sah.',
|
||||||
|
'page_url.url' => 'URL halaman tidak sah.',
|
||||||
|
'images.*.mimes' => 'Format imej mestilah jpeg, png, jpg, gif atau webp.',
|
||||||
|
'images.*.max' => 'Saiz imej tidak boleh melebihi 10MB.',
|
||||||
|
'videos.*.mimes' => 'Format video mestilah mp4, mov atau webm.',
|
||||||
|
'videos.*.max' => 'Saiz video tidak boleh melebihi 50MB.',
|
||||||
|
'status.in' => 'Status tidak sah.',
|
||||||
|
'assigned_to.exists' => 'Pengguna yang ditugaskan tidak wujud.',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Notifications;
|
||||||
|
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Notifications\Notification;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
use Modules\Auth\Entities\User;
|
||||||
|
|
||||||
|
class FeedbackNotification extends Notification
|
||||||
|
{
|
||||||
|
use Queueable;
|
||||||
|
|
||||||
|
protected $feedback;
|
||||||
|
protected $sender;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new notification instance.
|
||||||
|
*/
|
||||||
|
public function __construct(Feedback $feedback, User $sender = null)
|
||||||
|
{
|
||||||
|
$this->feedback = $feedback;
|
||||||
|
$this->sender = $sender;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the notification's delivery channels.
|
||||||
|
*/
|
||||||
|
public function via($notifiable): array
|
||||||
|
{
|
||||||
|
return ['database'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the array representation of the notification.
|
||||||
|
*/
|
||||||
|
public function toArray($notifiable): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'feedback_id' => $this->feedback->id,
|
||||||
|
'sender_id' => $this->sender ? $this->sender->id : null,
|
||||||
|
'type' => 'feedback_submitted',
|
||||||
|
'message' => $this->getNotificationMessage(),
|
||||||
|
'feedback_title' => $this->feedback->title ?? 'Unknown',
|
||||||
|
'feedback_type' => $this->feedback->type ?? 'Unknown',
|
||||||
|
'feedback_priority' => $this->feedback->priority ?? 'normal',
|
||||||
|
'user_name' => $this->feedback->user ? $this->feedback->user->name : 'Anonymous',
|
||||||
|
'user_email' => $this->feedback->user ? $this->feedback->user->email : null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get notification message
|
||||||
|
*/
|
||||||
|
private function getNotificationMessage(): string
|
||||||
|
{
|
||||||
|
$userName = $this->feedback->user ? $this->feedback->user->name : 'Pengguna tanpa nama';
|
||||||
|
$feedbackTitle = $this->feedback->title ?? 'Unknown';
|
||||||
|
$feedbackType = $this->feedback->type ?? 'Unknown';
|
||||||
|
$feedbackPriority = $this->feedback->priority ?? 'normal';
|
||||||
|
$feedbackId = $this->feedback->id;
|
||||||
|
|
||||||
|
return "Maklum balas baru telah diterima. ID: {$feedbackId}, Tajuk: {$feedbackTitle}, Jenis: {$feedbackType}, Keutamaan: {$feedbackPriority}, Pengguna: {$userName}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Policies;
|
||||||
|
|
||||||
|
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
|
||||||
|
class FeedbackPolicy
|
||||||
|
{
|
||||||
|
use HandlesAuthorization;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can view any models.
|
||||||
|
*/
|
||||||
|
public function viewAny($user): bool
|
||||||
|
{
|
||||||
|
return $user->hasPermissionTo('lihat maklum balas'); // Adjust based on your authorization logic
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can view the model.
|
||||||
|
*/
|
||||||
|
public function view($user, ?Feedback $feedback = null): bool
|
||||||
|
{
|
||||||
|
return $user->hasPermissionTo('lihat maklum balas'); // Adjust based on your authorization logic
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can create models.
|
||||||
|
*/
|
||||||
|
public function create($user): bool
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can update the model.
|
||||||
|
*/
|
||||||
|
public function update($user, ?Feedback $feedback = null): bool
|
||||||
|
{
|
||||||
|
return $user->hasPermissionTo('kemaskini maklum balas'); // Adjust based on your authorization logic
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can delete any model.
|
||||||
|
*/
|
||||||
|
public function deleteAny($user): bool
|
||||||
|
{
|
||||||
|
return $user->hasPermissionTo('padam maklum balas'); // Adjust based on your authorization logic
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether the user can delete the model.
|
||||||
|
*/
|
||||||
|
public function delete($user, ?Feedback $feedback = null): bool
|
||||||
|
{
|
||||||
|
return $user->hasPermissionTo('padam maklum balas'); // Adjust based on your authorization logic
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\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,160 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Providers;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Blade;
|
||||||
|
use Illuminate\Support\ServiceProvider;
|
||||||
|
use Nwidart\Modules\Traits\PathNamespace;
|
||||||
|
use RecursiveDirectoryIterator;
|
||||||
|
use RecursiveIteratorIterator;
|
||||||
|
|
||||||
|
class FeedbackServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
use PathNamespace;
|
||||||
|
|
||||||
|
protected string $name = 'Feedback';
|
||||||
|
|
||||||
|
protected string $nameLower = 'feedback';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 repository binding
|
||||||
|
$this->app->bind(
|
||||||
|
\Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface::class,
|
||||||
|
\Modules\Feedback\Repositories\FeedbackRepository::class
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register commands in the format of Command::class
|
||||||
|
*/
|
||||||
|
protected function registerCommands(): void
|
||||||
|
{
|
||||||
|
// $this->commands([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Providers;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
|
class RouteServiceProvider extends ServiceProvider
|
||||||
|
{
|
||||||
|
protected string $name = 'Feedback';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 "api" routes for the application.
|
||||||
|
*
|
||||||
|
* These routes are typically stateless.
|
||||||
|
*/
|
||||||
|
protected function mapApiRoutes(): void
|
||||||
|
{
|
||||||
|
Route::middleware('api')->group(module_path($this->name, '/Routes/api.php'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Repositories\Contracts;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
|
||||||
|
interface FeedbackRepositoryInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get all feedback with pagination and search
|
||||||
|
*/
|
||||||
|
public function getAllPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback with their relationships and pagination with search
|
||||||
|
*/
|
||||||
|
public function getAllWithRelationsPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback with their relationships and search
|
||||||
|
*/
|
||||||
|
public function getAllWithRelations(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new feedback
|
||||||
|
*/
|
||||||
|
public function create(array $data): Feedback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find feedback by ID
|
||||||
|
*/
|
||||||
|
public function findById(string $id): ?Feedback;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete feedback (soft delete)
|
||||||
|
*/
|
||||||
|
public function delete(string $id): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback
|
||||||
|
*/
|
||||||
|
public function all(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection;
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Repositories;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
use Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface;
|
||||||
|
|
||||||
|
class FeedbackRepository implements FeedbackRepositoryInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get all feedback with pagination and search
|
||||||
|
*/
|
||||||
|
public function getAllPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = [])
|
||||||
|
{
|
||||||
|
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
|
||||||
|
|
||||||
|
if (!empty($search)) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('title', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('description', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhereHas('user', function ($userQuery) use ($search) {
|
||||||
|
$userQuery->where('name', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('email', 'ILIKE', "%{$search}%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply filters
|
||||||
|
if (!empty($filters['type'])) {
|
||||||
|
$query->where('type', $filters['type']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($filters['status'])) {
|
||||||
|
$query->where('status', $filters['status']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($filters['priority'])) {
|
||||||
|
$query->where('priority', $filters['priority']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->paginate($perPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback with their relationships and pagination with search
|
||||||
|
*/
|
||||||
|
public function getAllWithRelationsPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = [])
|
||||||
|
{
|
||||||
|
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
|
||||||
|
|
||||||
|
if (!empty($search)) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('title', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('description', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhereHas('user', function ($userQuery) use ($search) {
|
||||||
|
$userQuery->where('name', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('email', 'ILIKE', "%{$search}%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply filters
|
||||||
|
if (!empty($filters['type'])) {
|
||||||
|
$query->where('type', $filters['type']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($filters['status'])) {
|
||||||
|
$query->where('status', $filters['status']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($filters['priority'])) {
|
||||||
|
$query->where('priority', $filters['priority']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->paginate($perPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback with their relationships and search
|
||||||
|
*/
|
||||||
|
public function getAllWithRelations(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection
|
||||||
|
{
|
||||||
|
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
|
||||||
|
|
||||||
|
if (!empty($search)) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('title', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('description', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhereHas('user', function ($userQuery) use ($search) {
|
||||||
|
$userQuery->where('name', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('email', 'ILIKE', "%{$search}%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new feedback
|
||||||
|
*/
|
||||||
|
public function create(array $data): Feedback
|
||||||
|
{
|
||||||
|
return Feedback::create($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find feedback by ID
|
||||||
|
*/
|
||||||
|
public function findById(string $id): ?Feedback
|
||||||
|
{
|
||||||
|
return Feedback::with(['user', 'assignedUser', 'documents'])->find($id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete feedback (soft delete)
|
||||||
|
*/
|
||||||
|
public function delete(string $id): bool
|
||||||
|
{
|
||||||
|
$feedback = Feedback::find($id);
|
||||||
|
if ($feedback) {
|
||||||
|
return $feedback->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all feedback
|
||||||
|
*/
|
||||||
|
public function all(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection
|
||||||
|
{
|
||||||
|
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
|
||||||
|
|
||||||
|
if (!empty($search)) {
|
||||||
|
$query->where(function ($q) use ($search) {
|
||||||
|
$q->where('title', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('description', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhereHas('user', function ($userQuery) use ($search) {
|
||||||
|
$userQuery->where('name', 'ILIKE', "%{$search}%")
|
||||||
|
->orWhere('email', 'ILIKE', "%{$search}%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $query->get();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
|
use Modules\Feedback\Http\Controllers\FeedbackController;
|
||||||
|
|
||||||
|
// Public feedback submission (no authentication required)
|
||||||
|
Route::post('/v1/feedback', [FeedbackController::class, 'store'])->name('feedback.store');
|
||||||
|
|
||||||
|
// Authenticated feedback routes
|
||||||
|
Route::middleware(['auth:sanctum'])->prefix('v1')->group(function () {
|
||||||
|
Route::get('/feedback', [FeedbackController::class, 'index'])->name('feedback.index');
|
||||||
|
Route::get('/feedback/{id}', [FeedbackController::class, 'show'])->name('feedback.show');
|
||||||
|
Route::put('/feedback/{id}', [FeedbackController::class, 'update'])->name('feedback.update');
|
||||||
|
Route::patch('/feedback/{id}', [FeedbackController::class, 'update'])->name('feedback.patch');
|
||||||
|
Route::delete('/feedback/{id}', [FeedbackController::class, 'destroy'])->name('feedback.destroy');
|
||||||
|
Route::get('/feedback-statistics', [FeedbackController::class, 'statistics'])->name('feedback.statistics');
|
||||||
|
Route::get('/my-feedback', [FeedbackController::class, 'myFeedback'])->name('feedback.my');
|
||||||
|
Route::get('/feedback/{id}/documents/{documentId}/download', [FeedbackController::class, 'serveDocument'])
|
||||||
|
->name('feedback.download-document');
|
||||||
|
});
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Modules\Feedback\Transformers;
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
use Modules\Feedback\Entities\Feedback;
|
||||||
|
|
||||||
|
class FeedbackResource extends JsonResource
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Transform the resource into an array.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
public function toArray(Request $request): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $this->id,
|
||||||
|
'type' => $this->type,
|
||||||
|
'title' => $this->title,
|
||||||
|
'description' => $this->description,
|
||||||
|
'priority' => $this->priority,
|
||||||
|
'status' => $this->status,
|
||||||
|
'page_url' => $this->page_url,
|
||||||
|
'browser_info' => $this->browser_info,
|
||||||
|
'images' => $this->whenLoaded('documents', function () {
|
||||||
|
return $this->documents
|
||||||
|
->where('type', Feedback::IMAGE_DOCUMENT_TYPE)
|
||||||
|
->values()
|
||||||
|
->map(fn ($document) => $this->formatDocument($document));
|
||||||
|
}),
|
||||||
|
'videos' => $this->whenLoaded('documents', function () {
|
||||||
|
return $this->documents
|
||||||
|
->where('type', Feedback::VIDEO_DOCUMENT_TYPE)
|
||||||
|
->values()
|
||||||
|
->map(fn ($document) => $this->formatDocument($document));
|
||||||
|
}),
|
||||||
|
'steps_to_reproduce' => $this->steps_to_reproduce,
|
||||||
|
'expected_behavior' => $this->expected_behavior,
|
||||||
|
'actual_behavior' => $this->actual_behavior,
|
||||||
|
'additional_notes' => $this->additional_notes,
|
||||||
|
'admin_notes' => $this->admin_notes,
|
||||||
|
'resolved_at' => $this->resolved_at,
|
||||||
|
'user' => $this->whenLoaded('user', function () {
|
||||||
|
return [
|
||||||
|
'id' => $this->user->id,
|
||||||
|
'name' => $this->user->name,
|
||||||
|
'email' => $this->user->email,
|
||||||
|
'army_number' => $this->user->army_number,
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
'assigned_user' => $this->whenLoaded('assignedUser', function () {
|
||||||
|
return [
|
||||||
|
'id' => $this->assignedUser->id,
|
||||||
|
'name' => $this->assignedUser->name,
|
||||||
|
'email' => $this->assignedUser->email,
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
'created_at' => $this->created_at,
|
||||||
|
'updated_at' => $this->updated_at,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function formatDocument($document): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'id' => $document->id,
|
||||||
|
'name' => $document->name,
|
||||||
|
'mime_type' => $document->mime_type,
|
||||||
|
'file_size' => $document->file_size,
|
||||||
|
'type' => $document->type,
|
||||||
|
'url' => url(route('feedback.download-document', [
|
||||||
|
'id' => $this->id,
|
||||||
|
'documentId' => $document->id,
|
||||||
|
])),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user