Authentication A to Z

Draft Disclaimer: Please note that this article is currently in draft form and may undergo revisions before final publication. The content, including information, opinions, and recommendations, is subject to change and may not represent the final version. We appreciate your understanding and patience as we work to refine and improve the quality of this article. Your feedback is valuable in shaping the final release.

Language Mismatch Disclaimer: Please be aware that the language of this article may not match the language settings of your browser or device.
Do you want to read articles in English instead ?

Authentication A to Z

Login Request

php artisan make:request LoginRequest

Should produce beautiful request we will fill

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'login' => [
              'required',
              'string',
            ],
          'password' => [
            'required'
          ]
        ];
    }
}

I like calling it login field but I guess username is valid too. I wouldn't use email or phone even if authentication is using those just because in my own experience we can get to refactor the authentication column to be something else (ie from username to email) or sometimes allowing multiple columns.

Carefull when doing multiple columns for authentication. User with email [email protected] and another user with username john.cena could potentially login as user 1 leading to serious account impersonation.

<?php

namespace App\Http\Controllers;

class LoginController extends Controller {
	
	public function __invoke(LoginRequest $request) {
		$user = User::login($request->input('login'))->first();

		if (!$user) {
			throw ValidationException::withMessages([
				'login' => __('auth.failed')
			]);
		}

		if (!Hash::check($request->input('password'), $user->password)) {
			throw ValidationException::withMessages([
				'login' => __('auth.failed')
			]);
		}

		if (Hash::needsRehash($user->password)) {
			dispatch(fn () => $user->update(['password' => Hash::make($request->input('password'))]))->afterResponse();
		}

		auth()->login($user);

		if ($request->isJson()) {
				return new JsonResource($user);
		}

		return redirect()->route('user.show', $user->uuid)
				->with('success', "Welcome back, {$user->name}");
	}
}

User scope scopeLogin

<?php

namespace App\Models;

class User extends Model {
	// ...
  public function scopeLogin (Builder $query) {
	  
	}
}