Created
March 21, 2025 14:38
-
-
Save newtonjob/32163e987e355fe33ee40221663b843e to your computer and use it in GitHub Desktop.
Magic login link using Laravel's `Password` broker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Notifications\Notification; | |
use SensitiveParameter; | |
class MagicLoginLink extends Notification | |
{ | |
use Queueable; | |
public function __construct(#[SensitiveParameter] protected string $token) {} | |
/** | |
* Get the notification's delivery channels. | |
*/ | |
public function via($notifiable): array | |
{ | |
return ['mail']; | |
} | |
/** | |
* Get the mail representation of the notification. | |
*/ | |
public function toMail($notifiable): MailMessage | |
{ | |
return (new MailMessage) | |
->greeting('Use this link to sign in') | |
->line("Here's a link to login to your account without a password.") | |
->line('Note that this link expires in 24 hours and can only be used once.') | |
->action('Sign in', route('magic-login', [$notifiable, 'token' => $this->token])); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MagicLoginLinkController extends Controller | |
{ | |
public function create(Request $request, User $user) | |
{ | |
$user->notify(new MagicLoginLink(Password::createToken($user))); | |
return response()->json(['message' => 'Magic login link sent.']); | |
} | |
public function store(Request $request, User $user): RedirectResponse | |
{ | |
if (! Password::tokenExists($user, $request->token)) { | |
abort(404); | |
} | |
Auth::login($user); | |
Password::deleteToken($user); | |
return redirect()->intended('dashboard'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment