norbybaru / passwordless-auth
Laravel 无密码登录 - 魔法链接
v1.2.0
2024-04-04 10:17 UTC
Requires
- php: ^8.0
- illuminate/support: ^9.52|^10.0|^11.0
Requires (Dev)
- laravel/pint: ^1.1
- nunomaduro/larastan: ^1.0|^2.0
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.5|^10.0|^11.0
README
LARAVEL 无密码认证
使用魔法链接进行 Laravel 无密码认证。
此包通过电子邮件链接实现认证,消除了用户需要输入密码进行认证的要求。相反,它利用用户的电子邮件地址将登录链接发送到他们的收件箱。用户可以通过点击此链接来安全地认证。请注意,此包不包含认证页面的用户界面;它假定应用程序的登录页面将是自定义构建的。请确保相应地搭建登录 UI 页面,以无缝集成此包。
PS. 电子邮件服务提供商必须正确设置并正常工作,以便将魔法链接发送给用户进行认证
安装
composer require norbybaru/passwordless-auth
发布配置文件
php artisan vendor:publish --provider="NorbyBaru\Passwordless\PasswordlessServiceProvider" --tag="passwordless-config"
准备数据库
发布迁移以创建所需的表
php artisan vendor:publish --provider="NorbyBaru\Passwordless\PasswordlessServiceProvider" --tag="passwordless-migrations"
运行迁移。
php artisan migrate
基本用法
准备模型
打开 User::class
模型,并确保实现 NorbyBaru\Passwordless\CanUsePasswordlessAuthenticatable::class
,并将特质 NorbyBaru\Passwordless\Traits\PasswordlessAuthenticatable::class
添加到类中
<?php namespace App\Models; ... use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use NorbyBaru\Passwordless\CanUsePasswordlessAuthenticatable; use NorbyBaru\Passwordless\Traits\PasswordlessAuthenticatable; class User extends Authenticatable implements CanUsePasswordlessAuthenticatable { ... use Notifiable; use PasswordlessAuthenticatable; ... }
准备 config/passwordless.php
打开配置文件 config/passwordless.php
- 将
default_redirect_route
更新为用户认证后默认应到达的正确路由名称,如果您有不同的路由名称而不是home
。例如。
'default_redirect_route' => 'dashboard',
- 将
login_route
更新为您的登录页面的正确路由名称,以便在无效的魔法链接的情况下将用户重定向回该页面。例如。
'login_route' => 'auth.login',
设置登录路由
更新应用程序的登录路由以向用户发送魔法链接
<?php use Illuminate\Support\Facades\Route; Route::post('login', function (Request $request) { $validated = $request->validate([ 'email' => 'required|email|exists:users', ]); $status = Passwordless::magicLink()->sendLink($validated); return redirect()->back()->with([ 'status' => trans($message) ]); });
设置邮件提供商
确保您的应用程序邮件提供商已设置并正常工作 100% 以用于 Laravel 应用程序
MAIL_MAILER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME="${APP_NAME}"
设置翻译
在您的翻译目录中添加文件 passwordless.php
并复制以下条目。根据您应用程序的需求自由更新文本。
return [ 'sent' => 'Login link sent to inbox.', 'throttled' => 'Login link was already sent. Please check your inbox or try again later.', 'invalid_token' => 'Invalid link supplied. Please request new one.', 'invalid_user' => 'Invalid user info supplied.', 'verified' => 'Login successful.', ];
高级用法
覆盖魔法链接通知
要覆盖默认通知模板,覆盖您的实现 CanUsePasswordlessAuthenticatable
接口的用户模型中的 sendAuthenticationMagicLink
方法
public function sendAuthenticationMagicLink(string $token): void { // Replace with your notification class. // eg. $this->notify(new SendMagicLinkNotification($token)); }
运行单元测试
composer test
运行代码格式化器
composer fmt