File: /var/www/javago-portal-updates/app/Http/Controllers/Admin/OTPController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\OTPRequest;
use App\Mail\SendOTPMail;
use App\Models\Admin;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
class OTPController extends Controller
{
private $redirectTo = 'admin/dashboard';
private $minute;
public function __construct()
{
// use guard as per role
$this->middleware('guest:admin')->except('logout');
$this->minute = 5;
}
public function showOTPForm($id)
{
if ($id) {
$url = route('admin.otp.verify', $id);
$resendUrl = route('admin.otp.resend', $id);
return view('custom_auth.otp', compact('url', 'resendUrl'));
}
}
public function resendOTP($id)
{
try {
if ($id) {
$id = decrypt($id);
$admin = Admin::find($id);
if (!empty($admin)) {
$otp = mt_rand(100000, 999999);
$admin->otp = $otp;
$admin->otp_expired_at = Carbon::now()->addMinutes($this->minute)->timestamp;
$result = $admin->save();
if ($result) {
$subject = __('auth.subjectOTP');;
$username = $admin->full_name;
$view = 'emails.otp';
$reply_to = $admin->email;
$data = [
'subject' => $subject,
'username' => $username,
'otp' => $otp,
'view' => $view,
'count' => $this->minute,
];
Mail::to($reply_to)->send(new SendOTPMail($data));
return redirect()->back()->with('success_message', __('auth.OTPSendSuccessfully'));
} else {
return redirect()->back()->with('error_message', __('common.somethingWentWrong'));
}
} else {
return redirect()->back()->with('error_message', __('common.somethingWentWrong'));
}
} else {
return redirect()->back()->with('error_message', __('common.somethingWentWrong'));
}
} catch (\Throwable $th) {
return redirect()->back()->with('error_message', __('common.somethingWentWrong'));
}
}
protected function guard()
{
// use guard as per role
return Auth::guard('admin');
}
public function verifyOTP(OTPRequest $request, $id)
{
try {
$id = decrypt($id);
$admin = Admin::find($id);
if (!empty($admin)) {
$time = Carbon::now()->timestamp;
if ($admin->otp_expired_at >= $time) {
if ($admin->otp == $request->otp) {
$otp_verified_at = Carbon::now()->timestamp;
$admin->update(['otp' => 0, 'otp_verified_at' => $otp_verified_at]);
Auth::guard('admin')->login($admin);
return redirect()->route('admin.dashboard');
} else {
session()->flash('error_message', __('auth.validOTP'));
return redirect()->back();
}
} else {
$admin->update(['otp' => 0]);
session()->flash('error_message', __('auth.OTPExpired'));
return redirect()->back();
}
} else {
session()->flash('error_message', __('common.somethingWentWrong'));
return redirect()->back();
}
} catch (\Throwable $th) {
session()->flash('error_message', __('common.somethingWentWrong'));
return redirect()->back();
}
}
}