-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathVerificationCode.php
More file actions
228 lines (197 loc) · 8.43 KB
/
VerificationCode.php
File metadata and controls
228 lines (197 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?php
namespace Fleetbase\Models;
use Fleetbase\Casts\Json;
use Fleetbase\Mail\VerificationMail;
use Fleetbase\Services\SmsService;
use Fleetbase\Support\Utils;
use Fleetbase\Traits\Expirable;
use Fleetbase\Traits\HasMetaAttributes;
use Fleetbase\Traits\HasSubject;
use Fleetbase\Traits\HasUuid;
use Fleetbase\Twilio\Support\Laravel\Facade as Twilio;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Mail;
class VerificationCode extends Model
{
use HasUuid;
use Expirable;
use HasSubject;
use HasMetaAttributes;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'verification_codes';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['subject_uuid', 'subject_type', 'code', 'for', 'expires_at', 'meta', 'status'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'expires_at' => 'datetime',
'meta' => Json::class,
];
/**
* Dynamic attributes that are appended to object.
*
* @var array
*/
protected $appends = [];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [];
/** on boot generate code */
public static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->code = mt_rand(100000, 999999);
});
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function subject()
{
return $this->morphTo(__FUNCTION__, 'subject_type', 'subject_uuid');
}
/**
* Generates a verification code object for the specified subject and context.
* This method can optionally save the generated verification code to the database.
*
* @param mixed $subject The subject for which the verification code is generated. Could be a User model or similar.
* @param string $for The context or purpose for generating the verification code. Default is 'general_verification'.
* @param bool $save Determines whether to persist the generated verification code to the database. Default is true.
*
* @return static returns an instance of the verification code with optional subject and purpose set
*/
public static function generateFor($subject = null, $for = 'general_verification', $save = true)
{
$verifyCode = new static();
$verifyCode->for = $for;
if ($subject) {
$verifyCode->setSubject($subject, false);
}
if ($save) {
$verifyCode->save();
}
return $verifyCode;
}
/**
* Generates and sends an email verification code for a specified subject. This method configures and sends an email
* containing the verification code.
*
* @param mixed $subject the subject (typically a User model) to whom the verification email will be sent
* @param string $for Context or purpose of the verification. Default is 'email_verification'.
* @param array $options Options to customize the verification process. Can include 'expireAfter' to set a custom expiration,
* 'meta' for additional metadata, 'subject' for the email subject, and 'content' for the email content.
*
* @return static returns the verification code instance after persisting it to the database and sending the email
*
* @throws \Exception throws an exception if the email cannot be sent
*/
public static function generateEmailVerificationFor($subject, $for = 'email_verification', array $options = [])
{
$expireAfter = data_get($options, 'expireAfter');
$verificationCode = static::generateFor($subject, $for, false);
$verificationCode->expires_at = $expireAfter === null ? Carbon::now()->addHour() : $expireAfter;
$verificationCode->meta = data_get($options, 'meta', []);
$verificationCode->save();
if (isset($subject->email)) {
// See if subject option passed is callable
$mailableSubject = data_get($options, 'subject');
if (is_callable($mailableSubject)) {
$options['subject'] = $mailableSubject($verificationCode);
}
// See if content or messageCallback passed
$content = Utils::or($options, ['content', 'messageCallback']);
if (is_callable($content)) {
$content = $content($verificationCode);
}
// Initialize the mailable definition
$mail = new VerificationMail($verificationCode, $content);
// Apply any additional Mail facade parameters
$mailer = Mail::to($subject);
foreach ($options as $key => $value) {
if (method_exists($mailer, $key)) {
$mailer->$key($value);
}
}
$mailer->send($mail);
}
return $verificationCode;
}
/**
* Generates and sends an SMS verification code for a specified subject. This method handles the creation and dispatch
* of an SMS containing the verification code.
*
* @param mixed $subject the subject (typically a User model) to whom the SMS will be sent
* @param string $for Context or purpose of the verification. Default is 'phone_verification'.
* @param array $options Options to customize the verification process. Can include 'expireAfter' to set a custom expiration,
* 'meta' for additional metadata, and 'messageCallback' to customize the SMS message content.
*
* @return static returns the verification code instance after persisting it to the database and sending the SMS
*
* @throws \Exception throws an exception if the SMS cannot be sent
*/
public static function generateSmsVerificationFor($subject, $for = 'phone_verification', array $options = [])
{
$expireAfter = data_get($options, 'expireAfter');
$verificationCode = static::generateFor($subject, $for, false);
$verificationCode->expires_at = $expireAfter === null ? Carbon::now()->addHour() : $expireAfter;
$verificationCode->meta = data_get($options, 'meta', []);
$verificationCode->save();
// Get message
$message = 'Your ' . config('app.name') . ' verification code is ' . $verificationCode->code;
$messageCallback = data_get($options, 'messageCallback');
if (is_callable($messageCallback)) {
$message = $messageCallback($verificationCode);
}
// SMS service options
$smsOptions = [];
// Check for company-specific sender ID
$companyUuid = data_get($options, 'company_uuid') ?? session('company') ?? data_get($subject, 'company_uuid');
if ($companyUuid) {
$company = Company::select(['uuid', 'options'])->find($companyUuid);
if ($company) {
$enabled = Utils::castBoolean($company->getOption('alpha_numeric_sender_id_enabled'));
$senderId = $company->getOption('alpha_numeric_sender_id');
if ($enabled && !empty($senderId)) {
// Alphanumeric sender IDs are Twilio-specific
// Do NOT set in $smsOptions['from'] as it would be passed to all providers
$smsOptions['twilioParams']['from'] = $senderId;
}
}
}
// Allow explicit provider selection
$provider = data_get($options, 'provider');
// Send SMS using SmsService with automatic provider routing
if ($subject->phone) {
try {
$smsService = new SmsService();
$smsService->send($subject->phone, $message, $smsOptions, $provider);
} catch (\Throwable $e) {
// Log error but don't fail the verification code generation
\Illuminate\Support\Facades\Log::error('Failed to send SMS verification', [
'phone' => $subject->phone,
'error' => $e->getMessage(),
]);
// Optionally rethrow based on configuration
if (config('sms.throw_on_error', false)) {
throw $e;
}
}
}
return $verificationCode;
}
}