[Vuejs]-Adding logic to loginController

0👍

See https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php for all the functions that are contained within the AuthenticatesUsers trait.

You can for instance override the login function like this:

LoginController.php

use AuthenticatesUsers {
    // Rename one function to another name, so we can use the original name ourselves.
    login as loginTrait;
}

public function login(Request $request)
{
    // And here you can put your own logic, a good starting point is
    // the source (the `AuthenticatesUsers::login()` function).

    // Call the original function.
    $this->loginTrait($request);
}

Also, there is an protected function authenticated(Request $request, $user) defined which you can freely override. This gets called after a user is authenticated.

0👍

I would override the authenticated method and add your logic there:

 /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        redirect()->intended($this->redirectPath())->cookie(
            'profile_id', $user->profiles[0]->id, now()->addSeconds(86400)
        );
    }

The reason this works is that once you’re authenticated, it hits the sendLoginResponse (as defined in the Trait), and calls the authenticated function. That function is empty by default, so it returns null which triggers the null coalesce comparison in the sendLoginResponse. what we’ve done here is copy the fall through logic of that method and added a cookie to be returned with the response.

0👍

AuthenticatesUsers::sendLoginResponse is returning a RedirectResponse after the user is authenticated.

A straight forward way is to override sendLoginResponse and include the cookie in the original response headers through ResponseTrait::cookie.

use Symfony\Component\HttpFoundation\Cookie;

class LoginController extends Controller
{
    use AuthenticatesUsers;
    #...

    /**
    * Send the response after the user was authenticated.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
    protected function sendLoginResponse(Request $request)
    {
        return parent::sendLoginResponse($request)
               ->cookie(
                   new Cookie(
                      "profile_id",
                      Auth::user()->profiles[0]->id,
                      time() + 86400,
                      "/"
                  )
              );
    }
}

Leave a comment