From ca9762df9a7bb934bea7d6d57e6bb44ee42781ae Mon Sep 17 00:00:00 2001 From: TimmensOne Date: Mon, 3 Apr 2023 14:44:33 +0200 Subject: [PATCH] add token based api auth --- ...01_create_personal_access_tokens_table.php | 4 ++- device-app/routes/api.php | 25 +++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/device-app/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php b/device-app/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php index e828ad8..92d4b1b 100644 --- a/device-app/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php +++ b/device-app/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php @@ -13,7 +13,9 @@ public function up(): void { Schema::create('personal_access_tokens', function (Blueprint $table) { $table->id(); - $table->morphs('tokenable'); + $table->string('tokenable_type'); + $table->string('tokenable_id'); + $table->index(["tokenable_type", "tokenable_id"]); $table->string('name'); $table->string('token', 64)->unique(); $table->text('abilities')->nullable(); diff --git a/device-app/routes/api.php b/device-app/routes/api.php index 5d7419b..88414be 100644 --- a/device-app/routes/api.php +++ b/device-app/routes/api.php @@ -4,8 +4,11 @@ use App\Models\LocationTransaction; use App\Models\OwnerTransaction; use App\Models\PurchasingInformation; +use App\Models\User; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Route; /* @@ -19,7 +22,25 @@ | */ -Route::get('/export', function () { +Route::post('/login', function (Request $request) { + $fields = $request->validate( + [ + 'user' => 'required', + 'password' => 'required' + ] + + ); + $user = User::where('rz_username', $fields['user'])->first(); + if (!$user || !Hash::check($fields['password'], $user->hashed_password)) { + return response([ + 'message' => 'Bad login' + ], 401); + } + $token = $user->createToken('token'); + return ['token' => $token->plainTextToken]; +}); + +Route::middleware('auth:sanctum')->get('/export', function () { return response()->json([ 'Devices' => Device::all(), @@ -29,7 +50,7 @@ ]); }); -Route::post('/import', function (Request $request) { +Route::middleware('auth:sanctum')->post('/import', function (Request $request) { $data = $request->json()->all(); $devices = $data['devices']; $purchasingInformations = $data['purchasing_information'];