- Added localization support for API responses in English and Spanish. - Introduced a middleware to set the API locale based on the Accept-Language header. - Updated various exception messages and validation responses to use localized strings. - Created new language files for English and Spanish translations. - Refactored existing code to replace hardcoded messages with localized strings. - Added tests to verify localization functionality and response correctness.
67 lines
2.0 KiB
PHP
67 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Auth\Controllers;
|
|
|
|
use App\Domains\Auth\Models\User;
|
|
use App\Domains\Auth\Requests\LoginUserRequest;
|
|
use App\Domains\Auth\Resources\UserResource;
|
|
use App\Domains\Cart\Services\GuestCartMergeService;
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Support\Facades\Cookie;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class LoginController extends Controller
|
|
{
|
|
public function __construct(
|
|
private readonly GuestCartMergeService $guestCartMergeService,
|
|
) {}
|
|
|
|
/**
|
|
* @throws ValidationException
|
|
*/
|
|
public function __invoke(LoginUserRequest $request): JsonResponse
|
|
{
|
|
$credentials = $request->validated();
|
|
$user = User::query()->where('email', $credentials['email'])->first();
|
|
|
|
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
|
|
throw ValidationException::withMessages([
|
|
'email' => __('api.auth.invalid_credentials'),
|
|
]);
|
|
}
|
|
|
|
$expirationMinutes = (int) config('sanctum.expiration');
|
|
$token = $user->createToken(
|
|
'api-token',
|
|
['*'],
|
|
now()->addMinutes($expirationMinutes),
|
|
)->plainTextToken;
|
|
|
|
$guestTokenCookie = $request->cookie('guest_token');
|
|
$guestToken = is_string($guestTokenCookie) && $guestTokenCookie !== ''
|
|
? $guestTokenCookie
|
|
: null;
|
|
$this->guestCartMergeService->merge(
|
|
$credentials['tenant_codigo'],
|
|
$user,
|
|
$guestToken,
|
|
);
|
|
|
|
$response = response()->json([
|
|
'code' => 'auth.login_success',
|
|
'message' => __('api.auth.login_success'),
|
|
'token' => $token,
|
|
'token_type' => 'Bearer',
|
|
'user' => UserResource::make($user),
|
|
]);
|
|
|
|
if ($guestToken !== null) {
|
|
$response->withCookie(Cookie::forget('guest_token'));
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
}
|