86 lines
3.1 KiB
PHP
86 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\APIS\CustomerApi;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Illuminate\Http\Request;
|
|
use Tymon\JWTAuth\Facades\JWTAuth;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Database\QueryException;
|
|
|
|
class AuthController extends Controller
|
|
{
|
|
|
|
public function login(Request $request)
|
|
{
|
|
try {
|
|
// Validate incoming request data
|
|
$validator = Validator::make($request->all(), [
|
|
'email_address' => 'required|email',
|
|
'password' => 'required',
|
|
]);
|
|
|
|
// Check if validation failed
|
|
if ($validator->fails()) {
|
|
$validationErrors = $validator->errors()->all();
|
|
Log::error("Login validation error: " . implode(", ", $validationErrors));
|
|
return jsonResponseWithErrorMessageApi($validationErrors, 403);
|
|
}
|
|
|
|
// Check if the user is soft-deleted
|
|
$isDelete = User::where('email_address', $request->email_address)->onlyTrashed()->first();
|
|
if ($isDelete) {
|
|
return jsonResponseWithErrorMessageApi(__('auth.deleted_user_by_admin'), 403);
|
|
}
|
|
|
|
// Check if the user exists and is not soft-deleted
|
|
$isExistEmail = User::where('email_address', $request->email_address)->whereNull('deleted_at')->first();
|
|
if ($isExistEmail == null) {
|
|
return jsonResponseWithErrorMessageApi(__('auth.incorrect_email'), 403);
|
|
}
|
|
|
|
// Check if the entered password matches the stored password
|
|
if ($isExistEmail && !(Hash::check($request->password, $isExistEmail->password))) {
|
|
Log::error('Entered Password is wrong for ' . $request->email_address);
|
|
return jsonResponseWithErrorMessageApi(__('auth.incorrect_password'), 403);
|
|
}
|
|
|
|
// Attempt to authenticate the user
|
|
$credentials = [
|
|
'email_address' => $request->email_address,
|
|
'password' => $request->password,
|
|
];
|
|
|
|
if (Auth::attempt($credentials)) {
|
|
$user = Auth::user();
|
|
$token = JWTAuth::fromUser($user);
|
|
|
|
// Return success response with JWT token
|
|
$response = [
|
|
'access_token' => $token,
|
|
'user' => $user,
|
|
];
|
|
|
|
return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $response, 200);
|
|
}
|
|
|
|
// Authentication failed
|
|
return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 401);
|
|
|
|
} catch (QueryException $e) {
|
|
Log::error('Customer Login Failed: ' . $e->getMessage());
|
|
return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 401);
|
|
} catch (\Exception $e) {
|
|
Log::error('Unexpected error during login: ' . $e->getMessage());
|
|
return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
|