「基礎から学ぶLaravel」の感想・備忘録2

スポンサーリンク

認証

Laravel Breezeのインストール

Laravel Breezeをインストールことで認証機能を簡単に実装することができる。

  1. sail composer require laravel/breeze --dev
  2. sail artisan breeze:install
  3. http://localhost/registerでアクセス

ガードとプロバイダ

  • config/auth.phpにガードとプロバイダが定義されている。
  • ガードとは認証が複数ある場合に識別するための名前で、例えば管理者用の認証であればadminというガードを用意する。
  • プロバイダとはユーザー情報の保存先のことであるが、通常はModelクラスを指定する。
  • Laravelに最初から用意されているUserモデルはAuthenticatable(Illuminate\Foundation\Auth\User)を継承している。
    Authenticatableを継承したクラスは認証用のモデルとして使用できるようになる。
'guards' => [
    'web' => [ // ガードの名前
        'driver' => 'session', // 認証方法=tokenなども指定できるが通常はsession
        'provider' => 'users', // プロバイダ
    ],
],
'providers' => [
    'users' => [ // プロバイダの名前
        'driver' => 'eloquent', // eloquent以外にすることはまずない
        'model' => App\Models\User::class,
    ],
],

ユーザー登録処理の流れ

app/Http/Controllers/Auth/RegisteredUserController.phpのstoreメソッドにユーザー登録処理がある。

public function store(Request $request): RedirectResponse
{
  // Rules\Password::defaults()はデフォルトのパスワードルール=8文字以上
  // 変更する場合はRules\Password::min(10)->mixedCase()など
  $request->validate([
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'string', 'email', 'max:255', 'unique:'.User::class],
    'password' => ['required', 'confirmed', Rules\Password::defaults()],
  ]);

  $user = User::create([
    'name' => $request->name,
    'email' => $request->email,
    'password' => Hash::make($request->password),
  ]);

  // イベントの発火
  // app/Providers/EventServiceProvider.phpでSendEmailVerificationNotificationリスナが登録されている
  // ただし、デフォルトではメールは送信されない。UserモデルでMustVerifyEmailをimplementsすると送信されるようになる
  event(new Registered($user));

  // ログイン済みとする
  Auth::login($user);

  return redirect(RouteServiceProvider::HOME);
}

確認メールを送信する場合

use Illuminate\Contracts\Auth\MustVerifyEmail; // デフォルトではコメントアウトされている
// 〜省略〜
class User extends Authenticatable implements MustVerifyEmail
{

ユーザー認証処理の流れ

app/Http/Controllers/Auth/AuthenticatedSessionController.phpのstoreメソッドにユーザー認証処理がある。

public function store(LoginRequest $request): RedirectResponse
{
  // LoginRequestのauthenticateメソッドをコール
  $request->authenticate();

  $request->session()->regenerate();

  return redirect()->intended(RouteServiceProvider::HOME);
}
public function authenticate(): void
{
  $this->ensureIsNotRateLimited();

  // emailとpasswordで認証。rememberは「Remember me」のチェック状態
  if (!Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
    // 連続失敗の制御
    RateLimiter::hit($this->throttleKey());

    throw ValidationException::withMessages([
      'email' => trans('auth.failed'),
    ]);
  }
  // 連続失敗回数をクリア
  RateLimiter::clear($this->throttleKey());
}

認証用のルーティング

// authミドルウェア=未認証の場合はログイン画面にリダイレクト
// verifiedミドルウェア=メアド確認ができていない場合は'verification.notice'ルートにリダイレクト
// ミドルウェアの設定はapp/Http/Kernel.phpにある
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';
// guestミドルウェア=認証済みの場合はダッシュボード画面にリダイレクト
Route::middleware('guest')->group(function () {
// 〜省略〜
}
Route::middleware('auth')->group(function () {
// 〜省略〜
}

コメント