File: /home/armgroup/libs/app/Http/Livewire/Auth/MobileVerification.php
<?php
namespace App\Http\Livewire\Auth;
use App\Models\User;
use App\Models\Verification;
use App\Notifications\VerificationCode;
use Carbon\Carbon;
use Illuminate\Validation\Rule;
trait MobileVerification
{
public $mobile;
public $code;
public $step = 1;
public function sendSMS()
{
$this->validate();
if ($this->canSendVerificationSMS(Verification::where('mobile', $this->mobile)->first())) {
$this->sendVerificationSMS();
}
$this->step = 2;
}
public function resend()
{
$verificationCode = Verification::where('mobile', $this->mobile)->first();
if ($this->canSendVerificationSMS($verificationCode)) {
$this->sendVerificationSMS();
session()->flash('message', ['status' => 'success', 'content' => __('Verification code sent successfully')]);
} else {
$totalDuration = Carbon::parse($verificationCode->updated_at->addMinutes(Verification::EXPIRATION_TIME))
->diffInSeconds();
session()->flash('message', ['status' => 'danger', 'content' => __('The verification code has just been sent to you, remaining time to resend :totalDuration Second', ['totalDuration' => $totalDuration])]);
}
$this->step = 2;
}
public function confirmValidationCode($type = null)
{
$this->validate([
'code' => ['required', 'string', Rule::exists('verifications')->where(function ($query) {
return $query->where('mobile', $this->mobile);
})],
]);
Verification::whereMobile($this->mobile)->whereCode($this->code)->update([
'approved' => true,
]);
if ($type == 'changeMobile') {
$this->updateMobile();
} elseif ($type == 'resetPassword') {
$this->step = 3;
} else {
session(['verification' => ['mobile' => $this->mobile, 'code' => $this->code]]);
return redirect()->route('register.normal');
// return redirect()->route('register.choose');
}
}
private function canSendVerificationSMS($verificationCode)
{
return ! ($verificationCode && $verificationCode->updated_at > Carbon::now()->subMinutes(Verification::EXPIRATION_TIME));
}
private function sendVerificationSMS()
{
$verification = Verification::generateCode($this->mobile);
$verification->notify(new VerificationCode);
}
private function canTakeMobile($mobile = null, $code = null)
{
$mobile = $mobile ?: $this->mobile;
$code = $code ?: $this->code;
$checkVerification = Verification::whereMobile($mobile)
->whereCode($code)
->whereApproved(true)
->count() ? true : false;
$chekUsers = User::whereMobile($mobile)->count() ? false : true;
return $checkVerification && $chekUsers;
}
}