1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Logic\Activation; |
4
|
|
|
|
5
|
|
|
use App\Models\Activation; |
6
|
|
|
use App\Models\User; |
7
|
|
|
use App\Notifications\SendActivationEmail; |
8
|
|
|
use App\Traits\CaptureIpTrait; |
9
|
|
|
use Carbon\Carbon; |
10
|
|
|
|
11
|
|
|
class ActivationRepository |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Creates a token and send email. |
15
|
|
|
* |
16
|
|
|
* @param \App\Models\User $user |
17
|
|
|
* |
18
|
|
|
* @return bool or void |
19
|
|
|
*/ |
20
|
|
|
public function createTokenAndSendEmail(User $user) |
21
|
|
|
{ |
22
|
|
|
$activations = Activation::where('user_id', $user->id) |
23
|
|
|
->where('created_at', '>=', Carbon::now()->subHours(config('settings.timePeriod'))) |
24
|
|
|
->count(); |
25
|
|
|
|
26
|
|
|
if ($activations >= config('settings.maxAttempts')) { |
27
|
|
|
return true; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
//if user changed activated email to new one |
31
|
|
|
if ($user->activated) { |
32
|
|
|
$user->update([ |
33
|
|
|
'activated' => false, |
34
|
|
|
]); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// Create new Activation record for this user |
38
|
|
|
$activation = self::createNewActivationToken($user); |
39
|
|
|
|
40
|
|
|
// Send activation email notification |
41
|
|
|
self::sendNewActivationEmail($user, $activation->token); |
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Creates a new activation token. |
46
|
|
|
* |
47
|
|
|
* @param \App\Models\User $user |
48
|
|
|
* |
49
|
|
|
* @return \App\Models\Activation $activation |
50
|
|
|
*/ |
51
|
|
|
public function createNewActivationToken(User $user) |
52
|
|
|
{ |
53
|
|
|
$ipAddress = new CaptureIpTrait(); |
54
|
|
|
$activation = new Activation(); |
55
|
|
|
$activation->user_id = $user->id; |
56
|
|
|
$activation->token = str_random(64); |
57
|
|
|
$activation->ip_address = $ipAddress->getClientIp(); |
58
|
|
|
$activation->save(); |
59
|
|
|
|
60
|
|
|
return $activation; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Sends a new activation email. |
65
|
|
|
* |
66
|
|
|
* @param \App\Models\User $user The user |
67
|
|
|
* @param string $token The token |
68
|
|
|
*/ |
69
|
|
|
public function sendNewActivationEmail(User $user, $token) |
70
|
|
|
{ |
71
|
|
|
$user->notify(new SendActivationEmail($token)); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Method to removed expired activations. |
76
|
|
|
* |
77
|
|
|
* @return void |
78
|
|
|
*/ |
79
|
|
|
public function deleteExpiredActivations() |
80
|
|
|
{ |
81
|
|
|
Activation::where('created_at', '<=', Carbon::now()->subHours(72))->delete(); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|