Search code examples
laravelencryptionlaravel-5md5password-encryption

How to convert password from md5 to laravel encryption method


I want to re-develop my existing project to laravel.

In my old system I store password into md5.

Now how can I convert it according to laravel hash method for existing user.

Is there any direct method to do it?


Solution

  • Is there any direct method to do it?

    No there's no direct method, but you could achieve that by overriding postLogin inside Auth/AuthController.php so it will check if the password is in md5 format then recrypt it with laravel hashing method else the user will connect normally, like :

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            'login' => 'required', 'password' => 'required',
        ]);
        $credentials = $this->getCredentials($request);
    
        //Get the user
        $user = User::where('login', $request->login)->first();
    
        //If Hached by bcrypt
        if (Auth::attempt($credentials, $request->has('remember'))) 
        {
            return redirect()->intended($this->redirectPath());
        }
        else //Else if Hached by md5
        {
            if( $user && $user->password == md5($request->password) )
            {
                $user->password = Hash::make($request->password);
                $user->save();
    
                if($user->authorized){
                    $user->save();
    
                    Auth::login($user);
                }else
                    Auth::logout();
            }
        }
    
        return redirect($this->loginPath())
            ->withInput($request->only('login', 'remember'))
            ->withErrors([
                'login' => $this->getFailedLoginMessage(),
            ]);
    }
    

    Hope this helps.