This repository was archived by the owner on Apr 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathHasEncryptedAttributes.php
335 lines (299 loc) · 9.16 KB
/
HasEncryptedAttributes.php
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
<?php
/**
* src/Traits/HasEncryptedAttributes.php.
*
* @author Austin Heap <me@austinheap.com>
* @version v0.2.1
*/
declare(strict_types=1);
namespace AustinHeap\Database\Encryption\Traits;
use AustinHeap\Database\Encryption\EncryptionFacade as DatabaseEncryption;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Encryption\EncryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
/**
* HasEncryptedAttributes.
*
* Automatically encrypt and decrypt Laravel 5.5+ Eloquent values
*
* ### Example
*
* <code>
* use AustinHeap\Database\Encryption\Traits\HasEncryptedAttributes;
*
* class User extends Eloquent {
*
* use HasEncryptedAttributes;
*
* protected $encrypted = [
* 'address_line_1', 'first_name', 'last_name', 'postcode'
* ];
* }
* </code>
*
* ### Summary of Methods in Illuminate\Database\Eloquent\Model
*
* This surveys the major methods in the Laravel Model class as of
* Laravel v5.5 and checks to see how those models set attributes
* and hence how they are affected by this trait.
*
* - __construct -- calls fill()
* - fill() -- calls setAttribute() which has been overridden.
* - hydrate() -- TBD
* - create() -- calls constructor and hence fill()
* - firstOrCreate -- calls constructor
* - firstOrNew -- calls constructor
* - updateOrCreate -- calls fill()
* - update() -- calls fill()
* - toArray() -- calls attributesToArray()
* - jsonSerialize() -- calls toArray()
* - toJson() -- calls toArray()
* - attributesToArray() -- has been over-ridden here.
* - getAttribute -- calls getAttributeValue()
* - getAttributeValue -- calls getAttributeFromArray()
* - getAttributeFromArray -- calls getArrayableAttributes
* - getArrayableAttributes -- has been over-ridden here.
* - setAttribute -- has been over-ridden here.
* - getAttributes -- has been over-ridden here.
*
* @see \Illuminate\Support\Facades\Crypt
* @see \Illuminate\Contracts\Encryption\Encrypter
* @see \Illuminate\Encryption\Encrypter
* @link http://laravel.com/docs/5.5/eloquent
* @link https://github.com/austinheap/laravel-database-encryption
* @link https://packagist.org/packages/austinheap/laravel-database-encryption
* @link https://austinheap.github.io/laravel-database-encryption/classes/AustinHeap.Database.Encryption.EncryptionServiceProvider.html
*/
trait HasEncryptedAttributes
{
/**
* Private copy of last Encryption exception to occur.
*
* @var null|EncryptException|DecryptException
*/
private $lastEncryptionException = null;
/**
* Get the last encryption-related exception to occur, if any.
*
* @return null|EncryptException|DecryptException
*/
public function getLastEncryptionException()
{
return $this->lastEncryptionException;
}
/**
* Set the last encryption-related exception to occur, if any.
*
* @param null|EncryptException|DecryptException $exception
* @param null|string $function
*
* @return self
*/
protected function setLastEncryptionException($exception, ?string $function = null): self
{
Log::debug('Ignored exception "'.get_class($exception).'" in function "'.(is_null($function) ? '(unknown)' : $function).'": '.$exception->getMessage());
$this->lastEncryptionException = $exception;
return $this;
}
/**
* Get the configuration setting for the prefix used to determine if a string is encrypted.
*
* @return string
*/
protected function getEncryptionPrefix(): string
{
return DatabaseEncryption::getHeaderPrefix();
}
/**
* Determine whether an attribute should be encrypted.
*
* @param string $key
*
* @return bool
*/
protected function shouldEncrypt($key): bool
{
$encrypt = DatabaseEncryption::isEnabled() && isset($this->encrypted) && is_array($this->encrypted) ? $this->encrypted : [];
return in_array($key, $encrypt, true);
}
/**
* Determine whether a model is ready for encryption.
*
* @return bool
*/
protected function isEncryptable(): bool
{
$exists = property_exists($this, 'exists');
return $exists === false || ($exists === true && $this->exists === true);
}
/**
* Determine whether a string has already been encrypted.
*
* @param mixed $value
*
* @return bool
*/
protected function isEncrypted($value): bool
{
return strpos((string) $value, $this->getEncryptionPrefix()) === 0;
}
/**
* Return the encrypted value of an attribute's value.
*
* This has been exposed as a public method because it is of some
* use when searching.
*
* @param string $value
*
* @return null|string
*/
public function encryptedAttribute($value): ?string
{
return DatabaseEncryption::buildHeader($value).Crypt::encrypt($value);
}
/**
* Return the decrypted value of an attribute's encrypted value.
*
* This has been exposed as a public method because it is of some
* use when searching.
*
* @param string $value
*
* @return null|mixed
* @throws \Throwable
*/
public function decryptedAttribute($value)
{
$characters = DatabaseEncryption::getControlCharacters('header');
throw_if(! array_key_exists('stop', $characters), DecryptException::class, 'Cannot decrypt model attribute not originally encrypted by this package!');
$offset = strpos($value, $characters['stop']['string']);
throw_if($offset === false, DecryptException::class, 'Cannot decrypt model attribute with no package header!');
$value = substr($value, $offset);
return Crypt::decrypt($value);
}
/**
* Encrypt a stored attribute.
*
* @param string $key
*
* @return self
*/
protected function doEncryptAttribute($key): self
{
if ($this->shouldEncrypt($key) && ! $this->isEncrypted($this->attributes[$key])) {
try {
$this->attributes[$key] = $this->encryptedAttribute($this->attributes[$key]);
} catch (EncryptException $exception) {
$this->setLastEncryptionException($exception, __FUNCTION__);
}
}
return $this;
}
/**
* Decrypt an attribute if required.
*
* @param string $key
* @param mixed $value
*
* @return mixed
*/
protected function doDecryptAttribute($key, $value)
{
if ($this->shouldEncrypt($key) && $this->isEncrypted($value)) {
try {
return $this->decryptedAttribute($value);
} catch (DecryptException $exception) {
$this->setLastEncryptionException($exception, __FUNCTION__);
}
}
return $value;
}
/**
* Decrypt each attribute in the array as required.
*
* @param array $attributes
*
* @return array
*/
public function doDecryptAttributes($attributes)
{
foreach ($attributes as $key => $value) {
$attributes[$key] = $this->doDecryptAttribute($key, $value);
}
return $attributes;
}
//
// Methods below here override methods within the base Laravel/Illuminate/Eloquent
// model class and may need adjusting for later releases of Laravel.
//
/**
* Decrypt encrypted data before it is processed by cast attribute.
*
* @param $key
* @param $value
*
* @return mixed
*/
protected function castAttribute($key, $value)
{
return parent::castAttribute($key, $this->doDecryptAttribute($key, $value));
}
/**
* Get the attributes that have been changed since last sync.
*
* @return array
*/
public function getDirty()
{
$dirty = [];
foreach ($this->attributes as $key => $value) {
if (! $this->originalIsEquivalent($key, $value)) {
$dirty[$key] = $value;
}
}
return $dirty;
}
/**
* Set a given attribute on the model.
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function setAttribute($key, $value)
{
parent::setAttribute($key, $value);
$this->doEncryptAttribute($key);
}
/**
* Get an attribute from the $attributes array.
*
* @param string $key
*
* @return mixed
*/
protected function getAttributeFromArray($key)
{
return $this->doDecryptAttribute($key, parent::getAttributeFromArray($key));
}
/**
* Get an attribute array of all arrayable attributes.
*
* @return array
*/
protected function getArrayableAttributes()
{
return $this->doDecryptAttributes(parent::getArrayableAttributes());
}
/**
* Get all of the current attributes on the model.
*
* @return array
*/
public function getAttributes()
{
return $this->isEncryptable() ? $this->doDecryptAttributes(parent::getAttributes()) : parent::getAttributes();
}
}