From 40fdd224800124ffc1bb509c25094293e6850c77 Mon Sep 17 00:00:00 2001 From: sayaliparab Date: Wed, 12 Mar 2025 19:19:13 +0530 Subject: [PATCH] middleware_cors --- .../APIS/CustomerApi/AuthController.php | 30 +++++--- .../APIS/CustomerApi/DeviceController.php | 2 +- .../CustomerApi/UserAssetLinkController.php | 73 ++++++++++++++----- app/Http/Helpers/Webhelper.php | 14 +++- app/Http/Middleware/CheckUserStatus.php | 22 ++---- app/Http/Middleware/CorsMiddleware.php | 29 ++++++++ app/Models/User.php | 9 ++- bootstrap/app.php | 13 +++- config/auth.php | 6 +- config/cors.php | 34 +++++++++ .../0001_01_01_000000_create_users_table.php | 1 - routes/customer_api.php | 13 +++- 12 files changed, 189 insertions(+), 57 deletions(-) create mode 100644 app/Http/Middleware/CorsMiddleware.php create mode 100644 config/cors.php diff --git a/app/Http/Controllers/APIS/CustomerApi/AuthController.php b/app/Http/Controllers/APIS/CustomerApi/AuthController.php index 740528b..fb76dbc 100644 --- a/app/Http/Controllers/APIS/CustomerApi/AuthController.php +++ b/app/Http/Controllers/APIS/CustomerApi/AuthController.php @@ -11,7 +11,8 @@ use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Hash; use Illuminate\Database\QueryException; - +// use App\Http\Controllers\APIS\CustomerApi\Http; +use Illuminate\Support\Facades\Http; class AuthController extends Controller { @@ -22,25 +23,19 @@ class AuthController extends Controller 'email' => 'required|email', 'password' => 'required', ]); - if ($validator->fails()) { $validationErrors = $validator->errors()->all(); Log::error("Login validation error: " . implode(", ", $validationErrors)); return jsonResponseWithErrorMessageApi($validationErrors, 403); } - - - $isExistEmail = User::where('email', $request->email)->first(); if ($isExistEmail == null) { return jsonResponseWithErrorMessageApi(__('auth.incorrect_email'), 403); } - if ($isExistEmail && !(Hash::check($request->password, $isExistEmail->password))) { Log::error('Entered Password is wrong for ' . $request->email); return jsonResponseWithErrorMessageApi(__('auth.incorrect_password'), 403); } - $credentials = [ 'email' => $request->email, 'password' => $request->password, @@ -58,14 +53,31 @@ class AuthController extends Controller return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $response, 200); } - - } catch (QueryException $e) { Log::error('Customer Login Failed: ' . $e->getMessage()); return jsonResponseWithErrorMessageApi(__('auth.authentication_failed'), 401); } } + // public function login() + // { + // // Define the API endpoint + // $url = 'http://65.0.131.117:8080/api/auth/login'; + + // // Define the payload + // $payload = [ + // 'username' => 'veoliauser@mail.com', + // 'password' => 'veolia123', + // ]; + + // // Make the POST request + // $response = Http::withHeaders([ + // 'Content-Type' => 'application/json', + // ])->post($url, $payload); + + // // Return the response + // return response()->json($response->json(), $response->status()); + // } } diff --git a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php index c848588..068e891 100644 --- a/app/Http/Controllers/APIS/CustomerApi/DeviceController.php +++ b/app/Http/Controllers/APIS/CustomerApi/DeviceController.php @@ -8,4 +8,4 @@ use Illuminate\Http\Request; class DeviceController extends Controller { // -} \ No newline at end of file +} diff --git a/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php b/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php index 82f990a..522a0b8 100644 --- a/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php +++ b/app/Http/Controllers/APIS/CustomerApi/UserAssetLinkController.php @@ -7,30 +7,67 @@ use App\Models\User; use App\Models\UserAssetLink; use Illuminate\Http\Request; use Tymon\JWTAuth\Facades\JWTAuth; - - +use Illuminate\Container\Attributes\Auth; +use Illuminate\Database\QueryException; +use Illuminate\Support\Facades\Log; class UserAssetLinkController extends Controller { + // public function index(Request $request) + // { + + // // $token = $request->bearerToken(); // Or $request->header('Authorization') + // $token = readHeaderToken(); // Or $request->header('Authorization') + // dd($token['sub']); + // // $user = Auth::user(); + // // dd($user); + + + // $userAssetLinks = UserAssetLink::with(['user', 'asset.devices']) + // ->withCount([ + // 'asset as active_devices_count' => function ($query) { + // $query->whereHas('devices', function ($q) { + // $q->where('active', 1); + // }); + // }, + // 'asset as inactive_devices_count' => function ($query) { + // $query->whereHas('devices', function ($q) { + // $q->where('active', 0); + // }); + // } + // ]) + // ->get(); + + + // return response()->json($userAssetLinks); + // } public function index() { - // $user = User::where('id', '8898f380-fd9e-11ef-a9dc-45dd276e4cd5')->first(); - $userAssetLinks = UserAssetLink::with(['user', 'asset.devices']) - ->withCount([ - 'asset as active_devices_count' => function ($query) { - $query->whereHas('devices', function ($q) { - $q->where('active', 1); - }); - }, - 'asset as inactive_devices_count' => function ($query) { - $query->whereHas('devices', function ($q) { - $q->where('active', 0); - }); - } - ]) - ->get(); + try { + $token = readHeaderToken(); + // dd($token['sub']); + $user = User::where('id',$token['sub'])->first(); + $userAssetLinks = UserAssetLink::with(['user', 'asset.devices']) + ->where('user_id', $user->id) + ->withCount([ + 'asset as active_devices_count' => function ($query) { + $query->whereHas('devices', function ($q) { + $q->where('active', 1); + }); + }, + 'asset as inactive_devices_count' => function ($query) { + $query->whereHas('devices', function ($q) { + $q->where('active', 0); + }); + } + ]) + ->get(); - return response()->json($userAssetLinks); + return jsonResponseWithSuccessMessage(__('auth.data_fetched_successfully'), $userAssetLinks, 200); + } catch (QueryException $e) { + Log::error('Something went wrong: ' . $e->getMessage()); + return jsonResponseWithErrorMessageApi(__('Something went wrong'), 500); + } } } diff --git a/app/Http/Helpers/Webhelper.php b/app/Http/Helpers/Webhelper.php index e8ce48e..90425cf 100644 --- a/app/Http/Helpers/Webhelper.php +++ b/app/Http/Helpers/Webhelper.php @@ -125,16 +125,22 @@ if (!function_exists('readHeaderToken')) { function readHeaderToken() { $tokenData = Session::get('vendorToken'); - $token = JWTAuth::setToken($tokenData)->getPayload(); - // dd("tokendata",$tokenData,$token['sub'],$token['iat']); +$token = JWTAuth::setToken($tokenData)->getPayload(); + +// dd([ +// 'tokenData' => $tokenData, +// 'sub' => $token['sub'], // This should be your UUID +// 'sub_type' => gettype($token['sub']), +// 'sub_length' => strlen($token['sub']), +// 'iat' => date('Y-m-d H:i:s', $token['iat']), +// ]); //convert iat to readable format $iat = date('Y-m-d H:i:s', $token['iat']); // check token issued time for single device login // ['last_login_datetime', $iat] - $check_iat = User::where([['id', $token['sub']],])->first(); - + $check_iat = User::find((string) $token['sub']); // dd($check_iat); if ($check_iat) { return $token; diff --git a/app/Http/Middleware/CheckUserStatus.php b/app/Http/Middleware/CheckUserStatus.php index fced48f..3491ec4 100644 --- a/app/Http/Middleware/CheckUserStatus.php +++ b/app/Http/Middleware/CheckUserStatus.php @@ -5,10 +5,12 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; +use Illuminate\Support\Facades\Auth; use Tymon\JWTAuth\Facades\JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use Illuminate\Support\Facades\Session; + class CheckUserStatus { /** @@ -16,10 +18,11 @@ class CheckUserStatus * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ + + public function handle(Request $request, Closure $next): Response { - // Check if the custom access-token header is present - if (!$request->hasHeader('access-token')) { + if (!$request->hasHeader('Authorization')) { return response()->json([ 'status' => 'error', 'status_code' => 401, @@ -27,20 +30,11 @@ class CheckUserStatus ], 401); } - // Retrieve the token from the custom access-token header - $token = $request->header('access-token'); + $token = $request->header('Authorization'); + $token = str_replace('Bearer ', '', $token); try { - // Attempt to authenticate the user based on the token - $user = JWTAuth::setToken($token)->authenticate(); - - if (!$user || $user->authority !== 'CUSTOMER_USER') { - return response()->json([ - 'status' => 'error', - 'status_code' => 403, - 'message' => 'Unauthorized access' - ], 403); - } + $payload = JWTAuth::setToken($token)->getPayload(); Session::flash('vendorToken', $token); } catch (JWTException $e) { diff --git a/app/Http/Middleware/CorsMiddleware.php b/app/Http/Middleware/CorsMiddleware.php new file mode 100644 index 0000000..14e2449 --- /dev/null +++ b/app/Http/Middleware/CorsMiddleware.php @@ -0,0 +1,29 @@ +headers->set('Access-Control-Allow-Origin', '*'); + $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); + } + + return $response; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 06d8a59..e39d486 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -10,11 +10,17 @@ use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { + + protected $primaryKey = 'id'; // Make sure this matches your table's PK + public $incrementing = false; // UUIDs are not auto-incrementing + protected $keyType = 'string'; // Ensures UUIDs work properly /** @use HasFactory<\Database\Factories\UserFactory> */ use HasFactory, Notifiable; + public function getJWTIdentifier() { - return $this->getKey(); + // return $this->getKey(); + return (string) $this->getKey(); } public function getJWTCustomClaims() @@ -30,6 +36,7 @@ class User extends Authenticatable implements JWTSubject 'name', 'email', 'password', + 'authority' ]; /** diff --git a/bootstrap/app.php b/bootstrap/app.php index d654276..fa01a38 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -6,13 +6,18 @@ use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( - web: __DIR__.'/../routes/web.php', - api: __DIR__.'/../routes/api.php', - commands: __DIR__.'/../routes/console.php', + web: __DIR__ . '/../routes/web.php', + api: __DIR__ . '/../routes/api.php', + commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { - // + $middleware->alias([ + + 'customerApiBasicAuth' => \App\Http\Middleware\CheckUserStatus::class, + 'cors' => \App\Http\Middleware\CorsMiddleware::class, + + ]); }) ->withExceptions(function (Exceptions $exceptions) { // diff --git a/config/auth.php b/config/auth.php index 0ba5d5d..bd880b4 100644 --- a/config/auth.php +++ b/config/auth.php @@ -40,6 +40,10 @@ return [ 'driver' => 'session', 'provider' => 'users', ], + 'api' => [ + 'driver' => 'jwt', + 'provider' => 'users', + ], ], /* @@ -62,7 +66,7 @@ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', - 'model' => env('AUTH_MODEL', App\Models\User::class), + 'model' => App\Models\User::class, ], // 'users' => [ diff --git a/config/cors.php b/config/cors.php new file mode 100644 index 0000000..d2f83aa --- /dev/null +++ b/config/cors.php @@ -0,0 +1,34 @@ + ['api/*', 'oauth/token','sanctum/csrf-cookie'], + + 'allowed_methods' => ['*'], + + 'allowed_origins' => ['*'], + + 'allowed_origins_patterns' => [], + + 'allowed_headers' => ['*'], + + 'exposed_headers' => [], + + 'max_age' => 0, + + 'supports_credentials' => false, + +]; diff --git a/database/migrations/0001_01_01_000000_create_users_table.php b/database/migrations/0001_01_01_000000_create_users_table.php index a4fadc7..f271e26 100644 --- a/database/migrations/0001_01_01_000000_create_users_table.php +++ b/database/migrations/0001_01_01_000000_create_users_table.php @@ -18,7 +18,6 @@ return new class extends Migration $table->uuid('customer_id'); $table->string('email')->unique(); $table->string('password')->nullable(); - $table->string('authority', 50); $table->string('first_name')->nullable(); $table->string('last_name')->nullable(); diff --git a/routes/customer_api.php b/routes/customer_api.php index 010a9b8..70553e8 100644 --- a/routes/customer_api.php +++ b/routes/customer_api.php @@ -3,14 +3,19 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\APIS\CustomerApi\UserAssetLinkController; -// use App\Http\Controllers\APIS\CustomerApi\AuthController; -// app\Http\Controllers\APIS\CustomerApi\AuthController.php +use Tymon\JWTAuth\Facades\JWTAuth; + use App\Http\Controllers\APIS\CustomerApi\AuthController; Route::get('/customerapi', function () { return ('Welcome to admin api routes.'); }); +Route::post('user-login', [AuthController::class, 'login']); + +// Route::post('/user-login', [AuthController::class, 'login']); +Route::middleware(['customerApiBasicAuth'])->group(function () { + Route::get('/user-assets', [UserAssetLinkController::class, 'index']); + +}); -Route::get('/user-assets', [UserAssetLinkController::class, 'index']); -Route::post('/user-login', [AuthController::class, 'login']);