Home >PHP Framework >Laravel >Share 9 tips related to Laravel Auth scaffolding

Share 9 tips related to Laravel Auth scaffolding

藏色散人
藏色散人forward
2020-08-27 13:42:433085browse

The following is the Share 9 tips related to Laravel Auth scaffolding tutorial column to share with you 9 tips related to Share 9 tips related to Laravel Auth scaffolding Auth scaffolding, I hope it will be helpful to friends in need!

Share 9 tips related to Laravel Auth scaffolding

#Share 9 tips related to Laravel Auth scaffolding has a great ready-made user authentication system, of course we also need to customize some configurations in some places. For some custom configurations, we don't need to find an extension pack or write a lot of code. Let’s take a look at the interesting features hidden behind this authentication system.

Tip 1. Auth::routes() parameters

We should all know the method Auth::routes() comes from Share 9 tips related to Laravel Auth scaffolding UI package (Before Share 9 tips related to Laravel Auth scaffolding 7, it was included in the kernel).

But did you know it can accept an array to enable/disable specific authentication routes?

For Share 9 tips related to Laravel Auth scaffolding 7, here are the available parameters and their default values:

Auth::routes([
    'login'    => true, 
    'logout'   => true, 
    'register' => true, 
    'reset'    => true,   // 用于重置密码
    'confirm'  => false,  // 用于额外的密码确认
    'verify'   => false,  // 用于邮箱认证
]);

These parameters only enable or disable certain routes.

To understand how they work, you can check out the documentation AuthRouteMethods in Share 9 tips related to Laravel Auth scaffolding UI:

return function ($options = []) {
    // 登录路由...
    if ($options['login'] ?? true) {
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
    }

    // 登出路由...
    if ($options['logout'] ?? true) {
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');
    }

    // 注册路由...
    if ($options['register'] ?? true) {
        $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('register', 'Auth\RegisterController@register');
    }

    // 密码重设路由...
    if ($options['reset'] ?? true) {
        $this->resetPassword();
    }

    // 密码确认路由...
    if ($options['confirm'] ??
        class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) {
        $this->confirmPassword();
    }

    // 邮箱验证路由...
    if ($options['verify'] ?? false) {
        $this->emailVerification();
    }
};

Tip 2. Share 9 tips related to Laravel Auth scaffolding UI: Generate Controllers Only

The official documentation specifies the main ways to use Share 9 tips related to Laravel Auth scaffolding UI:

php artisan ui vue --auth

But what if you don't need a visual UI? What if you create an API-only project without any frontend in the framework?

You can still use Share 9 tips related to Laravel Auth scaffolding Auth and its controllers. Install Share 9 tips related to Laravel Auth scaffolding UI and run the following command:

php artisan ui:controllers

It will only generate app/Http/Controllers/Auth , so you don't need Blade or Vue files to use them.

See the implementation of this Artisan command in the Github repository.


Tip 3. Reauthenticate passwords for sensitive operations

Have you ever maintained a Github repository and tried to change its access settings? Github then asks you to enter your password again to make sure it's really you.

Starting from Share 9 tips related to Laravel Auth scaffolding 6.2, this feature is also integrated in the framework.

Share 9 tips related to Laravel Auth scaffolding

You only need to add a middleware called password.confirm to the route you want to protect.

Route::get('/secrets', 'SecretsController@show')->middleware('password.confirm');

Dries Vints Quoted from the official feature release article:

If you try to access this route, you will be prompted to confirm your password, and Same as seen on other applications like GitHub.

After confirming the password, a timestamp is stored in the user session by default. The timestamp lasts for 3 hours, so the user does not have to enter their password again during this time.

You can customize this duration using the password_timeout configuration option in the auth configuration file.


Tip 4. Sign out of other devices

As of Share 9 tips related to Laravel Auth scaffolding 5.6, we provide a separate method to automatically sign out of any other device logged in with our account or Browser:

Auth::logoutOtherDevices($password);

Typical usage is to log out of other devices after successfully logging in to the current device. To do this, we override method authenticated() from TraitAuthenticatesUsers.php and put it into app/Http/Controllers/Auth/LoginController.php中:

protected function authenticated(Request $request, $user)
{
    \Auth::logoutOtherDevices(request('password'));
}

Also, don’t forget to activate the middleware AuthenticateSession in the app/Http/Kernel.php file, which is commented out by default :

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

Redirect after login/registration: Custom logic

By default, Share 9 tips related to Laravel Auth scaffolding's LoginController and RegisterController have the same properties:

class RegisterController extends Controller
{
    protected $redirectTo = RouteServiceProvider::HOME;

So , you can specify the URL to redirect to after successful login/registration. The default value is in app/Providers/RouteServiceProvider.php:

class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/home';

How to customize it?

First, you can specify other values ​​for the $redirectTo properties of the login and registration controllers respectively.

But what if you have more complex dynamic redirection logic that needs to be judged based on user role, for example?

您可以在身份验证控制器中创建一个redirectTo()方法,然后在其中指定条件。该方法将覆盖$ redirectTo属性的任何值。

参见示例:

class RegisterController extends Controller
{
    protected $redirectTo = RouteServiceProvider::HOME;

    protected function redirectTo()
    {
        if (auth()->user()->role_id == 1) {
            return '/admin';
        }
        return '/home';
    }

技巧 5. 快速创建新用户

如果您需要创建一个新用户,但还没有准备好注册页面该怎么办?

只需在您的终端中打开 Share 9 tips related to Laravel Auth scaffolding Tinker

php artisan tinker

如果您不熟悉 Tinker,需要知道它是能够执行任何 Share 9 tips related to Laravel Auth scaffolding / PHP 代码的命令行工具。因此,在其中,您可以轻松创建用户,键入此 Eloquent 命令并按 Enter:

\App\User::create(['name' => 'Admin', 'email' => 'admin@admin.com', 'password' => bcrypt('somesecurepassword')]);

但是,如果您需要创建许多用户进行测试,例如10、100或1000,该怎么办?没问题,我们可以在database / factories / UserFactory.php中使用 Share 9 tips related to Laravel Auth scaffolding 默认提供的 Factory 类:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // 密码
        'remember_token' => Str::random(10),
    ];
});

这些是我们创建的“假”用户的默认值。为此,我们将生成一个 Seeder 文件:

php artisan make:seeder UsersSeeder

然后,我们打开生成的文件database / seeds / UsersSeeder.php,并用以下代码填充run()方法:

public function run()
{
    // This will create 100 users
    factory(App\User::class, 100)->create(); 
}

要运行它,我们需要执行以下命令:

php artisan db:seed --class=UsersSeeder

您可以在Share 9 tips related to Laravel Auth scaffolding官方文档中了解更多有关数据库种子的信息。


Tip 6. 使用邮箱和/或用户名登录

默认情况下,Share 9 tips related to Laravel Auth scaffolding用户使用邮箱密码进行身份验证。但是,如果您的用户标识不使用邮箱怎么办?例如,使用用户名作为标识。

您可以通过覆盖 traitAuthenticatesUsers.php中的一种方法来轻松更改它。

这是默认值:

trait AuthenticatesUsers
{
    // ... 其他方法

    public function username()
    {
        return 'email';
    }

您可以将其复制到您的LoginController.php中,只需更改值即可:

class LoginController extends Controller
{
    use AuthenticatesUsers;

    // ... 其他方法

    public function username()
    {
        return 'username';
    }
}

让我们更进一步。如果您想让用户可以使用邮箱或用户名登录怎么办?这样的话,用户可以在“邮箱/用户名”字段中选择其中一个填写。

让我们向上面的username()方法添加一个判断。我们检查输入的字符串是否是电子邮件,若不是,则将其视为用户名。这是一个 PHP 函数,甚至不是 Share 9 tips related to Laravel Auth scaffolding 函数。

class LoginController extends Controller
{
    // ...

    public function username()
    {
        return filter_var(request('email'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
    }
}

注意: 别忘了把登录表单的  input type="email" 改成 type="text"


Tip 7.登录请求频繁:自定义参数

如果您尝试在同一分钟内使用无效凭据登录五次以上,则请求会被拦截,并显示一条消息尝试登录的次数过多。 请在X秒后重试。

该拦截操作将持续1分钟,并且对于用户的用户名/电子邮件及其IP地址是唯一的。

您可以自定义这些参数:

  • 一分钟内的无效尝试次数(默认为五次尝试)
  • 阻止登录的分钟数(默认为1分钟)

这两个参数在TraitThrottlesLogins内部:

trait ThrottlesLogins
{
    // ... other methods

    /**
     * Get the maximum number of attempts to allow.
     *
     * @return int
     */
    public function maxAttempts()
    {
        return property_exists($this, 'maxAttempts') ? $this->maxAttempts : 5;
    }

    /**
     * Get the number of minutes to throttle for.
     *
     * @return int
     */
    public function decayMinutes()
    {
        return property_exists($this, 'decayMinutes') ? $this->decayMinutes : 1;
    }
}

因此,要覆盖这些属性,可以在 LoginController 内部指定属性:

class LoginController extends Controller
{
    protected $maxAttempts = 3;  // Default is 5
    protected $decayMinutes = 2; // Default is 1

    // ...
}

Tip 8. 注册: 禁用自动登录

默认情况下,新注册的用户将自动登录并重定向到主页。

如果您需要禁用该功能并改为显示注册成功页面,而不自动登录的话,可以执行以下操作。

原始注册方法位于 Trait RegistersUsers 的内部:

trait RegistersUsers
{
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        if ($response = $this->registered($request, $user)) {
            return $response;
        }

        return $request->wantsJson()
                    ? new Response('', 201)
                    : redirect($this->redirectPath());
    }

因此,您的目标是在RegisterController中覆盖它,然后重定向到新页面,而不是登录:

class RegisterController extends Controller
{
    use RegistersUsers;

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        return redirect()->route('your_success_page_route_name');
    }

Tip 9. 登录: 通过电子邮件/密码进行附加检查

如果除了默认的电子邮件和密码外,还需要进行其他检查,该怎么办? 例如,您要检查用户是否处于活动状态或未被禁止。

您可以添加额外的字段 credentials 到定义在 AuthenticatesUsers trait 的鉴权数组中:

trait AuthenticatesUsers
{
    // ...

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

然后只需要重写 LoginController 即可:

class LoginController extends Controller
{
    // ...

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password') + ['is_active' => 1];
    }

注意: 这是一个很有趣的便捷提示,但是我建议您在单独的中间件中执行这种额外的检查,然后向用户提供更明确的错误消息,而不是默认的凭证错误。


就是这些,都是一些便捷提示,但是自定义代码和外部扩展包还有很多可以发挥的地方。 因此,可以继续关注有关该主题的更多文章!

原文地址:https://laravel-news.com/laravel-auth-tips

译文地址:https://learnku.com/laravel/t/48905

The above is the detailed content of Share 9 tips related to Laravel Auth scaffolding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete