LoginSignup
5
4

More than 3 years have passed since last update.

laravel5.5でゲストログイン実装

Posted at

ゲストログイン方法の実装をやりたかったんです。
誰かに機能を試してもらう時、いちいちユーザー登録とか面倒かなと思いましてん。

若干わかりにくかったのでメモとして残します。

認証機能

Laravelにはお手軽で強力な認証機能が初めから使えるようになっています。

php artisan make:auth

これだけで良いとかお手軽すぎます。
あとは新規ユーザー登録してログインすれば良いだけなんですが、ここにゲストユーザーのログイン機能を付けたいと思います。

やりたいこと

公式ページにはこのように書いています。

Laravelの認証サービスにはAuthファサードでアクセスできます。クラスの最初でAuthファサードを確実にインポート>しておきましょう。次にattemptメソッドを見てみましょう。

App/Http/Controllers/Auth/LoginController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * 認証を処理する
     *
     * @return Response
     */
    public function authenticate()
    {
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // 認証に成功した
            return redirect()->intended('dashboard');
        }
    }
}

この中のAuth::attempt();で認証するみたいです。
上記の引数ではemailとpasswordを渡しています。
passwordは自動でハッシュ化されるので、そのままで良いとのこと。

とにかく認証するにも元のデータが必要なので、DBに適当にゲスト用データを入れます。
それに合うように、上記のemailとpasswordを決めてしまえば良いということです。
無理やりこんな感じにしました。

App/Http/Controllers/Auth/LoginController.php
public function authenticate()
    {
        $email = 'guest@guest.com';
        $password = 'guestpass';

        if (\Auth::attempt(['email' => $email, 'password' => $password])) {
            // 認証に成功した
            return redirect('/');
        }
        return back();
    }

ルーティングもこれに合わせて調整。

web.php
Route::get('guest', 'Auth\LoginController@authenticate')->name('login.guest');

あとはボタンを押せばこのルートに飛ぶように調整しました。

中身のメモ

このLoginControllerはAuthenticatesUsersトレイトをuseしています。
これはvendor/laravel/framework/src/Illuminate/Foundation/Auth/にあります。

上記のAuth::attempt();はどこにあるん?
と思っていたらありました。
Illuminate\Auth\SessionGuard.phpだそうです。

vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
public function attempt(array $credentials = [], $remember = false)
    {
        $this->fireAttemptEvent($credentials, $remember);

        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

        // If an implementation of UserInterface was returned, we'll ask the provider
        // to validate the user against the given credentials, and if they are in
        // fact valid we'll log the users into the application and return true.
        if ($this->hasValidCredentials($user, $credentials)) {
            $this->login($user, $remember);

            return true;
        }

        // If the authentication attempt fails we will fire an event so that the user
        // may be notified of any suspicious attempts to access their account from
        // an unrecognized user. A developer may listen to this event as needed.
        $this->fireFailedEvent($user, $credentials);

        return false;
    }

さらに上記のメソッドがIlluminate\Auth\EloquentUserProvider.phpに定義されているそうです。
どうやって見つけるんやろこれ…?

気になること

かなり力技でログインさせてますが、これはある意味やりたい放題されそうで怖いです。
ゲストユーザーだけ機能を制限するような事もするべきですよね。

一応目的のものはできました。
なんかやばそうな感じはあるので、随時また更新してきたいです。

この記事を書くに当たってこちらを参考に勉強させてもらいました。
Laravel で認証パラメータを追加する
Laravel 5.5 認証
ありがとうございました。

5
4
1

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
5
4