Close anonymous write access to the public API and repair the broken test suite
Deploy Backend / deploy (push) Has been cancelled
Deploy Backend / deploy (push) Has been cancelled
Every mutating endpoint was reachable without authentication, so any visitor
could create, edit or delete posts, categories, tags, projects and about-me
records on the live site.
Security
- Split routes into an anonymous read-only group and a write group gated by
`auth:sanctum` + a new `admin` middleware.
- Add `is_admin` to users; Sanctum token support on the User model.
- Add AuthController (login / me / logout). The Sanctum token is delivered in
an httpOnly cookie and never returned in the JSON body, because the admin
panel reaches the API through a Next.js server-side proxy that breaks
Sanctum's first-party domain detection.
- AuthenticateAdminPanelSession promotes that cookie to a bearer header so
Sanctum's normal validation, expiry and revocation still apply.
- Remove the unauthenticated `/user/{id}` route, which exposed user emails.
- Non-admin accounts are refused at login and the failure shape is identical
to a bad password, so the endpoint cannot enumerate accounts.
- Fix `Route [login] not defined`: a non-JSON unauthenticated request resolved
a route that does not exist in this API-only app and returned 500.
- Reject invalid list query parameters with 422 instead of 500, and cap
per_page at 50 (`?per_page=100000` previously dumped whole tables).
Correctness
- Make the translation migration portable. It used MySQL-only JSON_OBJECTAGG,
which aborted all 29 tests during migration; the data collapse now runs in
PHP so it works on MySQL, MariaDB and SQLite.
- Add HasJsonTranslations trait providing the missing setTranslation(), which
made project create/update return 500, and replace five copy-pasted
getTranslation()/hasTranslation() bodies.
- Make posts.excerpt nullable to match StorePostRequest; omitting an excerpt
was a guaranteed SQL integrity error.
- Route the AboutMeController CRUD methods that existed but were never
registered.
- CategoryTest omitted a required description; fixed the test, the existing
schema and validation already agreed.
Tests: 83 passing / 126 assertions (was 29 failing / 0 assertions)
This commit is contained in:
1 parent
35686d82c3
commit
d2f6bd4d7d
29 files changed
+1002
-188
No files matched your search
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\UserResource;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* Name given to the personal access token backing the admin panel
|
||||
* session, so it can be revoked from `php artisan sanctum` output.
|
||||
*/
|
||||
private const TOKEN_NAME = 'admin-panel';
|
||||
|
||||
/**
|
||||
* Cookie carrying the Sanctum token. It is httpOnly so no client-side
|
||||
* JavaScript can read it, and the value is never echoed in the JSON body.
|
||||
*
|
||||
* The admin panel lives behind a Next.js server-side proxy, which is why
|
||||
* the token is carried this way rather than relying on Sanctum's
|
||||
* first-party (stateful) domain detection: a proxied request does not
|
||||
* always carry an Origin/Referer the backend recognises as stateful.
|
||||
*/
|
||||
public const SESSION_COOKIE = 'parsaaghayi_admin_session';
|
||||
|
||||
public function login(Request $request): JsonResponse
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string'],
|
||||
'remember' => ['sometimes', 'boolean'],
|
||||
]);
|
||||
|
||||
if (! Auth::attempt(['email' => $credentials['email'], 'password' => $credentials['password']], (bool) ($credentials['remember'] ?? false))) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
// A valid but non-admin account must not be able to hold a session,
|
||||
// and must not be distinguishable from a bad password.
|
||||
if (! $user->isAdmin()) {
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
// One live session at a time for the admin panel.
|
||||
$user->tokens()->where('name', self::TOKEN_NAME)->delete();
|
||||
|
||||
$token = $user->createToken(self::TOKEN_NAME)->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'user' => new UserResource($user),
|
||||
])->cookie($this->makeCookie($token, (int) ($credentials['remember'] ?? false) ? 1209600 : null));
|
||||
}
|
||||
|
||||
public function me(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (! $user->isAdmin()) {
|
||||
return response()->json(['message' => 'This action is unauthorized.'], 403);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'user' => new UserResource($user),
|
||||
]);
|
||||
}
|
||||
|
||||
public function logout(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user) {
|
||||
$user->tokens()->where('name', self::TOKEN_NAME)->delete();
|
||||
|
||||
Auth::guard('web')->logout();
|
||||
}
|
||||
|
||||
return response()->json(['message' => 'Logged out.'])
|
||||
->withoutCookie(self::SESSION_COOKIE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Cookie
|
||||
*/
|
||||
private function makeCookie(string $token, ?int $minutes)
|
||||
{
|
||||
return cookie(
|
||||
name: self::SESSION_COOKIE,
|
||||
value: $token,
|
||||
minutes: $minutes,
|
||||
path: '/',
|
||||
domain: config('session.domain'),
|
||||
secure: (bool) config('session.secure', true),
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap helper: promote an existing account to admin from the CLI.
|
||||
*/
|
||||
public static function grantAdmin(string $email): ?User
|
||||
{
|
||||
$user = User::where('email', $email)->first();
|
||||
|
||||
return $user?->forceFill(['is_admin' => true])->save() ? $user : null;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Blog;
|
||||
|
||||
use App\Http\Controllers\Concerns\ValidatesListQuery;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Blog\StoreCategoryRequest;
|
||||
use App\Http\Requests\Blog\UpdateCategoryRequest;
|
||||
@@ -15,32 +16,36 @@ use Illuminate\Http\Request;
|
||||
*/
|
||||
class CategoryController extends Controller
|
||||
{
|
||||
use ValidatesListQuery;
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/blog/categories",
|
||||
* tags={"Categories"},
|
||||
* summary="Paginated list of categories",
|
||||
*
|
||||
* @OA\Parameter(name="per_page", in="query", @OA\Schema(type="integer")),
|
||||
* @OA\Parameter(name="filter", in="query", @OA\Schema(type="string")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
public function index(Request $request)
|
||||
{
|
||||
$filter = $request->input('filter');
|
||||
$sortBy = $request->input('sort_by', 'created_at');
|
||||
$sortDirection = $request->input('sort_direction', 'desc');
|
||||
$perPage = $request->input('per_page', 10);
|
||||
$params = $this->listQuery(
|
||||
$request,
|
||||
['name', 'slug', 'created_at', 'updated_at']
|
||||
);
|
||||
|
||||
$query = Category::with('posts');
|
||||
|
||||
if (!empty($filter)) {
|
||||
$query->where('name', 'like', '%' . $filter . '%');
|
||||
if ($request->filled('filter')) {
|
||||
$query->where('name', 'like', '%'.$request->string('filter').'%');
|
||||
}
|
||||
|
||||
$query->orderBy($sortBy, $sortDirection);
|
||||
$query->orderBy($params['sort'], $params['direction']);
|
||||
|
||||
$categories = $query->paginate($perPage);
|
||||
$categories = $query->paginate($params['per_page']);
|
||||
|
||||
return CategoryResource::collection($categories);
|
||||
}
|
||||
@@ -50,13 +55,16 @@ class CategoryController extends Controller
|
||||
* path="/blog/categories/{id}",
|
||||
* tags={"Categories"},
|
||||
* summary="Get a category by ID",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$category = Category::with('posts')->findOrFail($id);
|
||||
|
||||
return new CategoryResource($category);
|
||||
}
|
||||
|
||||
@@ -65,8 +73,10 @@ class CategoryController extends Controller
|
||||
* path="/blog/categories/{slug}/posts",
|
||||
* tags={"Categories"},
|
||||
* summary="Get posts by category slug",
|
||||
*
|
||||
* @OA\Parameter(name="slug", in="path", required=true, @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="per_page", in="query", @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK"),
|
||||
* @OA\Response(response=404, description="Category not found")
|
||||
* )
|
||||
@@ -75,9 +85,9 @@ class CategoryController extends Controller
|
||||
{
|
||||
$category = Category::where('slug', $slug)->first();
|
||||
|
||||
if (!$category) {
|
||||
if (! $category) {
|
||||
return response()->json([
|
||||
'message' => 'Category not found.'
|
||||
'message' => 'Category not found.',
|
||||
], 404);
|
||||
}
|
||||
|
||||
@@ -88,8 +98,8 @@ class CategoryController extends Controller
|
||||
|
||||
$postsQuery = $category->posts()->with(['category', 'tags', 'author']);
|
||||
|
||||
if (!empty($filter)) {
|
||||
$postsQuery->where('title', 'like', '%' . $filter . '%');
|
||||
if (! empty($filter)) {
|
||||
$postsQuery->where('title', 'like', '%'.$filter.'%');
|
||||
}
|
||||
|
||||
$postsQuery->orderBy($sortBy, $sortDirection);
|
||||
@@ -125,13 +135,16 @@ class CategoryController extends Controller
|
||||
* path="/blog/categories",
|
||||
* tags={"Categories"},
|
||||
* summary="Create a category",
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=201, description="Created")
|
||||
* )
|
||||
*/
|
||||
public function store(StoreCategoryRequest $request)
|
||||
{
|
||||
$category = Category::create($request->validated());
|
||||
|
||||
return new CategoryResource($category);
|
||||
}
|
||||
|
||||
@@ -140,8 +153,11 @@ class CategoryController extends Controller
|
||||
* path="/blog/categories/{id}",
|
||||
* tags={"Categories"},
|
||||
* summary="Update a category",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -149,6 +165,7 @@ class CategoryController extends Controller
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
$category->update($request->validated());
|
||||
|
||||
return new CategoryResource($category);
|
||||
}
|
||||
|
||||
@@ -157,7 +174,9 @@ class CategoryController extends Controller
|
||||
* path="/blog/categories/{id}",
|
||||
* tags={"Categories"},
|
||||
* summary="Delete a category",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -165,6 +184,7 @@ class CategoryController extends Controller
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
$category->delete();
|
||||
|
||||
return response()->json(['message' => 'Category deleted successfully'], 200);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Blog;
|
||||
|
||||
use App\Http\Controllers\Concerns\ValidatesListQuery;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Blog\StorePostRequest;
|
||||
use App\Http\Requests\Blog\UpdatePostRequest;
|
||||
@@ -14,17 +15,21 @@ use Illuminate\Http\Request;
|
||||
*/
|
||||
class PostController extends Controller
|
||||
{
|
||||
use ValidatesListQuery;
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/blog/posts",
|
||||
* tags={"Posts"},
|
||||
* summary="Paginated list of posts",
|
||||
*
|
||||
* @OA\Parameter(name="per_page", in="query", @OA\Schema(type="integer")),
|
||||
* @OA\Parameter(name="category", in="query", @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="tag", in="query", @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="search", in="query", @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="sort_field", in="query", @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="sort_direction", in="query", @OA\Schema(type="string", enum={"asc","desc"})),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -32,16 +37,19 @@ class PostController extends Controller
|
||||
{
|
||||
$filters = $request->only(['category', 'tag', 'search', 'author', 'published']);
|
||||
|
||||
$sortField = $request->get('sort_field', 'published_at');
|
||||
$sortDirection = $request->get('sort_direction', 'desc');
|
||||
|
||||
$perPage = $request->get('per_page', 10);
|
||||
$params = $this->listQuery(
|
||||
$request,
|
||||
['published_at', 'views', 'likes', 'title'],
|
||||
'sort_field',
|
||||
'published_at',
|
||||
'desc'
|
||||
);
|
||||
|
||||
$query = Post::with(['category', 'tags', 'author'])
|
||||
->filter($filters)
|
||||
->sort($sortField, $sortDirection);
|
||||
->sort($params['sort'], $params['direction']);
|
||||
|
||||
$posts = $query->paginate($perPage);
|
||||
$posts = $query->paginate($params['per_page']);
|
||||
|
||||
return PostResource::collection($posts);
|
||||
}
|
||||
@@ -51,7 +59,9 @@ class PostController extends Controller
|
||||
* path="/blog/posts/{slug}",
|
||||
* tags={"Posts"},
|
||||
* summary="Get a single post by slug with related posts",
|
||||
*
|
||||
* @OA\Parameter(name="slug", in="path", required=true, @OA\Schema(type="string")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -72,7 +82,9 @@ class PostController extends Controller
|
||||
* path="/blog/posts",
|
||||
* tags={"Posts"},
|
||||
* summary="Create a post",
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=201, description="Created")
|
||||
* )
|
||||
*/
|
||||
@@ -92,8 +104,11 @@ class PostController extends Controller
|
||||
* path="/blog/posts/{id}",
|
||||
* tags={"Posts"},
|
||||
* summary="Update a post",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -114,7 +129,9 @@ class PostController extends Controller
|
||||
* path="/blog/posts/{id}",
|
||||
* tags={"Posts"},
|
||||
* summary="Delete a post",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\Blog;
|
||||
|
||||
use App\Http\Controllers\Concerns\ValidatesListQuery;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Blog\StoreTagRequest;
|
||||
use App\Http\Requests\Blog\UpdateTagRequest;
|
||||
@@ -14,17 +15,28 @@ use Illuminate\Http\Request;
|
||||
*/
|
||||
class TagController extends Controller
|
||||
{
|
||||
use ValidatesListQuery;
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/blog/tags",
|
||||
* tags={"Tags"},
|
||||
* summary="Paginated list of tags",
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
public function index(Request $request)
|
||||
{
|
||||
$tags = Tag::with('posts')->paginate(10);
|
||||
$params = $this->listQuery(
|
||||
$request,
|
||||
['name', 'slug', 'created_at', 'updated_at']
|
||||
);
|
||||
|
||||
$tags = Tag::with('posts')
|
||||
->orderBy($params['sort'], $params['direction'])
|
||||
->paginate($params['per_page']);
|
||||
|
||||
return TagResource::collection($tags);
|
||||
}
|
||||
|
||||
@@ -33,13 +45,16 @@ class TagController extends Controller
|
||||
* path="/blog/tags/{id}",
|
||||
* tags={"Tags"},
|
||||
* summary="Get a tag by ID",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$tag = Tag::with('posts')->findOrFail($id);
|
||||
|
||||
return new TagResource($tag);
|
||||
}
|
||||
|
||||
@@ -48,13 +63,16 @@ class TagController extends Controller
|
||||
* path="/blog/tags",
|
||||
* tags={"Tags"},
|
||||
* summary="Create a tag",
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=201, description="Created")
|
||||
* )
|
||||
*/
|
||||
public function store(StoreTagRequest $request)
|
||||
{
|
||||
$tag = Tag::create($request->validated());
|
||||
|
||||
return new TagResource($tag);
|
||||
}
|
||||
|
||||
@@ -63,8 +81,11 @@ class TagController extends Controller
|
||||
* path="/blog/tags/{id}",
|
||||
* tags={"Tags"},
|
||||
* summary="Update a tag",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=True, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\RequestBody(@OA\MediaType(mediaType="application/json")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -72,6 +93,7 @@ class TagController extends Controller
|
||||
{
|
||||
$tag = Tag::findOrFail($id);
|
||||
$tag->update($request->validated());
|
||||
|
||||
return new TagResource($tag);
|
||||
}
|
||||
|
||||
@@ -80,7 +102,9 @@ class TagController extends Controller
|
||||
* path="/blog/tags/{id}",
|
||||
* tags={"Tags"},
|
||||
* summary="Delete a tag",
|
||||
*
|
||||
* @OA\Parameter(name="id", in="path", required=True, @OA\Schema(type="integer")),
|
||||
*
|
||||
* @OA\Response(response=200, description="OK")
|
||||
* )
|
||||
*/
|
||||
@@ -89,6 +113,7 @@ class TagController extends Controller
|
||||
$tag = Tag::findOrFail($id);
|
||||
$tag->posts()->detach();
|
||||
$tag->delete();
|
||||
|
||||
return response()->json(['message' => 'Tag deleted successfully'], 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Concerns;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
trait ValidatesListQuery
|
||||
{
|
||||
/**
|
||||
* Validate the shared list-endpoint query parameters.
|
||||
*
|
||||
* `per_page` was previously read straight from the request, so
|
||||
* `?per_page=100000` returned the entire table in one response. Sort
|
||||
* columns and directions were also passed through unchecked, and
|
||||
* `?sort_direction=foo` made the query builder throw, turning a bad
|
||||
* query string into an HTTP 500.
|
||||
*
|
||||
* Invalid values are now rejected with a 422 and the sort field is
|
||||
* restricted to a per-endpoint allow-list.
|
||||
*
|
||||
* @param array<int, string> $sortable
|
||||
* @return array{per_page: int, page: int, sort: string, direction: string}
|
||||
*/
|
||||
protected function listQuery(
|
||||
Request $request,
|
||||
array $sortable,
|
||||
string $sortParam = 'sort_by',
|
||||
string $defaultSort = 'created_at',
|
||||
string $defaultDirection = 'desc',
|
||||
int $defaultPerPage = 10,
|
||||
int $maxPerPage = 50
|
||||
): array {
|
||||
$validated = $request->validate([
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:'.$maxPerPage],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
$sortParam => ['nullable', 'string', 'in:'.implode(',', $sortable)],
|
||||
'sort_direction' => ['nullable', 'string', 'in:asc,desc'],
|
||||
]);
|
||||
|
||||
return [
|
||||
'per_page' => (int) ($validated['per_page'] ?? $defaultPerPage),
|
||||
'page' => (int) ($validated['page'] ?? 1),
|
||||
'sort' => $validated[$sortParam] ?? $defaultSort,
|
||||
'direction' => $validated['sort_direction'] ?? $defaultDirection,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Http\Controllers\Api\AuthController;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Lets `auth:sanctum` authenticate from the admin-panel session cookie.
|
||||
*
|
||||
* Sanctum only reads a token from the Authorization header, but the admin
|
||||
* panel is reached through a Next.js proxy that forwards cookies rather than
|
||||
* headers. Promoting the cookie to a bearer header here keeps the token
|
||||
* httpOnly and out of JavaScript while leaving Sanctum's normal validation,
|
||||
* expiry and revocation behaviour fully intact.
|
||||
*/
|
||||
class AuthenticateAdminPanelSession
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (! $request->bearerToken()) {
|
||||
$token = $request->cookie(AuthController::SESSION_COOKIE);
|
||||
|
||||
if (is_string($token) && $token !== '') {
|
||||
$request->headers->set('Authorization', 'Bearer '.$token);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Second gate behind `auth:sanctum`: being authenticated is not enough to
|
||||
* change site content, the account also needs the admin flag.
|
||||
*/
|
||||
class EnsureUserIsAdmin
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if (! $user) {
|
||||
return response()->json(['message' => 'Unauthenticated.'], 401);
|
||||
}
|
||||
|
||||
if (! $user->isAdmin()) {
|
||||
return response()->json(['message' => 'This action is unauthorized.'], 403);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
|
||||
class UserResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
@@ -19,8 +19,11 @@ class UserResource extends JsonResource
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
// The admin panel needs this to decide whether to render
|
||||
// content-management controls.
|
||||
'is_admin' => (bool) $this->is_admin,
|
||||
'created_at' => Carbon::parse($this->created_at)->format('M d Y'),
|
||||
'updated_at' => Carbon::parse($this->updated_at)->format('M d Y'),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
/**
|
||||
* Locale-aware accessors for models that store translations in a single
|
||||
* `translations` JSON column, shaped as:
|
||||
*
|
||||
* ['title' => ['fa' => '...', 'en' => '...']]
|
||||
*
|
||||
* The website models each had their own copy-pasted getTranslation()/hasTranslation()
|
||||
* and no setTranslation() at all, which is why the project write endpoints
|
||||
* returned HTTP 500 in production. This trait replaces the duplicated bodies
|
||||
* and supplies the missing writer.
|
||||
*/
|
||||
trait HasJsonTranslations
|
||||
{
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
|
||||
if (! is_array($translations) || ! isset($translations[$key][$locale])) {
|
||||
if (! $useFallbackLocale) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$fallback = $this->getFallbackLocale();
|
||||
|
||||
return $translations[$key][$fallback] ?? null;
|
||||
}
|
||||
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a single locale's value. Call save() to persist.
|
||||
*/
|
||||
public function setTranslation(string $key, string $locale, mixed $value): static
|
||||
{
|
||||
$translations = $this->translations;
|
||||
$translations = is_array($translations) ? $translations : [];
|
||||
|
||||
$translations[$key][$locale] = $value;
|
||||
|
||||
$this->translations = $translations;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function hasTranslation(string $key, string $locale): bool
|
||||
{
|
||||
$translations = $this->translations;
|
||||
|
||||
return is_array($translations) && isset($translations[$key][$locale]);
|
||||
}
|
||||
|
||||
public function getFallbackLocale(): string
|
||||
{
|
||||
return (string) config('app.fallback_locale', 'en');
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -8,10 +8,11 @@ use App\Models\Blog\Post;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use HasFactory, Notifiable;
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
@@ -22,6 +23,7 @@ class User extends Authenticatable
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'is_admin',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -44,6 +46,7 @@ class User extends Authenticatable
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'is_admin' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -51,4 +54,12 @@ class User extends Authenticatable
|
||||
{
|
||||
return $this->hasMany(Post::class, 'author_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this user may modify site content.
|
||||
*/
|
||||
public function isAdmin(): bool
|
||||
{
|
||||
return (bool) $this->is_admin;
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
namespace App\Models\Website;
|
||||
|
||||
use App\Models\Concerns\HasJsonTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
|
||||
class AboutMe extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasJsonTranslations;
|
||||
|
||||
protected $table = 'website_about_me';
|
||||
protected $fillable = ['image',
|
||||
'translations',];
|
||||
|
||||
|
||||
protected $fillable = ['image',
|
||||
'translations', ];
|
||||
|
||||
public function skills()
|
||||
{
|
||||
@@ -25,24 +25,6 @@ class AboutMe extends Model
|
||||
'translations' => 'array',
|
||||
];
|
||||
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
if (isset($translations[$key][$locale])) {
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
if ($useFallbackLocale && isset($translations[$key]['en'])) {
|
||||
return $translations[$key]['en'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function hasTranslation(string $key, string $locale): bool
|
||||
{
|
||||
$translations = $this->translations;
|
||||
return isset($translations[$key][$locale]);
|
||||
}
|
||||
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
return $this->translations['title'] ?? null;
|
||||
@@ -52,5 +34,4 @@ class AboutMe extends Model
|
||||
{
|
||||
return $this->translations['description'] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
namespace App\Models\Website;
|
||||
|
||||
use App\Models\Concerns\HasJsonTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
|
||||
class Project extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasJsonTranslations;
|
||||
|
||||
protected $table = 'website_projects';
|
||||
protected $fillable = ['category_id', 'image1', 'image2',
|
||||
'translations',];
|
||||
|
||||
|
||||
protected $fillable = ['category_id', 'image1', 'image2',
|
||||
'translations', ];
|
||||
|
||||
public function category()
|
||||
{
|
||||
@@ -25,18 +25,6 @@ class Project extends Model
|
||||
'translations' => 'array',
|
||||
];
|
||||
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
if (isset($translations[$key][$locale])) {
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
if ($useFallbackLocale && isset($translations[$key]['en'])) {
|
||||
return $translations[$key]['en'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
return $this->translations['title'] ?? null;
|
||||
@@ -46,5 +34,4 @@ class Project extends Model
|
||||
{
|
||||
return $this->translations['description'] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,36 +2,24 @@
|
||||
|
||||
namespace App\Models\Website;
|
||||
|
||||
use App\Models\Concerns\HasJsonTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
|
||||
class ProjectCategory extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasJsonTranslations;
|
||||
|
||||
protected $table = 'website_project_categories';
|
||||
protected $fillable = ['image',
|
||||
'translations',];
|
||||
|
||||
|
||||
protected $fillable = ['image',
|
||||
'translations', ];
|
||||
|
||||
protected $casts = [
|
||||
'translations' => 'array',
|
||||
];
|
||||
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
if (isset($translations[$key][$locale])) {
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
if ($useFallbackLocale && isset($translations[$key]['en'])) {
|
||||
return $translations[$key]['en'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
return $this->translations['title'] ?? null;
|
||||
@@ -41,5 +29,4 @@ class ProjectCategory extends Model
|
||||
{
|
||||
return $this->translations['description'] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,14 +2,17 @@
|
||||
|
||||
namespace App\Models\Website;
|
||||
|
||||
use App\Models\Concerns\HasJsonTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Service extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasJsonTranslations;
|
||||
|
||||
protected $table = 'website_services';
|
||||
|
||||
protected $fillable = ['imageSrc',
|
||||
'translations'];
|
||||
|
||||
@@ -17,18 +20,6 @@ class Service extends Model
|
||||
'translations' => 'array',
|
||||
];
|
||||
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
if (isset($translations[$key][$locale])) {
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
if ($useFallbackLocale && isset($translations[$key]['en'])) {
|
||||
return $translations[$key]['en'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
return $this->translations['title'] ?? null;
|
||||
@@ -38,4 +29,4 @@ class Service extends Model
|
||||
{
|
||||
return $this->translations['description'] ?? null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
namespace App\Models\Website;
|
||||
|
||||
use App\Models\Concerns\HasJsonTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
|
||||
class Skill extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use HasJsonTranslations;
|
||||
|
||||
protected $table = 'website_skills';
|
||||
protected $fillable = ['image', 'link', 'about_me_id', 'percentage',
|
||||
'translations',];
|
||||
|
||||
|
||||
protected $fillable = ['image', 'link', 'about_me_id', 'percentage',
|
||||
'translations', ];
|
||||
|
||||
public function aboutMe()
|
||||
{
|
||||
@@ -25,18 +25,6 @@ class Skill extends Model
|
||||
'translations' => 'array',
|
||||
];
|
||||
|
||||
public function getTranslation(string $key, string $locale, bool $useFallbackLocale = true): mixed
|
||||
{
|
||||
$translations = $this->translations;
|
||||
if (isset($translations[$key][$locale])) {
|
||||
return $translations[$key][$locale];
|
||||
}
|
||||
if ($useFallbackLocale && isset($translations[$key]['en'])) {
|
||||
return $translations[$key]['en'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
return $this->translations['title'] ?? null;
|
||||
@@ -46,5 +34,4 @@ class Skill extends Model
|
||||
{
|
||||
return $this->translations['description'] ?? null;
|
||||
}
|
||||
|
||||
}
|
||||
+23
-2
@@ -1,5 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Middleware\AuthenticateAdminPanelSession;
|
||||
use App\Http\Middleware\EnsureUserIsAdmin;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
@@ -12,8 +14,27 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware) {
|
||||
//
|
||||
// Let the Next.js admin panel authenticate with a Sanctum session
|
||||
// cookie issued on the same registrable domain, instead of shipping a
|
||||
// bearer token to JavaScript.
|
||||
$middleware->statefulApi();
|
||||
|
||||
$middleware->api(prepend: [
|
||||
AuthenticateAdminPanelSession::class,
|
||||
]);
|
||||
|
||||
$middleware->alias([
|
||||
'admin' => EnsureUserIsAdmin::class,
|
||||
]);
|
||||
|
||||
// This is an API-only application with no `login` route. Without this,
|
||||
// an unauthenticated write request that does not advertise JSON (a
|
||||
// plain form POST or curl) resolves `route('login')` and dies with
|
||||
// "Route [login] not defined" instead of a 401.
|
||||
$middleware->redirectGuestsTo(fn () => null);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions) {
|
||||
//
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
fn ($request) => $request->is('api/*') || $request->expectsJson()
|
||||
);
|
||||
})->create();
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
|
||||
* @extends Factory<User>
|
||||
*/
|
||||
class UserFactory extends Factory
|
||||
{
|
||||
@@ -37,8 +38,18 @@ class UserFactory extends Factory
|
||||
*/
|
||||
public function unverified(): static
|
||||
{
|
||||
return $this->state(fn(array $attributes) => [
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'email_verified_at' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* An account allowed to modify site content.
|
||||
*/
|
||||
public function admin(): static
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'is_admin' => true,
|
||||
]);
|
||||
}
|
||||
}
|
||||
+99
-53
@@ -2,72 +2,118 @@
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Collapse the legacy "<table>_translations" rows into locale => value JSON
|
||||
* on the parent table.
|
||||
*
|
||||
* Written in PHP rather than MySQL's JSON_OBJECTAGG so the migration runs
|
||||
* on MySQL, MariaDB and SQLite alike. The previous implementation used
|
||||
* `UPDATE <table> alias SET alias.col = (SELECT JSON_OBJECTAGG(...))`,
|
||||
* which is MySQL-only and aborted the entire test suite during migration.
|
||||
*/
|
||||
private function collapseTranslations(string $table, string $foreignKey, array $columns): void
|
||||
{
|
||||
$translationsTable = $table.'_translations';
|
||||
|
||||
if (! Schema::hasTable($table) || ! Schema::hasTable($translationsTable)) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table($table)->orderBy('id')->chunkById(200, function ($parents) use ($table, $translationsTable, $foreignKey, $columns) {
|
||||
foreach ($parents as $parent) {
|
||||
$rows = DB::table($translationsTable)->where($foreignKey, $parent->id)->get();
|
||||
|
||||
$update = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$map = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if (isset($row->{$column}) && $row->{$column} !== null) {
|
||||
$map[$row->locale] = $row->{$column};
|
||||
}
|
||||
}
|
||||
|
||||
$update[$column] = $map === []
|
||||
? null
|
||||
: json_encode($map, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
|
||||
if ($update !== []) {
|
||||
DB::table($table)->where('id', $parent->id)->update($update);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
// Add JSON columns for spatie/laravel-translatable on website_about_me
|
||||
Schema::table('website_about_me', function (Blueprint $table) {
|
||||
if (!Schema::hasColumn('website_about_me', 'title')) {
|
||||
$table->json('title')->nullable()->after('image');
|
||||
}
|
||||
if (!Schema::hasColumn('website_about_me', 'description')) {
|
||||
$table->json('description')->nullable()->after('title');
|
||||
}
|
||||
});
|
||||
// `Schema::hasColumn()` is checked up front: calling it inside the
|
||||
// `Schema::table()` closure issues a query mid-DDL, which implicitly
|
||||
// commits on MySQL.
|
||||
$addAboutMeTitle = ! Schema::hasColumn('website_about_me', 'title');
|
||||
$addAboutMeDescription = ! Schema::hasColumn('website_about_me', 'description');
|
||||
|
||||
// Migrate data from translations table to JSON columns
|
||||
DB::statement('
|
||||
UPDATE website_about_me a
|
||||
SET a.title = (
|
||||
SELECT JSON_OBJECTAGG(locale, title)
|
||||
FROM website_about_me_translations t
|
||||
WHERE t.about_me_id = a.id
|
||||
),
|
||||
a.description = (
|
||||
SELECT JSON_OBJECTAGG(locale, description)
|
||||
FROM website_about_me_translations t
|
||||
WHERE t.about_me_id = a.id
|
||||
)
|
||||
');
|
||||
if ($addAboutMeTitle || $addAboutMeDescription) {
|
||||
Schema::table('website_about_me', function (Blueprint $table) use ($addAboutMeTitle, $addAboutMeDescription) {
|
||||
if ($addAboutMeTitle) {
|
||||
$table->json('title')->nullable()->after('image');
|
||||
}
|
||||
|
||||
// Add JSON columns for spatie/laravel-translatable on website_skills
|
||||
Schema::table('website_skills', function (Blueprint $table) {
|
||||
if (!Schema::hasColumn('website_skills', 'title')) {
|
||||
$table->json('title')->nullable()->after('image');
|
||||
}
|
||||
if (!Schema::hasColumn('website_skills', 'description')) {
|
||||
$table->json('description')->nullable()->after('title');
|
||||
}
|
||||
});
|
||||
if ($addAboutMeDescription) {
|
||||
$table->json('description')->nullable()->after('title');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Migrate data from skill translations table to JSON columns
|
||||
DB::statement('
|
||||
UPDATE website_skills s
|
||||
SET s.title = (
|
||||
SELECT JSON_OBJECTAGG(locale, title)
|
||||
FROM website_skill_translations t
|
||||
WHERE t.skill_id = s.id
|
||||
),
|
||||
s.description = (
|
||||
SELECT JSON_OBJECTAGG(locale, description)
|
||||
FROM website_skill_translations t
|
||||
WHERE t.skill_id = s.id
|
||||
)
|
||||
');
|
||||
$this->collapseTranslations('website_about_me', 'about_me_id', ['title', 'description']);
|
||||
|
||||
$addSkillTitle = ! Schema::hasColumn('website_skills', 'title');
|
||||
$addSkillDescription = ! Schema::hasColumn('website_skills', 'description');
|
||||
|
||||
if ($addSkillTitle || $addSkillDescription) {
|
||||
Schema::table('website_skills', function (Blueprint $table) use ($addSkillTitle, $addSkillDescription) {
|
||||
if ($addSkillTitle) {
|
||||
$table->json('title')->nullable()->after('image');
|
||||
}
|
||||
|
||||
if ($addSkillDescription) {
|
||||
$table->json('description')->nullable()->after('title');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$this->collapseTranslations('website_skills', 'skill_id', ['title', 'description']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('website_about_me', function (Blueprint $table) {
|
||||
$table->dropColumn(['title', 'description']);
|
||||
});
|
||||
// Guarded to mirror up(): the columns may predate this migration.
|
||||
$aboutMe = array_values(array_filter(
|
||||
['title', 'description'],
|
||||
fn (string $column) => Schema::hasColumn('website_about_me', $column)
|
||||
));
|
||||
|
||||
Schema::table('website_skills', function (Blueprint $table) {
|
||||
$table->dropColumn(['title', 'description']);
|
||||
});
|
||||
if ($aboutMe !== []) {
|
||||
Schema::table('website_about_me', function (Blueprint $table) use ($aboutMe) {
|
||||
$table->dropColumn($aboutMe);
|
||||
});
|
||||
}
|
||||
|
||||
$skills = array_values(array_filter(
|
||||
['title', 'description'],
|
||||
fn (string $column) => Schema::hasColumn('website_skills', $column)
|
||||
));
|
||||
|
||||
if ($skills !== []) {
|
||||
Schema::table('website_skills', function (Blueprint $table) use ($skills) {
|
||||
$table->dropColumn($skills);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* StorePostRequest declares `excerpt` as nullable, but the column was
|
||||
* created NOT NULL, so every request that legitimately omitted an excerpt
|
||||
* died with a SQL integrity error (HTTP 500). Align the schema with the
|
||||
* already-published validation contract.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->text('excerpt')->nullable()->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// Backfill first: existing NULLs would otherwise fail the NOT NULL
|
||||
// constraint when rolling back.
|
||||
DB::table('posts')
|
||||
->whereNull('excerpt')
|
||||
->update(['excerpt' => '']);
|
||||
|
||||
Schema::table('posts', function (Blueprint $table) {
|
||||
$table->text('excerpt')->nullable(false)->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Every write endpoint on this API was previously reachable without any
|
||||
* authentication, which let anonymous visitors create/edit/delete content.
|
||||
* Authorisation is enforced by the `admin` middleware, which requires this
|
||||
* flag in addition to a valid Sanctum session.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasColumn('users', 'is_admin')) {
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->boolean('is_admin')->default(false)->after('password');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (Schema::hasColumn('users', 'is_admin')) {
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->dropColumn('is_admin');
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
+76
-11
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use App\Http\Controllers\Api\AuthController;
|
||||
use App\Http\Controllers\Api\Blog\CategoryController;
|
||||
use App\Http\Controllers\Api\Blog\HomeController;
|
||||
use App\Http\Controllers\Api\Blog\PostController;
|
||||
@@ -8,26 +8,91 @@ use App\Http\Controllers\Api\Blog\TagController;
|
||||
use App\Http\Controllers\Api\Website\AboutMeController;
|
||||
use App\Http\Controllers\Api\Website\ProjectController;
|
||||
use App\Http\Controllers\Api\Website\ServiceController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication
|
||||
|--------------------------------------------------------------------------
|
||||
| Used by the admin panel. Login is throttled hard because it is the one
|
||||
| endpoint that accepts attacker-controlled credentials.
|
||||
*/
|
||||
|
||||
Route::post('auth/login', [AuthController::class, 'login'])
|
||||
->middleware('throttle:5,1')
|
||||
->name('auth.login');
|
||||
|
||||
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||
Route::get('auth/me', [AuthController::class, 'me'])->name('auth.me');
|
||||
Route::post('auth/logout', [AuthController::class, 'logout'])->name('auth.logout');
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Public read API
|
||||
|--------------------------------------------------------------------------
|
||||
| Anonymous, cacheable, GET-only. Nothing here can change state.
|
||||
*/
|
||||
|
||||
Route::middleware('throttle:60,1')->group(function () {
|
||||
Route::prefix('website')->group(function () {
|
||||
Route::get('about-me', [AboutMeController::class, 'index']);
|
||||
Route::get('about-me/{id}', [AboutMeController::class, 'show']);
|
||||
Route::get('about-me/{id}/translation/{locale}', [AboutMeController::class, 'getTranslation']);
|
||||
|
||||
Route::get('services/{locale}', [ServiceController::class, 'index']);
|
||||
Route::get('services/{id}/translation/{locale}', [ServiceController::class, 'showTranslation']);
|
||||
Route::group(['prefix' => 'projects'], function () {
|
||||
Route::get('/translation/{locale}', [ProjectController::class, 'index']);
|
||||
Route::get('/{id}/translation/{locale}', [ProjectController::class, 'show']);
|
||||
Route::post('/', [ProjectController::class, 'store']);
|
||||
Route::put('/{id}', [ProjectController::class, 'update']);
|
||||
Route::delete('/{id}', [ProjectController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::get('projects/translation/{locale}', [ProjectController::class, 'index']);
|
||||
Route::get('projects/{id}/translation/{locale}', [ProjectController::class, 'show']);
|
||||
});
|
||||
|
||||
Route::prefix('blog')->group(function () {
|
||||
Route::apiResource('posts', PostController::class);
|
||||
Route::apiResource('categories', CategoryController::class);
|
||||
Route::apiResource('tags', TagController::class);
|
||||
Route::get('homepage', [HomeController::class, 'index']);
|
||||
|
||||
Route::get('posts', [PostController::class, 'index']);
|
||||
Route::get('posts/{slug}', [PostController::class, 'show']);
|
||||
|
||||
Route::get('categories', [CategoryController::class, 'index']);
|
||||
Route::get('categories/{id}', [CategoryController::class, 'show']);
|
||||
Route::get('categories/{slug}/posts', [CategoryController::class, 'getCategoryWithPosts']);
|
||||
|
||||
Route::get('tags', [TagController::class, 'index']);
|
||||
Route::get('tags/{id}', [TagController::class, 'show']);
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Admin write API
|
||||
|--------------------------------------------------------------------------
|
||||
| Every mutating endpoint requires an authenticated admin. These routes were
|
||||
| previously anonymous, which allowed anyone to create, edit or delete every
|
||||
| post, category, tag, project and about-me record on the live site.
|
||||
*/
|
||||
|
||||
Route::middleware(['auth:sanctum', 'admin', 'throttle:30,1'])->group(function () {
|
||||
Route::prefix('website')->group(function () {
|
||||
Route::post('about-me', [AboutMeController::class, 'store']);
|
||||
Route::put('about-me/{id}', [AboutMeController::class, 'update']);
|
||||
Route::delete('about-me/{id}', [AboutMeController::class, 'destroy']);
|
||||
|
||||
Route::post('projects', [ProjectController::class, 'store']);
|
||||
Route::put('projects/{id}', [ProjectController::class, 'update']);
|
||||
Route::delete('projects/{id}', [ProjectController::class, 'destroy']);
|
||||
});
|
||||
|
||||
Route::prefix('blog')->group(function () {
|
||||
Route::post('posts', [PostController::class, 'store']);
|
||||
Route::put('posts/{id}', [PostController::class, 'update']);
|
||||
Route::delete('posts/{id}', [PostController::class, 'destroy']);
|
||||
|
||||
Route::post('categories', [CategoryController::class, 'store']);
|
||||
Route::put('categories/{id}', [CategoryController::class, 'update']);
|
||||
Route::delete('categories/{id}', [CategoryController::class, 'destroy']);
|
||||
|
||||
Route::post('tags', [TagController::class, 'store']);
|
||||
Route::put('tags/{id}', [TagController::class, 'update']);
|
||||
Route::delete('tags/{id}', [TagController::class, 'destroy']);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use App\Http\Resources\UserResource;
|
||||
use App\Models\User;
|
||||
|
||||
Route::get('/', function () {
|
||||
return view('welcome');
|
||||
});
|
||||
|
||||
Route::get('/user/{id}', function (string $id) {
|
||||
return new UserResource(User::findOrFail($id));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Controllers\Api\AuthController;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Regression coverage for the authorisation hole where every mutating endpoint
|
||||
* on the public API was anonymous, letting any visitor rewrite the whole site.
|
||||
*/
|
||||
class AdminAuthorisationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public static function mutatingRouteProvider(): array
|
||||
{
|
||||
return [
|
||||
'create about me' => ['POST', '/api/website/about-me'],
|
||||
'update about me' => ['PUT', '/api/website/about-me/1'],
|
||||
'delete about me' => ['DELETE', '/api/website/about-me/1'],
|
||||
|
||||
'create project' => ['POST', '/api/website/projects'],
|
||||
'update project' => ['PUT', '/api/website/projects/1'],
|
||||
'delete project' => ['DELETE', '/api/website/projects/1'],
|
||||
|
||||
'create post' => ['POST', '/api/blog/posts'],
|
||||
'update post' => ['PUT', '/api/blog/posts/1'],
|
||||
'delete post' => ['DELETE', '/api/blog/posts/1'],
|
||||
|
||||
'create category' => ['POST', '/api/blog/categories'],
|
||||
'update category' => ['PUT', '/api/blog/categories/1'],
|
||||
'delete category' => ['DELETE', '/api/blog/categories/1'],
|
||||
|
||||
'create tag' => ['POST', '/api/blog/tags'],
|
||||
'update tag' => ['PUT', '/api/blog/tags/1'],
|
||||
'delete tag' => ['DELETE', '/api/blog/tags/1'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('mutatingRouteProvider')]
|
||||
public function test_anonymous_requests_cannot_reach_write_endpoints(string $method, string $uri): void
|
||||
{
|
||||
$this->call($method, $uri)->assertUnauthorized();
|
||||
}
|
||||
|
||||
#[DataProvider('mutatingRouteProvider')]
|
||||
public function test_authenticated_non_admins_cannot_reach_write_endpoints(string $method, string $uri): void
|
||||
{
|
||||
Sanctum::actingAs(User::factory()->create());
|
||||
|
||||
$this->call($method, $uri)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_public_reads_remain_available_anonymously(): void
|
||||
{
|
||||
$this->getJson('/api/website/about-me')->assertOk();
|
||||
$this->getJson('/api/website/services/fa')->assertOk();
|
||||
$this->getJson('/api/blog/posts')->assertOk();
|
||||
$this->getJson('/api/blog/categories')->assertOk();
|
||||
$this->getJson('/api/blog/tags')->assertOk();
|
||||
}
|
||||
|
||||
public function test_user_email_endpoint_is_no_longer_public(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->getJson("/user/{$user->id}")->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_admin_can_log_in_and_receives_a_session_cookie(): void
|
||||
{
|
||||
$admin = User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$response = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('user.email', 'admin@parsaaghayi.ir')
|
||||
->assertCookie(AuthController::SESSION_COOKIE);
|
||||
|
||||
// The token must never be readable by client-side JavaScript.
|
||||
$cookie = $response->headers->getCookies()[0] ?? null;
|
||||
$this->assertNotNull($cookie);
|
||||
$this->assertTrue($cookie->isHttpOnly());
|
||||
$this->assertArrayNotHasKey('token', $response->json());
|
||||
|
||||
$this->assertSame(1, $admin->tokens()->count());
|
||||
}
|
||||
|
||||
public function test_login_rejects_a_valid_non_admin_account(): void
|
||||
{
|
||||
User::factory()->create([
|
||||
'email' => 'user@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$this->postJson('/api/auth/login', [
|
||||
'email' => 'user@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
])->assertUnprocessable();
|
||||
|
||||
$this->assertDatabaseCount('personal_access_tokens', 0);
|
||||
}
|
||||
|
||||
public function test_login_rejects_a_bad_password_without_revealing_which_field_failed(): void
|
||||
{
|
||||
User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'correct-horse-battery',
|
||||
]);
|
||||
|
||||
$wrongPassword = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$unknownAccount = $this->postJson('/api/auth/login', [
|
||||
'email' => 'nobody@parsaaghayi.ir',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$wrongPassword->assertUnprocessable();
|
||||
$unknownAccount->assertUnprocessable();
|
||||
|
||||
// Identical error shape, so the endpoint cannot be used to enumerate
|
||||
// which email addresses have accounts.
|
||||
$this->assertSame(
|
||||
array_keys($wrongPassword->json('errors')),
|
||||
array_keys($unknownAccount->json('errors'))
|
||||
);
|
||||
}
|
||||
|
||||
public function test_auth_me_requires_authentication(): void
|
||||
{
|
||||
$this->getJson('/api/auth/me')->assertUnauthorized();
|
||||
}
|
||||
|
||||
public function test_session_cookie_authenticates_requests(): void
|
||||
{
|
||||
User::factory()->admin()->create([
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$login = $this->postJson('/api/auth/login', [
|
||||
'email' => 'admin@parsaaghayi.ir',
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$token = $login->headers->getCookies()[0]->getValue();
|
||||
|
||||
// No Authorization header: the cookie alone must authenticate, which is
|
||||
// how the Next.js proxy will call the API.
|
||||
$this->withCookie(AuthController::SESSION_COOKIE, $token)
|
||||
->getJson('/api/auth/me')
|
||||
->assertOk()
|
||||
->assertJsonPath('user.is_admin', true);
|
||||
}
|
||||
|
||||
public function test_logout_revokes_the_admin_panel_token(): void
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$this->postJson('/api/auth/logout')->assertOk();
|
||||
|
||||
$this->assertDatabaseCount('personal_access_tokens', 0);
|
||||
}
|
||||
}
|
||||
@@ -40,9 +40,12 @@ class CategoryTest extends TestCase
|
||||
|
||||
public function test_can_create_category()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/blog/categories', [
|
||||
'name' => 'Tech',
|
||||
'slug' => 'tech',
|
||||
'description' => 'Everything related to software engineering.',
|
||||
]);
|
||||
|
||||
$response->assertStatus(201);
|
||||
@@ -51,6 +54,8 @@ class CategoryTest extends TestCase
|
||||
|
||||
public function test_can_delete_category()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$category = Category::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/categories/{$category->id}");
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace Tests\Feature\Blog;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use App\Models\Blog\Post;
|
||||
use App\Models\Blog\Tag;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
@@ -34,6 +33,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_create_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$category = Category::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
@@ -51,6 +52,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_update_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$post = Post::factory()->create();
|
||||
|
||||
$response = $this->putJson("/api/blog/posts/{$post->id}", [
|
||||
@@ -62,6 +65,8 @@ class PostTest extends TestCase
|
||||
|
||||
public function test_can_delete_post()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$post = Post::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/posts/{$post->id}");
|
||||
|
||||
@@ -30,6 +30,8 @@ class TagTest extends TestCase
|
||||
|
||||
public function test_can_create_tag()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/blog/tags', [
|
||||
'name' => 'Laravel',
|
||||
'slug' => 'laravel',
|
||||
@@ -41,6 +43,8 @@ class TagTest extends TestCase
|
||||
|
||||
public function test_can_delete_tag()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$tag = Tag::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/blog/tags/{$tag->id}");
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Blog\Category;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* The list endpoints previously forwarded raw request input into
|
||||
* `orderBy()` and `paginate()`, so a bad query string produced an HTTP 500
|
||||
* and `per_page` was unbounded.
|
||||
*/
|
||||
class ListQueryValidationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string}>
|
||||
*/
|
||||
public static function badQueryProvider(): array
|
||||
{
|
||||
return [
|
||||
'categories bad direction' => ['/api/blog/categories?sort_direction=foo'],
|
||||
'categories unknown column' => ['/api/blog/categories?sort_by=no_such_column'],
|
||||
'categories oversized page' => ['/api/blog/categories?per_page=100000'],
|
||||
'categories zero page size' => ['/api/blog/categories?per_page=0'],
|
||||
'posts unknown sort column' => ['/api/blog/posts?sort_field=password'],
|
||||
'posts oversized page' => ['/api/blog/posts?per_page=9999'],
|
||||
'tags bad direction' => ['/api/blog/tags?sort_direction=sideways'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('badQueryProvider')]
|
||||
public function test_invalid_list_parameters_are_rejected(string $url): void
|
||||
{
|
||||
$this->getJson($url)->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{0: string}>
|
||||
*/
|
||||
public static function goodQueryProvider(): array
|
||||
{
|
||||
return [
|
||||
'categories default' => ['/api/blog/categories'],
|
||||
'categories max page size' => ['/api/blog/categories?per_page=50'],
|
||||
'categories valid sort' => ['/api/blog/categories?sort_by=name&sort_direction=asc'],
|
||||
'categories filter' => ['/api/blog/categories?filter=web'],
|
||||
'posts default' => ['/api/blog/posts'],
|
||||
'posts valid sort' => ['/api/blog/posts?sort_field=views&sort_direction=asc'],
|
||||
'tags default' => ['/api/blog/tags'],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('goodQueryProvider')]
|
||||
public function test_valid_list_parameters_are_accepted(string $url): void
|
||||
{
|
||||
$this->getJson($url)->assertOk();
|
||||
}
|
||||
|
||||
public function test_page_size_is_capped(): void
|
||||
{
|
||||
Category::factory()->count(60)->create();
|
||||
|
||||
$response = $this->getJson('/api/blog/categories?per_page=50');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonPath('meta.per_page', 50)
|
||||
->assertJsonCount(50, 'data');
|
||||
}
|
||||
|
||||
public function test_defaults_are_unchanged_for_existing_consumers(): void
|
||||
{
|
||||
$response = $this->getJson('/api/blog/categories');
|
||||
|
||||
$response->assertOk()->assertJsonPath('meta.per_page', 10);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_create_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$response = $this->postJson('/api/website/about-me', [
|
||||
'image' => 'test.jpg',
|
||||
]);
|
||||
@@ -53,6 +55,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_update_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$aboutMe = AboutMe::factory()->create();
|
||||
|
||||
$response = $this->putJson("/api/website/about-me/{$aboutMe->id}", [
|
||||
@@ -65,6 +69,8 @@ class AboutMeTest extends TestCase
|
||||
|
||||
public function test_can_delete_about_me()
|
||||
{
|
||||
$this->actingAsAdmin();
|
||||
|
||||
$aboutMe = AboutMe::factory()->create();
|
||||
|
||||
$response = $this->deleteJson("/api/website/about-me/{$aboutMe->id}");
|
||||
|
||||
+30
-1
@@ -2,9 +2,38 @@
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
|
||||
abstract class TestCase extends BaseTestCase
|
||||
{
|
||||
//
|
||||
/**
|
||||
* Authenticate the current request as an admin user.
|
||||
*
|
||||
* Every mutating endpoint requires both a valid session and the admin
|
||||
* flag, so tests that create or destroy content must opt in explicitly
|
||||
* rather than relying on the previous anonymous behaviour.
|
||||
*/
|
||||
protected function actingAsAdmin(): User
|
||||
{
|
||||
$admin = User::factory()->admin()->create();
|
||||
|
||||
Sanctum::actingAs($admin);
|
||||
|
||||
return $admin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate as a valid user that is *not* an admin, to prove the
|
||||
* second authorisation gate is enforced.
|
||||
*/
|
||||
protected function actingAsNonAdmin(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
Sanctum::actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user