Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| ApiTokenController | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
6 | |
100.00% |
1 / 1 |
| index | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| store | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
2 | |||
| destroy | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Controllers\admin; |
| 4 | |
| 5 | use App\Http\Controllers\Controller; |
| 6 | use Illuminate\Http\RedirectResponse; |
| 7 | use Illuminate\Http\Request; |
| 8 | use Illuminate\View\View; |
| 9 | |
| 10 | /** |
| 11 | * Settings → API Tokens. Lets a signed-in admin mint/revoke their own |
| 12 | * Sanctum personal access tokens (Phase 11 Slice 7) — for the pre-existing |
| 13 | * `auth:sanctum` /api/user route today, and whatever else gets put behind |
| 14 | * that middleware later. The plaintext token is only ever shown once, right |
| 15 | * after creation, via a one-shot session flash — Sanctum itself only stores |
| 16 | * the hash, so this page can never show it again after a reload. |
| 17 | */ |
| 18 | class ApiTokenController extends Controller |
| 19 | { |
| 20 | public function index(): View |
| 21 | { |
| 22 | return view('admin.api-tokens.index', [ |
| 23 | 'tokens' => auth()->user()->tokens()->latest()->get(), |
| 24 | ]); |
| 25 | } |
| 26 | |
| 27 | public function store(Request $request): RedirectResponse |
| 28 | { |
| 29 | $data = $request->validate([ |
| 30 | 'name' => 'required|string|max:80', |
| 31 | 'abilities' => 'nullable|string|max:255', |
| 32 | ]); |
| 33 | |
| 34 | $abilities = collect(preg_split('/[\s,]+/', (string) ($data['abilities'] ?? ''), -1, PREG_SPLIT_NO_EMPTY)) |
| 35 | ->values()->all(); |
| 36 | |
| 37 | $token = auth()->user()->createToken($data['name'], $abilities ?: ['*']); |
| 38 | |
| 39 | return redirect()->route('admin.api-tokens.index') |
| 40 | ->with('success', 'Token created — copy it now, it will not be shown again.') |
| 41 | ->with('plain_text_token', $token->plainTextToken); |
| 42 | } |
| 43 | |
| 44 | public function destroy(int $id): RedirectResponse |
| 45 | { |
| 46 | // ->tokens() already scopes to the signed-in user — this can never |
| 47 | // reach (let alone delete) another admin's token by guessing an id. |
| 48 | $deleted = auth()->user()->tokens()->whereKey($id)->delete(); |
| 49 | |
| 50 | return back()->with($deleted ? 'success' : 'error', $deleted ? 'Token revoked.' : 'Token not found.'); |
| 51 | } |
| 52 | } |