takanori-matsushita / laravel-practice

http://laraveltutorial.herokuapp.com/
0 stars 0 forks source link

rails tutorial 11章をlaravelで実装 #9

Open takanori-matsushita opened 4 years ago

takanori-matsushita commented 4 years ago

branch: account-activation

takanori-matsushita commented 4 years ago

11.1 AccountActivationsリソース

AccountActivationsコントローラ

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;
  :
  : 
}
takanori-matsushita commented 4 years ago

Authのルーティングを以下のように編集する。 routes/web.php Auth::routes(['verify' => true]);

takanori-matsushita commented 4 years ago

usersコントローラーにアクセス制限をかける。 app/Http/Controllers/UsersController.php

  public function __construct()
  {
    :
    $this->middleware('verified')->except('destroy');  //destroyメソッドを除く
  }

これでログイン後にメール認証されていなければ、認証ページにリダイレクトする。

takanori-matsushita commented 4 years ago

認証ページのデザイン変更 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
takanori-matsushita commented 4 years ago

認証後にマイページへリダイレクトさせる。 app/Http/Controllers/Auth/VerificationController.php

class VerificationController extends Controller
{
  : 
  protected function redirectTo()
  {
    session()->flash('Account activated!');
    return route('users.show', \Auth::id());
  }
}
takanori-matsushita commented 4 years ago

ログイン後に認証していないとアクセスできないようにするには、middleware('verified')を利用する。 rootにアクセスした際にログインしていたら、認証ページにリダイレクトする app/Http/Controllers/StaticPagesController.php

  public function __construct()
  {
    if (\Auth::check()) {
      $this->middleware('verified', ['only' => 'home']);
    }
  }

これは、この後の13章、14章で必要な処理ため、先に実装しておく。

takanori-matsushita commented 4 years ago

11.4 本番環境でのメール送信 sendgridで実装する。 [公式]Sendgrid [日本語]Sendgrid

takanori-matsushita commented 4 years ago

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}"