Authenticate.php 1.74 KB
<?php

namespace App\Http\Middleware;

use App\Enums\UserStatusEnum;
use App\Exceptions\UserStatusException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    protected string $guard;

    /**
     * @param               $request
     * @param array<string> $guards
     * @return void
     * @throws \Illuminate\Auth\AuthenticationException
     * @throws \App\Exceptions\UserStatusException
     */
    protected function authenticate($request, array $guards): void
    {
        if (empty($guards)) {
            $guards = [NULL];
        }

        foreach ($guards as $guard) {
            $this->guard = $guard;
            if ($user = $this->auth->guard($guard)->user()) {
                if ($user->getAttribute('status') !== UserStatusEnum::ACTIVATE) {
                    throw new UserStatusException();
                }

                $this->auth->shouldUse($guard);
                return;
            }
        }

        $this->unauthenticated($request, $guards);
    }


    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @return string|null
     */
    protected function redirectTo($request): ?string
    {
        if (!$request->expectsJson()) {
            return route($this->guard . '.login');
        }

        return NULL;
    }

    /**
     * @param       $request
     * @param array $guards
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function unauthenticated($request, array $guards): void
    {
        throw new AuthenticationException('身份令牌无效', $guards, $this->redirectTo($request));
    }
}