อย่างไรก็ตาม ระบบดังกล่าวยังคงเก็บข้อมูลจริงลงฐานข้อมูลโดยไม่มีการเข้ารหัสใดๆ ทำให้ Database Admin ยังสามารถเข้าดูข้อมูลและแก้ไขได้
การเข้ารหัสข้อมูลก่อนเก็บลงฐานข้อมูล จึงเป็นการเพิ่มความปลอดภัยของข้อมูลอีกขั้นนึง
สำหรับ Laravel Model ที่มี function กลางสำหรับการดึงค่าข้อมูลและเก็บข้อมูลของ Fields ต่างๆ ทำให้การเข้ารหัสและถอดรหัสนั้นทำได้ง่ายขึ้นมาก เราเพียงเขียน Trait แล้วนำไปใส่ใน Model พร้อมกับกำหนด Fields ที่เราต้องการเข้ารหัสเท่านั้น
โค้ดของ Trait เป็นดังนี้
<?php
namespace App\Traits;
trait Encryptable
{
/**
* If the attribute is in the encryptable array
* then decrypt it.
*
* @param $key
*
* @return $value
*/
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (isset($this->encryptable) && in_array($key, $this->encryptable) && $value !== '') {
$value = decrypt($value);
}
return $value;
}
/**
* If the attribute is in the encryptable array
* then encrypt it.
*
* @param $key
* @param $value
*/
public function setAttribute($key, $value)
{
if (isset($this->encryptable) && in_array($key, $this->encryptable)) {
$value = encrypt($value);
}
return parent::setAttribute($key, $value);
}
/**
* When need to make sure that we iterate through
* all the keys.
*
* @return array
*/
public function attributesToArray()
{
$attributes = parent::attributesToArray();
if (isset($this->encryptable)) {
foreach ($this->encryptable as $key) {
if (isset($attributes[$key])) {
$attributes[$key] = decrypt($attributes[$key]);
}
}
return $attributes;
}
}
}
โดยที่
getAttribute($key)เป็น function ที่ถูกเรียกโดยอัตโนมัติ เมื่อมีการดึงค่า AttributesetAttribute($key, $value)เป็น function ที่ถูกเรียกโดยอัตโนมัติ เมื่อมีการตั้งค่า AttributeattributesToArray()เป็น function ที่ถูกเรียกโดยอัตโนมัติ เมื่อมีแปลง Attributes ทั้งหมดของ Model ไปเป็น Array
- ประกาศ
use App\Traits\Encryptable; - ใส่
use Encryptable;ใน Model Class - ตั้งค่า fields ที่ต้องการเข้ารหัสใน
$encryptable
ตัวอย่างการใช้งาน Trait ข้างต้นเป็นดังนี้
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\Encryptable;
class UserSalary extends Model
{
use Encryptable;
protected $fillable = [
'user_id',
'payroll',
'start_at',
'end_at',
];
protected $encryptable = [
'payroll',
];
}
No comments:
Post a Comment