Laravel 認証(Admin)

resister

<?php

namespace Oms\Http\Controllers\Admin\Auth;

use Carbon\Carbon;
use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\View\View;
use Illuminate\Database\DatabaseManager;
use Illuminate\Foundation\Auth\RedirectsUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Oms\Domain\Timezone;
use Oms\Http\Controllers\Controller;
use Oms\Http\Requests\Admin\AdminRequest;
use Oms\Models\ActivationAdmin;
use Oms\Models\Admin;
use Oms\Models\Role;
use Oms\UseCase\Admin\Mail\ConfirmEmail;
use Throwable;

class RegisterController extends Controller
{
    use RedirectsUsers;

    /**
     * Where to redirect admins after login / registration.
     *
     * @var string
     */
    protected $redirectTo = 'admins';

    /**
     * @var ActivationAdmin
     */
    private $activationAdmin;

    /**
     * @var Admin
     */
    private $admin;

    /**
     * @var AuthManager
     */
    private $auth;

    /**
     * @var SessionManager
     */
    private $session;

    /**
     * @var Mailer
     */
    private $mailer;

    /**
     * RegisterController constructor.
     *
     * @param ActivationAdmin $activationAdmin
     * @param Admin $admin
     * @param AuthManager $auth
     * @param SessionManager $session
     * @param Mailer $mailer
     */
    public function __construct(
        ActivationAdmin $activationAdmin,
        Admin $admin,
        AuthManager $auth,
        SessionManager $session,
        Mailer $mailer
    ) {
        $this->middleware('auth:admin')->except('confirm');
        $this->admin = $admin;
        $this->activationAdmin = $activationAdmin;
        $this->auth = $auth;
        $this->session = $session;
        $this->mailer = $mailer;
    }

    /**
     * show registration form.
     *
     * @param Timezone $timezone
     * @param Role $role
     *
     * @return \Illuminate\Contracts\View\View;
     */
    public function showRegistrationForm(Timezone $timezone, Role $role): View
    {
        $allTimezone = $timezone->lists();
        $roles = $role->all();

        return view('admin.admins.register', compact('allTimezone', 'roles'));
    }

    /**
     * Handle a registration request for the application.
     *
     * @param Request|AdminRequest $request
     * @param DatabaseManager $db
     * @return RedirectResponse
     * @throws \Exception
     * @throws \Throwable
     */
    public function register(AdminRequest $request): RedirectResponse
    {
        /** @var array{role_id:int,name:string,email:string,password:string,timezone:string} */
        $updateParam = $request->only(['role_id', 'name', 'email', 'password', 'timezone']);
        $updateParam['confirmation_token'] = Str::random(40);
        $updateParam['confirmation_sent_at'] = Carbon::now();

        try {
            DB::transaction(function () use ($updateParam) {
                /** @var ActivationAdmin $activationAdmin */
                $activationAdmin = $this->activationAdmin->updateOrCreate(
                    ['email' => $updateParam['email']],
                    $updateParam,
                );

                // send confirmation mail
                $this->mailer->to($activationAdmin)->send(new ConfirmEmail($activationAdmin));
                $this->session->flash('success', 'We have sent a confirmation mail. Plese see it.');
            });
        } catch (Throwable $th) {
            report($th);

            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => 'Something went wrong. Please try again later or contact Administrator']);
        }

        return redirect($this->redirectPath());
    }

    /**
     * Confirm a email
     *
     * @param  DatabaseManager $db
     * @param  string $token
     * @return RedirectResponse
     * @throws \Exception
     * @throws \Throwable
     */
    public function confirm(DatabaseManager $db, $token): RedirectResponse
    {
        $activationAdmin = $this->activationAdmin->findByToken($token);

        if (! $activationAdmin) {
            $this->session->flash('waring', 'Invalid token');

            return redirect()->route('admin.admins');
        }

        $db->transaction(function () use ($activationAdmin) {
            $activationAdmin->update([
                'confirmed_at' => Carbon::now(),
                'confirmation_token' => '',
            ]);

            $this->auth->login($this->admin->activate($activationAdmin));
        });

        $this->session->flash('success', 'You have been confirmed and registered.');

        return redirect()->route('admin.admins');
    }
}

login

<?php

namespace Oms\Http\Controllers\Admin\Auth;

use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Oms\Http\Controllers\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = 'dashboard';

    /**
     * @var AuthManager
     */
    private $auth;

    /**
     * LoginController $auth
     *
     * @param AuthManager $auth
     */
    public function __construct(AuthManager $auth)
    {
        $this->middleware('guest:admin', ['except' => 'logout']);
        $this->redirectTo = route('admin.dashboard');
        $this->auth = $auth;
    }

    /**
     * @return RedirectResponse
     */
    public function index(): RedirectResponse
    {
        if (! $this->guard()->check()) {
            return redirect(route('admin.login'));
        }
        return redirect()->route('admin.dashboard');
    }

    /**
     * @inheritdoc
     */
    public function showLoginForm(): View
    {
        return view('admin.login');
    }

    /**
     * @inheritdoc
     */
    public function logout(Request $request): RedirectResponse
    {
        $this->guard()->logout();

        // jwt guard logout
        auth('api')->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect()->route('admin.dashboard');
    }

    /**
     * @inheritdoc
     */
    protected function guard()
    {
        return $this->auth->guard('admin');
    }
}

resetPassword

<?php

namespace Oms\Http\Controllers\Admin\Auth;

use Illuminate\Auth\AuthManager;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;
use Oms\Http\Controllers\Controller;
use Oms\Http\Requests\Admin\AdminRequest;
use Password;

class AdminResetPasswordController extends Controller
{
    use ResetsPasswords;

    private AuthManager $auth;

    /** @var $redirectTo */
    protected $redirectTo = '/login';

    public function __construct(AuthManager $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Display the password reset view for the given token.
     *
     * @param Request $request
     * @param string $token
     * @return View
     */
    public function showResetForm(Request $request, string $token): View
    {
        $this->guard()->logout();

        // jwt guard logout
        auth('api')->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return view('admin.admins.reset')->with(compact('token'));
    }

    /**
    * Reset the given user's password.
    *
    * @param AdminRequest $request
    * @return \Illuminate\Http\RedirectResponse
    */
    public function reset(AdminRequest $request)
    {
        $response = $this->broker()->reset(
            $this->credentials($request),
            function ($user, $password) {
                $this->resetPassword($user, $password);
            }
        );

        return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($request, $response)
                : $this->sendResetFailedResponse($request, $response);
    }

    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('admins');
    }

    /**
     * @inheritdoc
     */
    protected function guard()
    {
        return $this->auth->guard('admin');
    }
}

forgot

<?php

namespace Oms\Http\Controllers\Admin\Auth;

use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Oms\Http\Controllers\Controller;
use Oms\Models\Admin;

class AdminForgotPasswordController extends Controller
{
    use SendsPasswordResetEmails;

    /**
     * Where to redirect admins after login / registration.
     *
     * @var string
     */
    protected $redirectTo = 'dashboard';

    /**
     * @var Admin
     */
    private $admin;

    /**
     * UsersController constructor.
     *
     * @param Admin $admin
     * @internal param Factory $validator
     */
    public function __construct(Admin $admin)
    {
        $this->middleware('auth:admin');
        $this->admin = $admin;
    }

    /**
     * Send a reset link to the given user.
     *
     * @param  Request $request
     * @param Admin $admin
     * @return RedirectResponse
     */
    public function sendResetLinkEmail(Request $request, Admin $admin): RedirectResponse
    {
        $response = $this->broker()->sendResetLink([
            'email' => $admin->email,
        ]);

        return $response == Password::RESET_LINK_SENT
            ? $this->sendResetLinkResponse($request, $response)
            : $this->sendResetLinkFailedResponse($request, $response);
    }

    public function broker()
    {
        return Password::broker('admins');
    }
}

コメント

タイトルとURLをコピーしました