라라벨 9에서 매직링크로 어떻게 로그인하나요?
32331 단어 beginnersprogramminglaravelwebdev
코드 편집기에서 코드 프로젝트를 열고 아래 단계를 따릅니다.
1 단계
매직링크로 로그인 비밀번호를 덜 만들기 위해 저희Laravel Password Less패키지로 갑니다.
작성기 명령을 실행하기만 하면 됩니다.
composer require grosv/laravel-passwordless-login
2 단계
로그인 보기 파일을 변경하고
resources/views/auth/login.blade.php
를 열고 아래 코드를 업데이트합니다.@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
@csrf
@if (session('message'))
<div class="alert alert-info">{{ session('message') }}</div>
@endif
<div class="row mb-3">
<label for="username" class="col-md-4 col-form-label text-md-end">{{ __('Username') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" name="submit" class="btn btn-primary" value="login">
{{ __('Login') }}
</button>
or
<button type="submit" class="btn btn-secondary" name="submit" value="magic-link">
{{ __('Send Magic Link') }}
</button>
</div>
</div>
<div class="row mb-0 mt-3">
<div class="col-md-8 offset-md-4">
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
<a class="btn btn-link" href="{{ route('otp.login') }}">
{{ __('Login With OTP.') }}
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
3단계
업데이트
app/Http/Controllers/Auth/LoginControlller.php
로그인 추가 및 Magic Link 기능으로 로그인<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Notifications\SendMagicLinkNotification;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'username';
}
public function login(Request $request)
{
if($request->input('submit') == 'magic-link'){
$user = $this->loginViaMagicLink($request);
if(!$user){
return redirect()->route('login')
->withErrors(['username' => 'User with this username does not exist.'])
->withInput();
}
return redirect()->route('login')
->withMessage('Magic Link Sent to the registered email ID.');
}
$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)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
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);
}
public function loginViaMagicLink(Request $request)
{
$user = User::where('username', $request->input('username'))->first();
if ($user) {
$user->notify(new SendMagicLinkNotification());
}
return $user;
}
}
4단계
등록된 이메일에 매직링크를 보내는 알림을 생성합니다.
php artisan make:notification SendMagicLinkNotification
알림을 만든 후
app/Notifications
에서 알림을 열고 아래 코드를 업데이트합니다.<?php
namespace App\Notifications;
use Grosv\LaravelPasswordlessLogin\LoginUrl;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class SendMagicLinkNotification extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$generator = new LoginUrl($notifiable);
$generator->setRedirectUrl('/home');
$url = $generator->generate();
return (new MailMessage)
->subject('Your Login Magic Link!')
->line('Click this link to log in!')
->action('Login', $url)
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
이제 로그인 페이지를 방문하면 로그인 페이지에 매직 링크 버튼이 표시됩니다.
매직 링크 보내기를 누르면 다음과 같은 이메일을 받게 됩니다.
LARAVEL 9에서
MAGIC LINK
로 로그인하는 데 도움이 되었으면 합니다.YouTube에서 동영상 자습서를 완료하세요.
구현하는 동안 문제가 발생하면 질문을 댓글로 남겨주세요.
읽어 주셔서 감사합니다
나에게 연락하십시오.
Reference
이 문제에 관하여(라라벨 9에서 매직링크로 어떻게 로그인하나요?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/techtoolindia/how-to-login-with-magic-link-in-laravel-9-3c3j텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)