Files
ERP-upgrade/app/Http/Controllers/OtpController.php
2026-08-27 11:52:50 +00:00

74 lines
2.2 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\StaffMember;
use Illuminate\Http\Request;
use App\Mail\LoginOtpMail;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
class OtpController extends Controller
{
public function show()
{
if (!session()->has('otp_staff_id')) {
return redirect()->route('login');
}
return view('auth.otp-verify');
}
public function verify(Request $request)
{
$request->validate(['otp' => 'required|numeric|digits:6']);
$staff = StaffMember::findOrFail(session('otp_staff_id'));
// Check if OTP matches and is not expired
if ($staff->otp_code == $request->otp && now()->lessThanOrEqualTo($staff->otp_expires_at)) {
// Clear the OTP data
$staff->update([
'otp_code' => null,
'otp_expires_at' => null
]);
// Log the staff member in
// NOTE: If using a specific guard, use Auth::guard('staff')->login($staff);
Auth::login($staff);
// Clear the temp session
session()->forget('otp_staff_id');
return redirect()->intended('/');
}
return back()->withErrors(['otp' => 'The verification code is invalid or has expired.']);
}
public function resend(Request $request)
{
// Ensure the session still exists
if (!session()->has('otp_staff_id')) {
return redirect()->route('login')->withErrors(['email' => 'Session expired. Please log in again.']);
}
$staff = StaffMember::findOrFail(session('otp_staff_id'));
// Generate a new 6-digit OTP
$otp = rand(100000, 999999);
// Update database with new code and fresh 10-minute expiration
$staff->update([
'otp_code' => $otp,
'otp_expires_at' => now()->addMinutes(10)
]);
// Send the new code via email
Mail::to($staff->email)->send(new LoginOtpMail($otp));
return back()->with('success', 'A new verification code has been sent to your email.');
}
}