Open takanori-matsushita opened 4 years ago
Laravel Authには認証の機能も用意されているため、そちらを利用する。
Userモデルの修正 app/User.php
use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmailContract
{
use MustVerifyEmail, Notifiable;
:
:
}
Authのルーティングを以下のように編集する。
routes/web.php
Auth::routes(['verify' => true]);
usersコントローラーにアクセス制限をかける。 app/Http/Controllers/UsersController.php
public function __construct()
{
:
$this->middleware('verified')->except('destroy'); //destroyメソッドを除く
}
これでログイン後にメール認証されていなければ、認証ページにリダイレクトする。
認証ページのデザイン変更 resources/views/auth/verify.blade.php
@php
$title = 'Verify'
@endphp
@extends('layouts.layout')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header bg-dark text-white">{{ __('Verify Your Email Address') }}</div> //class追加
:
@endsection
認証後にマイページへリダイレクトさせる。 app/Http/Controllers/Auth/VerificationController.php
class VerificationController extends Controller
{
:
protected function redirectTo()
{
session()->flash('Account activated!');
return route('users.show', \Auth::id());
}
}
ログイン後に認証していないとアクセスできないようにするには、middleware('verified')を利用する。 rootにアクセスした際にログインしていたら、認証ページにリダイレクトする app/Http/Controllers/StaticPagesController.php
public function __construct()
{
if (\Auth::check()) {
$this->middleware('verified', ['only' => 'home']);
}
}
これは、この後の13章、14章で必要な処理ため、先に実装しておく。
11.4 本番環境でのメール送信 sendgridで実装する。 [公式]Sendgrid [日本語]Sendgrid
Sendgridに登録
Sendgridのメール設定は、WebAPIの方法もあるがSTMPのほうが簡単そうだったため、.env
ファイルのメール設定を以下のようにする。
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=登録時に発行されるユーザーID
MAIL_PASSWORD=登録パスワード
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=FROMメールアドレス
MAIL_FROM_NAME="${APP_NAME}"
branch: account-activation