Laravel 8 Мульти-аутентификация с использованием охранного пароля ПРОБЛЕМА

Я пытаюсь создать приложение Laravel с мульти-аутентификацией с использованием охранников.

Github: репозиторий

Я создал приложение Fresh Laravel 8 и добавил защиту администратора, и теперь я могу входить и выходить из системы как в административном, так и в пользовательском режимах.

На этом изображении показаны подробности того, что я сделал, вы можете пропустить и просто прочитать раздел сброса пароля администратора ниже Подробное изображение

config / auth.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],

        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 30,
            'throttle' => 30,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

Раздел сброса пароля администратора

Я добавил текущие функции в PasswordResetLinkController and NewPasswordController for admin:

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

/**
 * Returns the password broker for admins
 * 
 * @return broker
 */
protected function broker()
{
    return Password::broker('admins');
}

А затем я пошел по /admin/forget-password маршруту и ​​отправил адрес электронной почты администратора, но получил следующую ошибку: We can't find a user with that email address.

После проверки я обнаружил, что функция store из PasswordResetLinkController пытается найти адрес электронной почты администратора в users table/model. Вот хранилище функций:

/**
 * Handle an incoming password reset link request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse
 *
 * @throws \Illuminate\Validation\ValidationException
 */
public function store(Request $request)
{
    $request->validate([
        'email' => 'required|email',
    ]);

    // We will send the password reset link to this user. Once we have attempted
    // to send the link, we will examine the response then see the message we
    // need to show to the user. Finally, we'll send out a proper response.
    $status = Password::sendResetLink(
        $request->only('email')
    );

    return $status == Password::RESET_LINK_SENT
                ? back()->with('status', __($status))
                : back()->withInput($request->only('email'))
                        ->withErrors(['email' => __($status)]);
}

Как я могу заставить классы PasswordResetLinkController и NewPasswordController использовать функции guard () и broker (), которые я добавил к ним?

Извините за длинное объяснение, которое я пытался найти по этому вопросу на нескольких платформах, они используют для этого только ролевой подход. Если я не объясню подробно, некоторые могут не понять, что я пытаюсь сделать


person Hilal Najem    schedule 29.03.2021    source источник
comment
Вы можете поделиться изменениями, внесенными в config / auth.php?   -  person Prospero    schedule 29.03.2021
comment
Конечно, но вы можете получить полный репозиторий, я приложил его к вопросу.   -  person Hilal Najem    schedule 29.03.2021
comment
Добавлен файл @Prospero   -  person Hilal Najem    schedule 29.03.2021
comment
Я делаю что-то связанное, но использую Fortify. В config / fortify.php я настраиваю брокера паролей, который будет использовать Fortify, и это связано с паролем сброса множественных значений, настроенным в auth.php. В ваших файлах где это сделано?   -  person Prospero    schedule 29.03.2021
comment
Я предполагаю, что вы добавляете пакет, используя композитор, который добавляет fortify. Я не знаю, что это такое ... Можете ли вы назвать мне его имя, чтобы я мог его найти   -  person Hilal Najem    schedule 29.03.2021
comment
Вы также используете охрану в LARAVEL-8 ??? Я не могу найти подходящую документацию по этому поводу ... Есть тонны для Laravel 7 и ниже, а не для 8   -  person Hilal Najem    schedule 29.03.2021
comment
Да, я использую охрану в L8. Но я использую Fortify для аутентификации, это еще один пакет для этого. Это реализует некоторые классы, и я не могу связать его с вашим проектом, например класс PasswordBrokerManager и файл fortify.php в конфигурации   -  person Prospero    schedule 29.03.2021
comment
Хорошо, я найду пакет и добавлю его в проект после отмены последнего коммита. И я вернусь к этому вопросу, когда закончу. Спасибо @Prospero   -  person Hilal Najem    schedule 29.03.2021
comment
laracasts.com/discuss/ каналы / laravel / здесь есть кое-что, связанное с ветерком. Похоже, вам нужно использовать промежуточное ПО в маршруте вроде этого Route :: group (['middleware' = ›'auth: admin'], function () {// маршруты под администратором});   -  person Prospero    schedule 29.03.2021
comment
@Prospero Я пробовал Fortify, он не отвечает на мой вопрос .. Он рекламирует только двухфакторную аутентификацию. Я хочу отправить Reset-Password-Link администраторам с помощью уведомления по электронной почте   -  person Hilal Najem    schedule 01.04.2021
comment
Хорошо, если вы добавите Fortify (это больше, чем 2FA), теперь вы можете увидеть класс PasswordBrokerManager, верно? и файл config / fortify.php, верно?   -  person Prospero    schedule 01.04.2021
comment
Я вижу config/fortify.php, но не PasswordBrokerManager   -  person Hilal Najem    schedule 02.04.2021
comment
Дело в том, что у меня есть новое приложение Laravel, в которое я добавил стартовый комплект, а затем Foritfy. Это неправильно ?? Стоит ли снимать стартовый комплект? У вас есть список шагов, которые я должен выполнить, начиная с нового приложения composer create-project laravel/laravel example-app. @Prospero   -  person Hilal Najem    schedule 02.04.2021
comment
Нет, я думаю. Я начинаю проект с auth ui, позже добавляю Jetstream и теперь развертываю аутентификацию с Fortify. Важно то, что вы знаете, что вам нужно развернуть в качестве проекта, и знаете, какие пакеты могут предоставить вам для этих требований. Я рассказал вам о Fortify из-за своего опыта работы с вашим постом. Ниже я расскажу вам о своем решении этого вопроса. В моем случае я развертываю мультитенантное приложение Saas и использую разные модели пользователей, базы данных, представления для входа и регистрации ... и т. Д. Надеюсь, это вам поможет. В app / Actions / Fortify должен быть PasswordBrokerManager.   -  person Prospero    schedule 03.04.2021


Ответы (2)


В config / auth.php

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'tenant' => [
            'driver' => 'session',
            'provider' => 'tenant',
        ],
///
'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        'tenant' => [
            'driver' => 'eloquent',
            'model' => App\Models\Tenant\User::class,
        ],
    ],
///
'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
        'tenant' => [
            'provider' => 'tenant',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],

    ],

В файле config / fortify.php

    'passwords' => ['users','tenant'],

расширить класс PasswordBrokerManager и переопределить метод брокера, например

public function broker($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();
        if (Tenancy::getTenant()) {
            return $this->brokers[$name[1]] ?? ($this->brokers[$name[1]] = $this->resolve($name[1]));
        }
        else
            return $this->brokers[$name[0]] ?? ($this->brokers[$name[0]] = $this->resolve($name[0]));
    }

В моем случае я проверяю среду арендатора. Вы можете настроить себя по своему усмотрению, в вашем случае для администратора или пользователя.

person Prospero    schedule 03.04.2021

Поскольку вы используете Laravel Breeze, просто замените эту строку кода в методе store класса PasswordResetLinkController $ status = Password :: sendResetLink ($ request- ›only ('email'));

с этой линией

Пароль :: брокер ('admins') - ›sendResetLink ($ request-› only ('email'))

person ray kudjie    schedule 20.04.2021