LoginSignup
1
3

More than 5 years have passed since last update.

laravel Auth 会員登録

Last updated at Posted at 2018-12-21

流れ

・ログイン機能をつける
・パスワードを平文にする
・メール認証もつける

[参考]
導入
https://www.terakoya.work/laravel-make-auth-exec-flow/

パスワードを平文で保存
https://nobuhiroharada.com/2018/05/22/auth-login-plain-text/

メール認証
https://blog.capilano-fw.com/?p=1099

初期設定

config/app.php


'email' => env('APP_EMAIL', 'info@your.com'),

を追加。
また、URLやNAMEなども設定しておく。
そして、同じ値を .env にも記載。

その後


php artisan config:cache

でキャッシュをクリアずる。

ログイン機能をつけよう


php artisan make:auth

テーブルを作ろう


--
-- テーブルの構造 `users`
--

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `email` text NOT NULL,
  `email_verified_at` timestamp NULL DEFAULT NULL,
  `name` text NOT NULL,
  `password` varchar(60) NOT NULL,
  `reminder_token` text DEFAULT NULL,
  `remember_token` text DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
COMMIT;

ついでにパスワードリセット用テーブルも作成


--
-- テーブルの構造 `password_resets`
--

CREATE TABLE `password_resets` (
  `email` varchar(255) DEFAULT NULL,
  `token` varchar(255) DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
COMMIT;


以上で完了。

にアクセスしてログインページが表示されるか確認。

パスワードを平文にしよう

app/Http/Controllers/Auth/RegisterController.php 60行目らへん

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => $data['password'],
    ]);
}

vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php130行目らへん

public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];

    return ($plain === $user->getAuthPassword());
}


注意
composer update などをすると コアファイルが変わってしまう。
よって以下のエラーが出るようになるので、updateしたら必ず確認し、変更すること。

These credentials do not match our records.

以上で暗号化無しの平文化完了。

メール認証及び日本語化

app/User.php

class User extends Authenticatable implements MustVerifyEmail
{
    // 省略
}

Email Verificationを使うためにMustVerifyEmailと追加。

//Auth::routes();
Auth::routes(['verify' => true]);//変更

Route::middleware('verified')->group(function() {

    // 本登録ユーザーだけ表示できるページ
    Route::get('verified',  function(){

        return '本登録が完了してます!';

    });

});

テスト登録

https://sample.test/register
で登録。

https://sample.test/verified
へアクセス

「メールアドレスの認証をお願いします。もしメールを受け取ってないなら、ここをクリックしてください」

という英文が表示されていますね。

では届いたメールをクリックしてみましょう。

https://sample.test/verified
すると web.php に設定した"本登録が完了しています"が表示されます。

日本語化

resources/views/auth/verify.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">本登録</div>

                <div class="card-body">
                    @if (session('resent'))
                        <div class="alert alert-success" role="alert">
                            新しい本登録メッセージが送信されました。
                        </div>
                    @endif

                    メールアドレスの認証をお願いします。<br>
                    もしメールを受け取ってないなら、<a href="{{ route('verification.resend') }}">ここをクリックしてください</a>。
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

本登録メールを日本語化する


php artisan make:notification VerifyEmailJapanese

app/Notifications/VerifyEmailJapanese.php

<?php

namespace App\Notifications;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class VerifyEmailJapanese extends Notification
{
    /**
     * The callback that should be used to build the mail message.
     *
     * @var \Closure|null
     */
    public static $toMailCallback;

    /**
     * Get the notification's channels.
     *
     * @param  mixed  $notifiable
     * @return array|string
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Build the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        if (static::$toMailCallback) {
            return call_user_func(static::$toMailCallback, $notifiable);
        }

        return (new MailMessage)
            ->subject(Lang::getFromJson('本登録メール'))
            ->line(Lang::getFromJson('以下の認証リンクをクリックして本登録を完了させてください。'))
            ->action(
                Lang::getFromJson('メールアドレスを認証する'),
                $this->verificationUrl($notifiable)
            )
            ->line(Lang::getFromJson('もしこのメールに覚えが無い場合は破棄してください。'));
    }

    /**
     * Get the verification URL for the given notifiable.
     *
     * @param  mixed  $notifiable
     * @return string
     */
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
            'verification.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );
    }

    /**
     * Set a callback that should be used when building the notification mail message.
     *
     * @param  \Closure  $callback
     * @return void
     */
    public static function toMailUsing($callback)
    {
        static::$toMailCallback = $callback;
    }
}

app/User.php

// Override
public function sendEmailVerificationNotification()
{
    $this->notify(new \App\Notifications\VerifyEmailJapanese);
}


以上で完了!

web.php の挙動


//ログインしていないと表示させない
Route::middleware('auth')->group(function() {
    Route::match(['get', 'post'] , '/nikki/loginnomi/', 'NikkiController@loginnomi');
});


//ログインしている 且つ、 メール認証していないと表示させない
Route::middleware('verified')->group(function() {
    Route::match(['get', 'post'] , '/nikki/ninsyou/', 'NikkiController@ninsyou');
    Route::get('verified',  function(){
        return '本登録が完了してます!';
    });

});


ログアウトへ飛ぶとエラーになる

web.phpに追加


Route::match(['get', 'post'] , '/logout/', 'Auth\LoginController@logout');



validateのパスワード数を変更したい

/RegisterController.php の 50行目らへんを変更


    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:4|confirmed',
        ]);
    }


また、パスワードのリセット時のバリデートも変更する必要があるので、
https://qiita.com/ma7ma7pipipi/items/479ecc4a49ea7fd059ba
を参考にする。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3