AuthController.php

mail@pastecode.io avatar
unknown
php
7 months ago
1.8 kB
3
Indexable
Never
<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\CheckAppError;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Services\AuthService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{

    protected $authService;

    // change to authService
    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(LoginRequest $request): JsonResponse
    {
        $data = $request->safe()->only(['email', 'password']);

        $guard = $request->is('api/admin/login') ? 'adminapi' : 'userapi';

        $tokenResult = $this->authService->login($data, $guard);

        if (CheckAppError::isAppError($tokenResult)) {
            return $this->respondError($tokenResult->getErrorData());
        }

        //dd(auth()->guard('userapi')->user());  CAN GET USER LOGGED IN

        return $this->respondSuccess([
            'access_token' => $tokenResult,
            'token_type' => 'bearer',
        ]);
    }

    public function refresh(Request $request): JsonResponse
    {
        $guard = $request->is('api/admin/refresh') ? 'adminapi' : 'userapi';

        //dd(auth()->guard($guard)->user()); CANNOT GET USER LOGGED IN, JUST RECEIVED NULL

        try {
            $guard = $request->is('api/admin/refresh') ? 'adminapi' : 'userapi';

            $newToken = auth()->guard($guard)->refresh();

            return $this->respondSuccess([
                'access_token' => $newToken,
                'token_type' => 'bearer',
            ]);
        } catch (Exception $e) {
            throw $e;
        }
    }
}