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.
|
||||
|
||||
Reference in New Issue
Block a user