Skip to content

Commit 67175ac

Browse files
authored
Merge pull request #11 from labomatik/ability-to-encrypt-body
Ability to encrypt automatically message's body
2 parents f74ca76 + 0c379e1 commit 67175ac

File tree

4 files changed

+46
-2
lines changed

4 files changed

+46
-2
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ php artisan migrate
6464
To configure message body encryption add these key on `.env` file.
6565

6666
```
67-
CHAT_ENCRYPT_MESSAGE=true #boolen
67+
CHAT_ENCRYPT_MESSAGE=true #boolean
6868
```
6969

7070
## Usage

config/chat.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@
1414
'media_folder' => env('CHAT_MEDIA_FOLDER', 'image'),
1515
'pusher_event_trigger' => [
1616
'send_message' => env('CHAT_SEND_MESSAGE_PUSHER_EVENT', true)
17-
]
17+
],
18+
'encrypt_message' => env('CHAT_ENCRYPT_MESSAGE', false),
1819
];

src/Helpers/Helper.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
use Illuminate\Support\Str;
88
use Illuminate\Support\Facades\File;
9+
use Illuminate\Support\Facades\Crypt;
910
use Illuminate\Support\Facades\Storage;
11+
use Illuminate\Contracts\Encryption\DecryptException;
1012

1113
class Helper
1214
{
@@ -63,4 +65,14 @@ public static function fileDelete($disk, $path, $fileName)
6365
return true;
6466
}
6567
}
68+
69+
public static function isEncrypted($value)
70+
{
71+
try {
72+
Crypt::decryptString($value);
73+
return true;
74+
} catch (DecryptException $e) {
75+
return false;
76+
}
77+
}
6678
}

src/Models/Message.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
namespace SevenSpan\Chat\Models;
44

55
use App\Models\User;
6+
use SevenSpan\Chat\Helpers\Helper;
7+
use Illuminate\Support\Facades\Crypt;
68
use Illuminate\Database\Eloquent\Model;
79
use Illuminate\Support\Facades\Storage;
810
use Illuminate\Database\Eloquent\SoftDeletes;
11+
use Illuminate\Database\Eloquent\Casts\Attribute;
912
use Illuminate\Database\Eloquent\Factories\HasFactory;
1013

1114
class Message extends Model
@@ -73,4 +76,32 @@ public function variables()
7376
{
7477
return $this->hasMany(MessageVariable::class, 'message_id', 'id');
7578
}
79+
80+
/**
81+
* Get the attributes that should be cast.
82+
*
83+
* @return array<string, string>
84+
*/
85+
protected function casts(): array
86+
{
87+
if(config('chat.encrypt_message')) {
88+
return [
89+
'body' => 'encrypted',
90+
];
91+
}else {
92+
return [
93+
'body' => 'string',
94+
];
95+
}
96+
}
97+
98+
99+
protected function body(): Attribute
100+
{
101+
return Attribute::make(
102+
get: function (string $value) {
103+
return Helper::isEncrypted($value) ? Crypt::decryptString($value) : $value;
104+
}
105+
);
106+
}
76107
}

0 commit comments

Comments
 (0)