S
S
serNevajno2020-02-25 11:48:08
JavaScript
serNevajno, 2020-02-25 11:48:08

Like in Laravel+jquery: Authorization - how to do it?

Hello uv. community. Please tell me how to implement authorization in laravel using jquery.
JS:

$('body').on('submit', '#login-form', function (e) {
                e.preventDefault();
                var token = $('#login-form input[name="_token"]').val();

                $.ajax({
                        url: "/login",
                        data: $('#login-form').serialize(),
                        headers: {
                                'X-CSRF-TOKEN': token
                        },
                        type: 'POST',
                        dataType: 'JSON',
                        success: function (html) {
                                console.log("ok");
                                console.log(html);
                        },
                        error: function (data) {
                                console.log("error");
                                console.log(data);
                        }
                });

                console.log('Submit');
        });

AuthenticatesUser.php:
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 (method_exists($this, 'hasTooManyLoginAttempts') &&
            $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);
    }


Console:
Submit
error
{…}
​abort
: function abort(t)
​ always : function always()
​ complete: function add()
​ done : function add()
​ error: function add()
​ fail : function add() ​getAllResponseHeaders
: function getAllResponseHeaders()
​ getResponseHeader : function getResponseHeader(t)
​ overrideMimeType: function overrideMimeType(t)
​ pipe : function then()
​ progress: function add()
​ promise : function promise(t)
​readyState
:
4
responseJSON: Object { message: "The given data was invalid.", errors: {…}
}
responseText: "{\"message\":\"The given data was invalid.\",\"errors\":{\"email\":[\"These credentials do not match our records.\"]}} "
​setRequestHeader
: function setRequestHeader(t, e)
​ state : function state()
​status
: 422
​statusCode
: function statusCode(t)
​statusText
: "Unprocessable Entity"
​success
: function add()
​ then : function then( )
​ : Object { ... }

I understand that in LoginController you need to override the login method so that you can track the result normally. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
serNevajno, 2020-02-26
@serNevajno

Solution:
In the LoginController class:

/* Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLoginResponse(Request $request) {
        $this->clearLoginAttempts($request);

        return response()->json(['SUCCESS' => 'AUTHENTICATED'], 200);
    }

    /**
     * Get the failed login response instance.
     *
     * @return \Illuminate\Http\Response
     */
    protected function sendFailedLoginResponse() {
        return response()->json(['ERROR' => 'AUTH_FAILED'], 401);
    }

    /**
     * Error after determining they are locked out.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendLockoutResponse(Request $request) {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        return response()->json(['ERROR' => 'TOO_MANY_ATTEMPTS', 'WAIT' => $seconds], 401);
    }

J
Jedi, 2020-02-26
@PHPjedi

Learn the basics of the JS language. If you can't figure out a common mistake.
I don't understand why you're all getting into jQuery... Vanilla js will be much "cooler" .
And so...
1. We study javascript.
2. Learning to work with the console.
3. Read the validation documentation on the Laravel website.
The problem is that in Laravel everything is already ready and you don’t have to think.
The error in the console is the validator response with code 422. It's worth checking loginRequest() and what it requires. Regarding other errors, most likely here - sendLoginResponse() .
And yes - here according to the code, some Indian wrote it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question