diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php new file mode 100644 index 00000000..39dc4d6e --- /dev/null +++ b/app/Http/Controllers/AuthController.php @@ -0,0 +1,38 @@ +validate([ + 'email' => ['required', 'string', 'email'], + 'password' => ['required'] + ]); + + if (!auth()->attempt($credentials)) { + return response()->json([ + 'message' => 'Invalid login credentials' + ], Response::HTTP_UNAUTHORIZED); + } + + /** @var \App\Models\User $user */ + $user = auth()->user(); + $token = $user->createToken('authToken')->plainTextToken; + + return response()->json([ + 'user' => $user, + 'access_token' => $token + ], Response::HTTP_OK); + } +} diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index a9f4519f..0223acf4 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -17,6 +17,8 @@ public function run(): void // \App\Models\User::factory()->create([ // 'name' => 'Test User', // 'email' => 'test@example.com', + // 'email_verified_at' => now(), + // 'password' => bcrypt('test1234'), // ]); } } diff --git a/routes/api.php b/routes/api.php index 889937e1..8ad25252 100644 --- a/routes/api.php +++ b/routes/api.php @@ -1,5 +1,6 @@ get('/user', function (Request $request) { - return $request->user(); +/** + * Defines the API routes for version 1. + * + * @group v1 + */ +Route::group(['prefix' => 'v1'], function () { + require __DIR__ . '/api/v1/auth.php'; }); diff --git a/routes/api/v1/auth.php b/routes/api/v1/auth.php new file mode 100644 index 00000000..8ac55dfc --- /dev/null +++ b/routes/api/v1/auth.php @@ -0,0 +1,6 @@ +create([ + 'email' => 'valid@example.com', + 'password' => bcrypt('ValidPassword'), + ]); + + $response = $this->postJson('/api/v1/login', [ + 'email' => 'valid@example.com', + 'password' => 'ValidPassword', + ]); + + $response->assertStatus(Response::HTTP_OK) + ->assertJsonStructure([ + 'user' => [ + 'id', + 'name', + 'email', + 'email_verified_at', + 'created_at', + 'updated_at', + ], + 'access_token', + ]); + + $this->assertAuthenticatedAs($user); + } + + /** + * Test login with invalid credentials. + * + * @return void + */ + public function test_login_with_invalid_credentials(): void + { + $response = $this->postJson('/api/v1/login', [ + 'email' => 'invalid@example.com', + 'password' => 'invalidpassword', + ]); + + $response->assertStatus(Response::HTTP_UNAUTHORIZED) + ->assertJson([ + 'message' => 'Invalid login credentials', + ]); + + $this->assertGuest(); + } +}