Laravel Breeze를 커스텀하다.

김문범·2021년 8월 10일
2

라라벨 CMS 부품들

목록 보기
4/4
post-thumbnail

라라벨 브리즈를 설치하여, 이메일 로그인 방식을 아이디 로그인 방식으로 변환하는 방법에 대하여 작성함.

1. laravel 설치

  1. composer create-project laravel/laravel [원하는 폴더명]
  2. cd [원하는 폴더명]
  3. php artisan serve

위와 같은 절차를 진행하면, 설치 및 아래와 같은 화면을 보게된다.


2. 데이터베이스 설정

.env 파일을 확인하여 아래의 사진과 같은 부분을 설정함.

추가적으로 MySQL / MariaDB의 경우 MySQL 5.7.7의 이전 버전과 MariaDB 10.2.2의 이전 버전의 경우는 App/Providers/AppServiceProvider.php를 찾아서 아래의 사진과 같은 처리를 해야 오류가 생기지 않음.

Schema::defaultStringLength(191);를 추가함.


3. 마이그레이션 파일 수정

Database/migrations/2014_10_12_000000_create_users_table.php라는 파일을 찾아서 수정을 한다.

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Custom and Add Code
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('user_id')->unique()->comment('사용자 아이디');
            $table->string('name')->comment('사용자 이름');
            $table->string('email')->comment('사용자 이메일');
            $table->timestamp('email_verified_at')->nullable()->comment('사용자 이메일 인증');
            $table->string('password')->comment('사용자 비밀번호');
            $table->rememberToken();
            $table->timestamps();
        });

        DB::statement("ALTER TABLE users COMMENT='회원정보'");

        /*
         * Basic example
         *
         * Schema::create('users', function (Blueprint $table) {
         *     $table->id();
         *     $table->string('name');
         *     $table->string('email')->unique();
         *     $table->timestamp('email_verified_at')->nullable();
         *     $table->string('password');
         *     $table->rememberToken();
         *     $table->timestamps();
         * });
        */
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

수정 후에 php artisan migrate를 터미널에서 실행한다. 그러면, DB에 table이 생성된다.


4. Laravel Breeze 설치

  1. cd [laravel이 설치된 폴더]
  2. composer require laravel/breeze --dev
  3. php artisan breeze:install
  4. npm install
  5. npm run dev

위와 같은 순서로 터미널에서 실행하면, 아래와 같은 우측 대각선에 Log in 및 Register의 링크가 생성됨.


5. register 관련 내용 수정

5-1. register.blade.php 수정

위치 : resources/views/auth/register.blade.php

<x-guest-layout>
    <x-auth-card>
        <x-slot name="logo">
            <a href="/">
                <x-application-logo class="w-20 h-20 fill-current text-gray-500"/>
            </a>
        </x-slot>

        <!-- Validation Errors -->
        <x-auth-validation-errors class="mb-4" :errors="$errors"/>

        <form method="POST" action="{{ route('register') }}">
        @csrf

        <!-- User Id(Custom and Add Code) -->
            <div>
                <x-label for="userId" :value="__('User Id')"/>

                <x-input id="userId" class="block mt-1 w-full" type="text" name="user_id" :value="old('user_id')"
                         required
                         autofocus/>
            </div>

            <!-- Name -->
            <div>
                <x-label for="name" :value="__('Name')"/>

                <x-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required/>
            </div>

            <!-- Email Address -->
            <div class="mt-4">
                <x-label for="email" :value="__('Email')"/>

                <x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required/>
            </div>

            <!-- Password -->
            <div class="mt-4">
                <x-label for="password" :value="__('Password')"/>

                <x-input id="password" class="block mt-1 w-full"
                         type="password"
                         name="password"
                         required autocomplete="new-password"/>
            </div>

            <!-- Confirm Password -->
            <div class="mt-4">
                <x-label for="password_confirmation" :value="__('Confirm Password')"/>

                <x-input id="password_confirmation" class="block mt-1 w-full"
                         type="password"
                         name="password_confirmation" required/>
            </div>

            <div class="flex items-center justify-end mt-4">
                <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('login') }}">
                    {{ __('Already registered?') }}
                </a>

                <x-button class="ml-4">
                    {{ __('Register') }}
                </x-button>
            </div>
        </form>
    </x-auth-card>
</x-guest-layout>

5-2. User 모델 수정

위치 : app/Models/User.php

protected $fillable = [
        'user_id', // Custom and Add Code
        'name',
        'email',
        'password',
    ];

5-3. RegisteredUserController 수정

위치 : app/Http/Controllers/Auth/RegisteredUserController.php

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|string|max:255|unique:users', // Custom and Add Code
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user = User::create([
            'user_id' => $request->user_id, // Custom and Add Code
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        /*
         * Basic Example
         *
         * $request->validate([
         *     'name' => 'required|string|max:255',
         *     'email' => 'required|string|email|max:255|unique:users',
         *     'password' => ['required', 'confirmed', Rules\Password::defaults()],
         * ]);
         *
         * $user = User::create([
         *     'name' => $request->name,
         *     'email' => $request->email,
         *     'password' => Hash::make($request->password),
         * ]);
        */

        event(new Registered($user));

        Auth::login($user);

        return redirect(RouteServiceProvider::HOME);
    }
}

6. login 관련 수정

6-1. login.blade.php 수정

위치 : resources/views/auth/login.blade.php

<x-guest-layout>
    <x-auth-card>
        <x-slot name="logo">
            <a href="/">
                <x-application-logo class="w-20 h-20 fill-current text-gray-500"/>
            </a>
        </x-slot>

        <!-- Session Status -->
        <x-auth-session-status class="mb-4" :status="session('status')"/>

        <!-- Validation Errors -->
        <x-auth-validation-errors class="mb-4" :errors="$errors"/>

        <form method="POST" action="{{ route('login') }}">
        @csrf

        <!-- User Id(Custom and Add Code) -->
            <div>
                <x-label for="userId" :value="__('User Id')"/>

                <x-input id="userId" class="block mt-1 w-full" type="text" name="user_id" :value="old('user_id')"
                         required
                         autofocus/>
            </div>

            <!-- Password -->
            <div class="mt-4">
                <x-label for="password" :value="__('Password')"/>

                <x-input id="password" class="block mt-1 w-full"
                         type="password"
                         name="password"
                         required autocomplete="current-password"/>
            </div>

            <!-- Remember Me -->
            <div class="block mt-4">
                <label for="remember_me" class="inline-flex items-center">
                    <input id="remember_me" type="checkbox"
                           class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                           name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900"
                       href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-button class="ml-3">
                    {{ __('Log in') }}
                </x-button>
            </div>
        </form>
    </x-auth-card>
</x-guest-layout>

6-2. LoginRequest.php 수정

위치 : app/Http/Requests/Auth/LoginRequest.php

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // 'email' => 'required|string|email',
            'user_id' => 'required|string', // Custom and Add Code
            'password' => 'required|string',
        ];
    }

    /**
     * Attempt to authenticate the request's credentials.
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function authenticate()
    {
        $this->ensureIsNotRateLimited();

        // if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
        if (! Auth::attempt($this->only('user_id', 'password'), $this->boolean('remember'))) { // Custom and Add Code
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                // 'email' => __('auth.failed'),
                'user_id' => __('auth.failed'), // Custom and Add Code
            ]);
        }

        RateLimiter::clear($this->throttleKey());
    }

    /**
     * Ensure the login request is not rate limited.
     *
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function ensureIsNotRateLimited()
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
            return;
        }

        event(new Lockout($this));

        $seconds = RateLimiter::availableIn($this->throttleKey());

        throw ValidationException::withMessages([
            // 'email' => trans('auth.throttle', [
            'user_id' => trans('auth.throttle', [ // Custom and Add Code
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }

    /**
     * Get the rate limiting throttle key for the request.
     *
     * @return string
     */
    public function throttleKey()
    {
        // return Str::lower($this->input('email')).'|'.$this->ip();
        return Str::lower($this->input('user_id')).'|'.$this->ip(); // Custom and Add Code
    }
}

이상으로 여기까지의 절차를 진행하면, 아이디 로그인 방식으로 변경됨.

profile
다양하지만 공부할 것이 많은 개발자입니다.

0개의 댓글