0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Using an encrypted column for auth login in Laravel.

Last updated at Posted at 2019-11-30

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;
        }
    }
}   

References

Encrypted email validation in laravel

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?