feat(api): mobile API Milestone 1+2 — Sanctum auth + offline sync vertical slice
Milestone 1 (auth foundation):
- Installed laravel/sanctum; HasApiTokens on User; published config + migration.
- routes/api.php with /api/v1; Sanctum 'ability' middleware alias registered.
- AuthController: POST login (long-lived revocable device token w/ ability
mobile-sync + devices table), GET me, POST logout. New Device model/table.
Milestone 2 (vertical slice, offline-first):
- progress_updates: +uuid (client-generated) +client_updated_at.
- ProjectApiController: GET projects (accessibleBy), GET projects/{id}/bundle
(project/phases/layers/features, membership-authorized).
- SyncController: POST sync — batch ops, idempotent by uuid, per-op result
(applied/duplicate/error), server-set user_id, authz by permission+membership.
Currently handles progress_update.create.
Tests: tests/Feature/Api/MobileApiTest (9 passing) — auth, accessible projects,
bundle authz, sync apply+idempotency, permission enforcement.
Also fixed a latent schema bug: projects.reference (and external_reference_1)
existed in the live DB but had no migration — added a guarded migration so fresh
installs match production.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Device;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* Issue a long-lived, revocable device token (Sanctum).
|
||||
*/
|
||||
public function login(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
'device_name' => ['required', 'string', 'max:255'],
|
||||
'app_version' => ['nullable', 'string', 'max:50'],
|
||||
]);
|
||||
|
||||
$user = User::where('email', $data['email'])->first();
|
||||
|
||||
if (! $user || ! Hash::check($data['password'], $user->password)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [__('auth.failed')],
|
||||
]);
|
||||
}
|
||||
|
||||
// One token per device name: revoke the previous one for this device.
|
||||
$user->tokens()->where('name', $data['device_name'])->delete();
|
||||
|
||||
$token = $user->createToken($data['device_name'], ['mobile-sync']);
|
||||
|
||||
Device::updateOrCreate(
|
||||
['user_id' => $user->id, 'name' => $data['device_name']],
|
||||
[
|
||||
'token_id' => $token->accessToken->id,
|
||||
'app_version' => $data['app_version'] ?? null,
|
||||
'last_seen_at' => now(),
|
||||
]
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'token' => $token->plainTextToken,
|
||||
'user' => $this->userPayload($user),
|
||||
]);
|
||||
}
|
||||
|
||||
public function me(Request $request)
|
||||
{
|
||||
return response()->json(['user' => $this->userPayload($request->user())]);
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
$token = $request->user()->currentAccessToken();
|
||||
|
||||
// Clean up the device record bound to this token.
|
||||
Device::where('token_id', $token->id)->delete();
|
||||
$token->delete();
|
||||
|
||||
return response()->json(['message' => 'Logged out']);
|
||||
}
|
||||
|
||||
private function userPayload(User $user): array
|
||||
{
|
||||
return [
|
||||
'id' => $user->id,
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
'roles' => $user->getRoleNames(),
|
||||
'permissions' => $user->getAllPermissions()->pluck('name')->values(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Project;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProjectApiController extends Controller
|
||||
{
|
||||
/** Projects the authenticated user can access. */
|
||||
public function index(Request $request)
|
||||
{
|
||||
$projects = Project::accessibleBy($request->user())
|
||||
->orderBy('name')
|
||||
->get(['id', 'reference', 'name', 'address', 'status', 'lat', 'lng', 'updated_at']);
|
||||
|
||||
return response()->json(['projects' => $projects]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Offline bundle for one project (Milestone 2 — minimal: structure, no media yet).
|
||||
*/
|
||||
public function bundle(Request $request, Project $project)
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_unless(
|
||||
$user->can('manage all') || $project->users()->where('user_id', $user->id)->exists(),
|
||||
403
|
||||
);
|
||||
|
||||
$project->load([
|
||||
'phases' => fn ($q) => $q->orderBy('order'),
|
||||
'phases.layers',
|
||||
'phases.layers.features',
|
||||
]);
|
||||
|
||||
$layers = $project->phases->flatMap->layers;
|
||||
$features = $layers->flatMap->features;
|
||||
|
||||
return response()->json([
|
||||
'server_time' => now()->toIso8601String(),
|
||||
'project' => [
|
||||
'id' => $project->id,
|
||||
'reference' => $project->reference,
|
||||
'name' => $project->name,
|
||||
'address' => $project->address,
|
||||
'lat' => $project->lat,
|
||||
'lng' => $project->lng,
|
||||
'status' => $project->status,
|
||||
'updated_at' => $project->updated_at?->toIso8601String(),
|
||||
],
|
||||
'phases' => $project->phases->map(fn ($p) => [
|
||||
'id' => $p->id,
|
||||
'name' => $p->name,
|
||||
'order' => $p->order,
|
||||
'color' => $p->color,
|
||||
'progress_percent' => $p->progress_percent,
|
||||
'updated_at' => $p->updated_at?->toIso8601String(),
|
||||
])->values(),
|
||||
'layers' => $layers->map(fn ($l) => [
|
||||
'id' => $l->id,
|
||||
'phase_id' => $l->phase_id,
|
||||
'name' => $l->name,
|
||||
'color' => $l->color,
|
||||
'updated_at' => $l->updated_at?->toIso8601String(),
|
||||
])->values(),
|
||||
'features' => $features->map(fn ($f) => [
|
||||
'id' => $f->id,
|
||||
'layer_id' => $f->layer_id,
|
||||
'name' => $f->name,
|
||||
'geometry' => $f->geometry,
|
||||
'status' => $f->status,
|
||||
'progress' => $f->progress,
|
||||
'updated_at' => $f->updated_at?->toIso8601String(),
|
||||
])->values(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Phase;
|
||||
use App\Models\ProgressUpdate;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class SyncController extends Controller
|
||||
{
|
||||
/**
|
||||
* Push a batch of offline mutations. Idempotent by client-generated `uuid`.
|
||||
* Returns a per-operation result (applied | duplicate | conflict | error).
|
||||
*
|
||||
* Milestone 2: supports only progress_update.create (vertical slice).
|
||||
*/
|
||||
public function sync(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'operations' => ['required', 'array'],
|
||||
'operations.*.entity' => ['required', 'string'],
|
||||
'operations.*.op' => ['required', 'string'],
|
||||
'operations.*.uuid' => ['required', 'uuid'],
|
||||
'operations.*.data' => ['required', 'array'],
|
||||
'operations.*.client_updated_at' => ['nullable', 'date'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
$results = [];
|
||||
|
||||
foreach ($data['operations'] as $op) {
|
||||
$results[] = $this->handle($user, $op);
|
||||
}
|
||||
|
||||
return response()->json(['results' => $results]);
|
||||
}
|
||||
|
||||
private function handle(User $user, array $op): array
|
||||
{
|
||||
$uuid = $op['uuid'];
|
||||
|
||||
try {
|
||||
if ($op['entity'] === 'progress_update' && $op['op'] === 'create') {
|
||||
return $this->progressUpdateCreate($user, $uuid, $op);
|
||||
}
|
||||
|
||||
return $this->error($uuid, 'unsupported entity/op: ' . $op['entity'] . '.' . $op['op']);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error($uuid, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function progressUpdateCreate(User $user, string $uuid, array $op): array
|
||||
{
|
||||
// Idempotency: same uuid already applied → duplicate (no-op).
|
||||
$existing = ProgressUpdate::where('uuid', $uuid)->first();
|
||||
if ($existing) {
|
||||
return ['uuid' => $uuid, 'status' => 'duplicate', 'server_id' => $existing->id];
|
||||
}
|
||||
|
||||
$validator = Validator::make($op['data'], [
|
||||
'phase_id' => ['required', 'integer', 'exists:phases,id'],
|
||||
'progress' => ['required', 'integer', 'min:0', 'max:100'],
|
||||
'comment' => ['nullable', 'string'],
|
||||
'location' => ['nullable', 'array'],
|
||||
]);
|
||||
if ($validator->fails()) {
|
||||
return $this->error($uuid, 'validation: ' . $validator->errors()->first());
|
||||
}
|
||||
$d = $validator->validated();
|
||||
|
||||
$phase = Phase::with('project')->findOrFail($d['phase_id']);
|
||||
|
||||
// Authorization: project membership + permission (per-op, never abort the batch).
|
||||
$isMember = $user->can('manage all')
|
||||
|| ($phase->project && $phase->project->users()->where('user_id', $user->id)->exists());
|
||||
if (! $isMember || ! $user->can('update progress')) {
|
||||
return $this->error($uuid, 'forbidden');
|
||||
}
|
||||
|
||||
$pu = ProgressUpdate::create([
|
||||
'uuid' => $uuid,
|
||||
'phase_id' => $phase->id,
|
||||
'user_id' => $user->id, // server-set, never trust client
|
||||
'progress_percent' => $d['progress'],
|
||||
'comment' => $d['comment'] ?? null,
|
||||
'location' => $d['location'] ?? null,
|
||||
'client_updated_at' => $op['client_updated_at'] ?? null,
|
||||
]);
|
||||
|
||||
// Mirror the web behaviour: reflect latest progress on the phase.
|
||||
$phase->progress_percent = $d['progress'];
|
||||
$phase->save();
|
||||
|
||||
return ['uuid' => $uuid, 'status' => 'applied', 'server_id' => $pu->id];
|
||||
}
|
||||
|
||||
private function error(string $uuid, string $message): array
|
||||
{
|
||||
return ['uuid' => $uuid, 'status' => 'error', 'error' => $message];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Device extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id', 'name', 'token_id', 'app_version', 'last_seen_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'last_seen_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,12 @@ use Illuminate\Database\Eloquent\Model;
|
||||
class ProgressUpdate extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'phase_id', 'user_id', 'progress_percent', 'comment', 'location'
|
||||
'uuid', 'phase_id', 'user_id', 'progress_percent', 'comment', 'location', 'client_updated_at'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'location' => 'array', // Store as [lat, lng]
|
||||
'client_updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function phase()
|
||||
|
||||
+3
-2
@@ -7,12 +7,13 @@ use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Spatie\Permission\Traits\HasRoles;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
use Spatie\Permission\Traits\HasRoles;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasFactory, Notifiable, HasRoles;
|
||||
use HasFactory, Notifiable, HasRoles, HasApiTokens;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
|
||||
+4
-1
@@ -7,17 +7,20 @@ 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',
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->appendToGroup('web', \App\Http\Middleware\SetLocale::class);
|
||||
|
||||
// Spatie permission middleware aliases
|
||||
// Spatie permission + Sanctum ability middleware aliases
|
||||
$middleware->alias([
|
||||
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
|
||||
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
|
||||
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
|
||||
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
|
||||
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
|
||||
]);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"blade-ui-kit/blade-heroicons": "^2.7",
|
||||
"gasparesganga/php-shapefile": "^3.4",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/sanctum": "^4.3",
|
||||
"laravel/tinker": "^2.10.1",
|
||||
"league/geotools": "^1.3",
|
||||
"livewire/livewire": "^3.6.4",
|
||||
|
||||
Generated
+67
-4
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "1b74f08906a514a8a24b6e299587d9f3",
|
||||
"content-hash": "45553317b713050f78b4233c204790f9",
|
||||
"packages": [
|
||||
{
|
||||
"name": "blade-ui-kit/blade-heroicons",
|
||||
@@ -1753,6 +1753,69 @@
|
||||
},
|
||||
"time": "2026-04-20T16:07:33+00:00"
|
||||
},
|
||||
{
|
||||
"name": "laravel/sanctum",
|
||||
"version": "v4.3.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/laravel/sanctum.git",
|
||||
"reference": "2a9bccc18e9907808e0018dd15fa643937886b1e"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/laravel/sanctum/zipball/2a9bccc18e9907808e0018dd15fa643937886b1e",
|
||||
"reference": "2a9bccc18e9907808e0018dd15fa643937886b1e",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-json": "*",
|
||||
"illuminate/console": "^11.0|^12.0|^13.0",
|
||||
"illuminate/contracts": "^11.0|^12.0|^13.0",
|
||||
"illuminate/database": "^11.0|^12.0|^13.0",
|
||||
"illuminate/support": "^11.0|^12.0|^13.0",
|
||||
"php": "^8.2",
|
||||
"symfony/console": "^7.0|^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"mockery/mockery": "^1.6",
|
||||
"orchestra/testbench": "^9.15|^10.8|^11.0",
|
||||
"phpstan/phpstan": "^1.10"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"Laravel\\Sanctum\\SanctumServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Laravel\\Sanctum\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Taylor Otwell",
|
||||
"email": "taylor@laravel.com"
|
||||
}
|
||||
],
|
||||
"description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.",
|
||||
"keywords": [
|
||||
"auth",
|
||||
"laravel",
|
||||
"sanctum"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/laravel/sanctum/issues",
|
||||
"source": "https://github.com/laravel/sanctum"
|
||||
},
|
||||
"time": "2026-04-30T11:46:25+00:00"
|
||||
},
|
||||
{
|
||||
"name": "laravel/serializable-closure",
|
||||
"version": "v2.0.12",
|
||||
@@ -10429,12 +10492,12 @@
|
||||
],
|
||||
"aliases": [],
|
||||
"minimum-stability": "stable",
|
||||
"stability-flags": [],
|
||||
"stability-flags": {},
|
||||
"prefer-stable": true,
|
||||
"prefer-lowest": false,
|
||||
"platform": {
|
||||
"php": "^8.2"
|
||||
},
|
||||
"platform-dev": [],
|
||||
"plugin-api-version": "2.6.0"
|
||||
"platform-dev": {},
|
||||
"plugin-api-version": "2.9.0"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies;
|
||||
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
|
||||
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Stateful Domains
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Requests from the following domains / hosts will receive stateful API
|
||||
| authentication cookies. Typically, these should include your local
|
||||
| and production domains which access your API via a frontend SPA.
|
||||
|
|
||||
*/
|
||||
|
||||
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
|
||||
'%s%s',
|
||||
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
|
||||
Sanctum::currentApplicationUrlWithPort(),
|
||||
// Sanctum::currentRequestHost(),
|
||||
))),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Sanctum Guards
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This array contains the authentication guards that will be checked when
|
||||
| Sanctum is trying to authenticate a request. If none of these guards
|
||||
| are able to authenticate the request, Sanctum will use the bearer
|
||||
| token that's present on an incoming request for authentication.
|
||||
|
|
||||
*/
|
||||
|
||||
'guard' => ['web'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Expiration Minutes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value controls the number of minutes until an issued token will be
|
||||
| considered expired. This will override any values set in the token's
|
||||
| "expires_at" attribute, but first-party sessions are not affected.
|
||||
|
|
||||
*/
|
||||
|
||||
'expiration' => null,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Token Prefix
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Sanctum can prefix new tokens in order to take advantage of numerous
|
||||
| security scanning initiatives maintained by open source platforms
|
||||
| that notify developers if they commit tokens into repositories.
|
||||
|
|
||||
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
||||
|
|
||||
*/
|
||||
|
||||
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Sanctum Middleware
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When authenticating your first-party SPA with Sanctum you may need to
|
||||
| customize some of the middleware Sanctum uses while processing the
|
||||
| request. You may change the middleware listed below as required.
|
||||
|
|
||||
*/
|
||||
|
||||
'middleware' => [
|
||||
'authenticate_session' => AuthenticateSession::class,
|
||||
'encrypt_cookies' => EncryptCookies::class,
|
||||
'validate_csrf_token' => ValidateCsrfToken::class,
|
||||
],
|
||||
|
||||
];
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('personal_access_tokens', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->morphs('tokenable');
|
||||
$table->text('name');
|
||||
$table->string('token', 64)->unique();
|
||||
$table->text('abilities')->nullable();
|
||||
$table->timestamp('last_used_at')->nullable();
|
||||
$table->timestamp('expires_at')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('personal_access_tokens');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('devices', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('name'); // device_name del login
|
||||
$table->unsignedBigInteger('token_id')->nullable(); // id del personal_access_token actual
|
||||
$table->string('app_version')->nullable();
|
||||
$table->timestamp('last_seen_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['user_id', 'name']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('devices');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('progress_updates', function (Blueprint $table) {
|
||||
if (! Schema::hasColumn('progress_updates', 'uuid')) {
|
||||
$table->uuid('uuid')->nullable()->unique()->after('id');
|
||||
}
|
||||
if (! Schema::hasColumn('progress_updates', 'client_updated_at')) {
|
||||
$table->timestamp('client_updated_at')->nullable()->after('location');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('progress_updates', function (Blueprint $table) {
|
||||
foreach (['uuid', 'client_updated_at'] as $col) {
|
||||
if (Schema::hasColumn('progress_updates', $col)) {
|
||||
$table->dropColumn($col);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* `reference` (and `external_reference_1`) exist in the live DB but were never
|
||||
* created by a migration (the "add_reference_and_country" migration only added
|
||||
* `country`). This guarded migration reconciles the schema: on the live DB the
|
||||
* columns already exist and are skipped; on a fresh install they get created.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('projects', function (Blueprint $table) {
|
||||
if (! Schema::hasColumn('projects', 'reference')) {
|
||||
$table->string('reference')->nullable()->after('id');
|
||||
}
|
||||
if (! Schema::hasColumn('projects', 'external_reference_1')) {
|
||||
$table->string('external_reference_1')->nullable()->after('reference');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('projects', function (Blueprint $table) {
|
||||
foreach (['reference', 'external_reference_1'] as $col) {
|
||||
if (Schema::hasColumn('projects', $col)) {
|
||||
$table->dropColumn($col);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\Api\V1\AuthController;
|
||||
use App\Http\Controllers\Api\V1\ProjectApiController;
|
||||
use App\Http\Controllers\Api\V1\SyncController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::prefix('v1')->group(function () {
|
||||
|
||||
// Público
|
||||
Route::post('login', [AuthController::class, 'login'])->middleware('throttle:10,1');
|
||||
|
||||
// Protegido: token Sanctum con ability 'mobile-sync'
|
||||
Route::middleware(['auth:sanctum', 'ability:mobile-sync'])->group(function () {
|
||||
Route::get('me', [AuthController::class, 'me']);
|
||||
Route::post('logout', [AuthController::class, 'logout']);
|
||||
|
||||
// PULL
|
||||
Route::get('projects', [ProjectApiController::class, 'index']);
|
||||
Route::get('projects/{project}/bundle', [ProjectApiController::class, 'bundle']);
|
||||
|
||||
// PUSH
|
||||
Route::post('sync', [SyncController::class, 'sync'])->middleware('throttle:60,1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Api;
|
||||
|
||||
use App\Models\Phase;
|
||||
use App\Models\Project;
|
||||
use App\Models\ProgressUpdate;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Tests\TestCase;
|
||||
|
||||
class MobileApiTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Permission::findOrCreate('update progress');
|
||||
Permission::findOrCreate('manage all');
|
||||
}
|
||||
|
||||
private function makeProject(?User $member = null): Project
|
||||
{
|
||||
$project = Project::create([
|
||||
'reference' => 'TEST-1',
|
||||
'name' => 'Proyecto Test',
|
||||
'address' => 'Calle Falsa 123',
|
||||
'lat' => 40.0,
|
||||
'lng' => -3.0,
|
||||
'start_date' => now()->toDateString(),
|
||||
'end_date_estimated' => now()->addMonths(6)->toDateString(),
|
||||
'status' => 'in_progress',
|
||||
'created_by' => $member?->id ?? User::factory()->create()->id,
|
||||
]);
|
||||
|
||||
if ($member) {
|
||||
$project->users()->attach($member->id, ['role_in_project' => 'supervisor']);
|
||||
}
|
||||
|
||||
return $project;
|
||||
}
|
||||
|
||||
private function makePhase(Project $project): Phase
|
||||
{
|
||||
return Phase::create([
|
||||
'project_id' => $project->id,
|
||||
'name' => 'Fase 1',
|
||||
'order' => 1,
|
||||
'color' => '#3b82f6',
|
||||
'progress_percent' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
// ── Auth ───────────────────────────────────────────────────────────────────
|
||||
|
||||
public function test_login_returns_a_token(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$res = $this->postJson('/api/v1/login', [
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
'device_name' => 'Pixel-Test',
|
||||
]);
|
||||
|
||||
$res->assertOk()->assertJsonStructure(['token', 'user' => ['id', 'email', 'permissions']]);
|
||||
$this->assertDatabaseHas('devices', ['user_id' => $user->id, 'name' => 'Pixel-Test']);
|
||||
}
|
||||
|
||||
public function test_login_fails_with_wrong_password(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->postJson('/api/v1/login', [
|
||||
'email' => $user->email,
|
||||
'password' => 'incorrecta',
|
||||
'device_name' => 'Pixel-Test',
|
||||
])->assertStatus(422);
|
||||
}
|
||||
|
||||
public function test_me_requires_authentication(): void
|
||||
{
|
||||
$this->getJson('/api/v1/me')->assertStatus(401);
|
||||
}
|
||||
|
||||
public function test_me_returns_user_with_token(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$this->getJson('/api/v1/me')
|
||||
->assertOk()
|
||||
->assertJsonPath('user.id', $user->id);
|
||||
}
|
||||
|
||||
// ── Pull ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
public function test_projects_index_only_returns_accessible_projects(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$mine = $this->makeProject($user);
|
||||
$other = $this->makeProject(); // not a member
|
||||
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$res = $this->getJson('/api/v1/projects')->assertOk();
|
||||
$ids = collect($res->json('projects'))->pluck('id');
|
||||
$this->assertTrue($ids->contains($mine->id));
|
||||
$this->assertFalse($ids->contains($other->id));
|
||||
}
|
||||
|
||||
public function test_bundle_is_forbidden_for_non_member(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$project = $this->makeProject(); // user is not a member
|
||||
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$this->getJson("/api/v1/projects/{$project->id}/bundle")->assertStatus(403);
|
||||
}
|
||||
|
||||
public function test_bundle_returns_structure_for_member(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$project = $this->makeProject($user);
|
||||
$phase = $this->makePhase($project);
|
||||
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$this->getJson("/api/v1/projects/{$project->id}/bundle")
|
||||
->assertOk()
|
||||
->assertJsonPath('project.id', $project->id)
|
||||
->assertJsonPath('phases.0.id', $phase->id);
|
||||
}
|
||||
|
||||
// ── Push (sync) ──────────────────────────────────────────────────────────────
|
||||
|
||||
public function test_sync_creates_progress_update_and_is_idempotent(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$user->givePermissionTo('update progress');
|
||||
$project = $this->makeProject($user);
|
||||
$phase = $this->makePhase($project);
|
||||
$uuid = (string) Str::uuid();
|
||||
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$payload = ['operations' => [[
|
||||
'entity' => 'progress_update', 'op' => 'create', 'uuid' => $uuid,
|
||||
'client_updated_at' => now()->toIso8601String(),
|
||||
'data' => ['phase_id' => $phase->id, 'progress' => 75, 'comment' => 'Avance'],
|
||||
]]];
|
||||
|
||||
// First push → applied
|
||||
$this->postJson('/api/v1/sync', $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('results.0.status', 'applied');
|
||||
|
||||
$this->assertDatabaseHas('progress_updates', ['uuid' => $uuid, 'progress_percent' => 75, 'user_id' => $user->id]);
|
||||
$this->assertEquals(75, $phase->fresh()->progress_percent);
|
||||
|
||||
// Re-send same uuid → duplicate (no second row)
|
||||
$this->postJson('/api/v1/sync', $payload)
|
||||
->assertOk()
|
||||
->assertJsonPath('results.0.status', 'duplicate');
|
||||
|
||||
$this->assertEquals(1, ProgressUpdate::where('uuid', $uuid)->count());
|
||||
}
|
||||
|
||||
public function test_sync_returns_error_without_permission(): void
|
||||
{
|
||||
$user = User::factory()->create(); // member but WITHOUT 'update progress'
|
||||
$project = $this->makeProject($user);
|
||||
$phase = $this->makePhase($project);
|
||||
|
||||
Sanctum::actingAs($user, ['mobile-sync']);
|
||||
|
||||
$this->postJson('/api/v1/sync', ['operations' => [[
|
||||
'entity' => 'progress_update', 'op' => 'create', 'uuid' => (string) Str::uuid(),
|
||||
'data' => ['phase_id' => $phase->id, 'progress' => 50],
|
||||
]]])
|
||||
->assertOk()
|
||||
->assertJsonPath('results.0.status', 'error');
|
||||
|
||||
$this->assertDatabaseCount('progress_updates', 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user