How to stop user redirection after receiving login request in laravel 5.3

Posted 2 years ago by anonymox

I have a strange problem, I want to show logged in message after one attempt of user login. I mean if user attempt for the first time he/she gets token, then if he/she send more request exactly like before I want to show a json response to him/her which says your are logged in.

But I couldn't figure it out how. FYI : I'm using my own customized laravel auth scaffold.

AuthenticatesUsers.php :

<?php

namespace App\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Lang;
use GuzzleHttp\Client;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins;

    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * Validate the user login request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required', 'password' => 'required',
        ]);
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        isset($request->refresh_token) ? $refreshToken = $request->refresh_token : $refreshToken = null;//Check if login request contain token

        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ? $this->StatusCode($refreshToken,$this->credentials($request),$status=false) : $this->StatusCode($refreshToken,$this->credentials($request),$status=true);
//                ?: redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        return \Response::json('Logged In','200');
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        isset($request->refresh_token) ? $refreshToken = $request->refresh_token : $refreshToken = null;//Check if login request contain token

        return $this->StatusCode($refreshToken,$this->credentials($request),$status=false);
//        return redirect()->back()
//            ->withInput($request->only($this->username(), 'remember'))
//            ->withErrors([
//                $this->username() => Lang::get('auth.failed'),
//            ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'email';
    }

    /**
     * Log the user out of the application.
     *
     * @param \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

//        return redirect('/');
        return response()->json('Logged out', '200');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }


    public function StatusCode($refreshToken,$user,$status){

        function GetToken($userobject)
        {
            $http = new Client;

            $response = $http->post('http://localhost/iranAd/public/oauth/token', [ //TODO Make this url dynamic
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => '1',
                    'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
                    'username' => $userobject['email'],
                    'password' => $userobject['password'],
                    'scope' => '',
                ],
            ]);

            return json_decode((string) $response->getBody(), true);
        }

        function RefreshToken($refresh_token)
        {

            $http = new Client;

            $response = $http->post('http://localhost/iranAd/public/oauth/token', [ //TODO Make this url dynamic
                'form_params' => [
                    'grant_type' => 'refresh_token',
                    'refresh_token' => $refresh_token,
                    'client_id' => '1',
                    'client_secret' => 'xKqNbzcXyjySg20nVuVLw5nk5PAMhFQOQwRTeTjd',
                ],
            ]);

            return json_decode((string) $response->getBody(), true);//TODO Fix The Token has expired Exception
        }

        if(is_null($refreshToken)){
            return ($status == true) ? response()->json(GetToken($user),200) : response()->json(['Message' => 'Failed to log in'],403);
        }elseif (isset($refreshToken) && (!empty($refreshToken))){
            return ($status == true) ? response()->json(RefreshToken($refreshToken),200) : response()->json(['Message' => 'Failed to log in'],403);
        }

    }
}

Please sign in or create an account to participate in this conversation.