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,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user