Everybody wants to encrypt personal information.
That is the way of the world isn't that?
Anyway, I wrote down how to make it come true.
Introduction
This time, I encrypt 'email' column and use it for auth login.
Encryption is easy because you use just encrypt method, however you can't login because values don't be matched in attempt method.
So that I override attempt method to decrypt email column which was encrypted in its.
Environment
Target | Version |
---|---|
PHP | 7.3.12 |
Laravel | 6.2 |
Encrypt when create
app/Http/Controllers/Auth/RegistraterController.php
protected function create(array $data)
{
return User::create([
'email' => encrypt($data['email']),
'password' => Hash::make($data['password']),
]);
}
}
Add Attributtion method on Model
You always get decrypted value when you use below.
appModels/User.php
public function getEmailAttribute($value)
{
return decrypt($value);
}
Override attemptLogin method
app/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User; // Add
use Illuminate\Http\Request; // Add
use Illuminate\Support\Facades\Hash; // Add
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
...
// Override to use decrypt column for attempt.
protected function attemptLogin(Request $request)
{
$users = User::all();
$isUserValidated = false;
$field = $request->email;
foreach ($users as $user) {
try {
if ( $field === $user->email && Hash::check($request->password, $user->password) ) {
$isUserValidated = true;
$this->guard()->login($user, false);
break;
}
} catch (DecryptException $e) {
// do something you want
}
return $isUserValidated;
}
}
}