@serNevajno

Как в Laravel+jquery: Авторизация — как сделать?

Здравствуйте, ув. сообщество. Подскажите, пожалуйста, как реализовать авторизацию в laravel с использованием 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);
    }


Консоль:
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 { … }

Я так понимаю что в LoginController нужно переопределить метод login так, что бы можно было нормально отслеживать результат. Как это сделать?
  • Вопрос задан
  • 317 просмотров
Решения вопроса 1
@serNevajno Автор вопроса
Решение:
В классе LoginController:
/* 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);
    }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@PHPjedi
Изучай основы языка JS. Раз не можешь разобраться с обыкновенной ошибкой.

Не понимаю, что вы все лезете к jQuery... Ванильный js намного будет "круче".

И так...

1. Изучаем javascript.
2. Учимся работать с консолем.
3. Читаем документацию по валидации на сайте Laravel.

Проблема в том, что в Laravel уже все готово и думать не приходится.

Ошибка в консоле, это ответ валидатора с кодом 422. Стоит проверить loginRequest() и что она требует. По поводу других ошибок, скорее всего сюда - sendLoginResponse().

И да - сюда по коду, его писал какой-то индус.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы