LoginSignup
8
10

More than 5 years have passed since last update.

Laravelのログインを改造してみた

Posted at

やりたいこと

システムのリニューアルのためLaravelで作っていたら、旧システムのユーザーをパスワードの変更なく移行したくなった。
なお、旧システムのパスワードは平文ではなく、謎ロジックで認証が動いているが、ロジックは移行可能とする。

どうやるか

\app\Http\Controllers\Auth\LoginController.phpを改造(カスタマイズ)する。

ログイン時に通常のLaravelの認証を通して失敗した後、独自のロジックで認証を行い、成功した場合はログインするという方向で検討。

なお、Laravelのバージョンは5.7とする。

調べる

AuthenticatesUsersを調べると
public function login(Request $request)
の中で
$this->attemptLogin($request)
がtrueを返す場合にログイン成功しているようなので、attemptLoginをオーバーライドして改造すれば良さそう。

やってみる

とりあえず独自の認証ロジックは、固定のID、パスワードで成功するかどうかで試してみる。

LoginController.php
protected function attemptLogin(Request $request)
{
    $attempted = $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );

    if (!$attempted) {
        // ここに旧ユーザー用の独自の認証を作る
        if ($request[$this->username()] == 'hoge@hoge.jp' && $request['password'] == 'fuga') {
            $user = User::where('email', $request->input($this->username()))->first();
            if ($user) {
                // 本来のパスワードに保存
                $user->password = Hash::make($request->input('password'));
                $user->save();
                // 認証が通ったらログイン処理をする
                \Auth::login($user);
                $attempted = true;
            } else {
                $attempted = false;
            }
        }
    }

    return $attempted;
}

条件をパスした後にUserオブジェクトを取得してAuth::login($user)してあげることで、ログインできた。

8
10
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
8
10