From cdcb2afc6d1a84115a89d1e4796c24d0f94d3bd5 Mon Sep 17 00:00:00 2001 From: pratik bhujel Date: Sun, 13 Sep 2026 09:54:18 +0545 Subject: [PATCH] Add HasApiTokens trait to User model for Sanctum token auth Allow User instances to issue Sanctum personal access tokens via createToken() as documented in README and CONTRIBUTING. Also add Pest feature tests verifying token issuance and /api/user authentication. --- app/Models/User.php | 3 ++- tests/Feature/ApiAuthTest.php | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 tests/Feature/ApiAuthTest.php diff --git a/app/Models/User.php b/app/Models/User.php index f6ba1d2..4e71ebe 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -9,13 +9,14 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; +use Laravel\Sanctum\HasApiTokens; #[Fillable(['name', 'email', 'password'])] #[Hidden(['password', 'remember_token'])] class User extends Authenticatable { /** @use HasFactory */ - use HasFactory, Notifiable; + use HasApiTokens, HasFactory, Notifiable; /** * Get the attributes that should be cast. diff --git a/tests/Feature/ApiAuthTest.php b/tests/Feature/ApiAuthTest.php new file mode 100644 index 0000000..38c3c70 --- /dev/null +++ b/tests/Feature/ApiAuthTest.php @@ -0,0 +1,40 @@ +getJson('/api/user'); + + $response->assertUnauthorized(); +}); + +test('authenticated request with sanctum token returns user', function () { + $user = User::factory()->create([ + 'name' => 'Jane Doe', + 'email' => 'jane@example.com', + ]); + + Sanctum::actingAs($user, ['*']); + + $response = $this->getJson('/api/user'); + + $response->assertOk() + ->assertJson([ + 'id' => $user->id, + 'name' => 'Jane Doe', + 'email' => 'jane@example.com', + ]); +}); + +test('user model can issue personal access tokens', function () { + $user = User::factory()->create(); + + $token = $user->createToken('mobile-app'); + + expect($token->plainTextToken)->toBeString()->not->toBeEmpty(); + expect($user->tokens)->toHaveCount(1); +});