middleware_cors
This commit is contained in:
@@ -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());
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -8,4 +8,4 @@ use Illuminate\Http\Request;
|
||||
class DeviceController extends Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
29
app/Http/Middleware/CorsMiddleware.php
Normal file
29
app/Http/Middleware/CorsMiddleware.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CorsMiddleware
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$response = $next($request);
|
||||
|
||||
if ($response instanceof Response) {
|
||||
$response->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;
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -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) {
|
||||
//
|
||||
|
||||
@@ -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' => [
|
||||
|
||||
34
config/cors.php
Normal file
34
config/cors.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cross-Origin Resource Sharing (CORS) Configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure your settings for cross-origin resource sharing
|
||||
| or "CORS". This determines what cross-origin operations may execute
|
||||
| in web browsers. You are free to adjust these settings as needed.
|
||||
|
|
||||
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
||||
|
|
||||
*/
|
||||
|
||||
'paths' => ['api/*', 'oauth/token','sanctum/csrf-cookie'],
|
||||
|
||||
'allowed_methods' => ['*'],
|
||||
|
||||
'allowed_origins' => ['*'],
|
||||
|
||||
'allowed_origins_patterns' => [],
|
||||
|
||||
'allowed_headers' => ['*'],
|
||||
|
||||
'exposed_headers' => [],
|
||||
|
||||
'max_age' => 0,
|
||||
|
||||
'supports_credentials' => false,
|
||||
|
||||
];
|
||||
@@ -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();
|
||||
|
||||
@@ -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']);
|
||||
|
||||
Reference in New Issue
Block a user