Pagination on the list, optional auth
This commit is contained in:
parent
7ee04b0a4b
commit
5251c43a6b
20
exam/api/Posts/Posts.php
Normal file
20
exam/api/Posts/Posts.php
Normal file
@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Api\Posts;
|
||||
|
||||
use Khofmann\Api\Api;
|
||||
use Khofmann\Input\Input;
|
||||
use Khofmann\Models\Post\Post;
|
||||
use Khofmann\Request\Request;
|
||||
use Khofmann\Response\Response;
|
||||
|
||||
class Posts extends Api
|
||||
{
|
||||
public function get()
|
||||
{
|
||||
$page = max(0, intval(Input::get("p", 0)));
|
||||
$limit = constrain(0, 30, intval(Input::get("l", 10)));
|
||||
$authed = Request::header("token") !== null;
|
||||
Response::json(Post::list($page, $limit, $authed));
|
||||
}
|
||||
}
|
||||
@ -3,6 +3,7 @@
|
||||
namespace Api\Users;
|
||||
|
||||
use Khofmann\Api\Api;
|
||||
use Khofmann\Input\Input;
|
||||
use Khofmann\Models\User\User;
|
||||
use Khofmann\Response\Response;
|
||||
|
||||
@ -10,6 +11,8 @@ class Users extends Api
|
||||
{
|
||||
public function get()
|
||||
{
|
||||
Response::json(User::list());
|
||||
$page = max(0, intval(Input::get("p", 0)));
|
||||
$limit = constrain(0, 30, intval(Input::get("l", 10)));
|
||||
Response::json(User::list($page, $limit));
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,7 +10,7 @@ paths:
|
||||
/login:
|
||||
post:
|
||||
summary: Login
|
||||
description: Log in user
|
||||
description: Log in user.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@ -19,7 +19,7 @@ paths:
|
||||
$ref: "#/components/schemas/LoginRequest"
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -28,7 +28,7 @@ paths:
|
||||
Success:
|
||||
value: true
|
||||
400:
|
||||
description: Missing fields
|
||||
description: Missing fields.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -37,7 +37,7 @@ paths:
|
||||
Missing fields:
|
||||
value: { "message": "Missing email" }
|
||||
401:
|
||||
description: Invalid credentials
|
||||
description: Invalid credentials.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -46,7 +46,7 @@ paths:
|
||||
Invalid username or password:
|
||||
value: { "message": "Invalid username or password" }
|
||||
404:
|
||||
description: User not found
|
||||
description: User not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -55,7 +55,7 @@ paths:
|
||||
User not found:
|
||||
value: { "message": "User not found" }
|
||||
500:
|
||||
description: Failed
|
||||
description: Failed.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -68,12 +68,12 @@ paths:
|
||||
/logout:
|
||||
post:
|
||||
summary: Logout
|
||||
description: Log out user
|
||||
description: Log out user.
|
||||
security:
|
||||
- BasicAuth: []
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -161,10 +161,25 @@ paths:
|
||||
/users:
|
||||
get:
|
||||
summary: List users
|
||||
description: List all users. <br>
|
||||
Requires logged in user to have admin permissions.
|
||||
description: List all users.
|
||||
security:
|
||||
- BasicAuth: []
|
||||
parameters:
|
||||
- in: query
|
||||
name: p
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 0
|
||||
default: 0
|
||||
description: Current page.
|
||||
- in: query
|
||||
name: l
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 30
|
||||
default: 10
|
||||
description: The number of items to return.
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
@ -175,6 +190,9 @@ paths:
|
||||
examples:
|
||||
Success:
|
||||
value:
|
||||
{
|
||||
"pages": 1,
|
||||
"data":
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
@ -206,15 +224,16 @@ paths:
|
||||
},
|
||||
"postCount": 2,
|
||||
},
|
||||
]
|
||||
],
|
||||
}
|
||||
tags:
|
||||
- User
|
||||
/user{id}:
|
||||
get:
|
||||
summary: Get user
|
||||
description: Get user by ID
|
||||
description: Get user by ID.
|
||||
security:
|
||||
- BasicAuth: []
|
||||
- BasicAuth: [isAdmin]
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
@ -225,7 +244,7 @@ paths:
|
||||
format: int14
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -249,7 +268,7 @@ paths:
|
||||
"postCount": 3,
|
||||
}
|
||||
404:
|
||||
description: User not found
|
||||
description: User not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -266,7 +285,7 @@ paths:
|
||||
Use special ID <code>self</code> to update logged in user. <br>
|
||||
Requires logged in user to have admin permissions for any ID other than <code>self</code>.
|
||||
security:
|
||||
- BasicAuth: []
|
||||
- BasicAuth: [isAdmin]
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
@ -282,7 +301,7 @@ paths:
|
||||
$ref: "#/components/schemas/UserUpdateRequest"
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -291,7 +310,7 @@ paths:
|
||||
Success:
|
||||
value: true
|
||||
404:
|
||||
description: User not found
|
||||
description: User not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -300,7 +319,7 @@ paths:
|
||||
User not found:
|
||||
value: { "message": "User not found" }
|
||||
500:
|
||||
description: Update failed
|
||||
description: Update failed.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -312,10 +331,9 @@ paths:
|
||||
- User
|
||||
delete:
|
||||
summary: Delete user
|
||||
description: Delete user with ID. <br>
|
||||
Requires logged in user to have admin permissions.
|
||||
description: Delete user with ID.
|
||||
security:
|
||||
- BasicAuth: []
|
||||
- BasicAuth: [isAdmin]
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
@ -326,7 +344,7 @@ paths:
|
||||
format: int14
|
||||
responses:
|
||||
200:
|
||||
description: Success
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -335,7 +353,7 @@ paths:
|
||||
Success:
|
||||
value: true
|
||||
404:
|
||||
description: User not found
|
||||
description: User not found.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@ -345,7 +363,129 @@ paths:
|
||||
value: { "message": "User not found" }
|
||||
tags:
|
||||
- User
|
||||
|
||||
/posts:
|
||||
get:
|
||||
summary: List posts
|
||||
description: List all posts, return full user data if authenticated.
|
||||
security:
|
||||
- {}
|
||||
- BasicAuth: []
|
||||
parameters:
|
||||
- in: query
|
||||
name: p
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 0
|
||||
default: 0
|
||||
description: Current page.
|
||||
- in: query
|
||||
name: l
|
||||
schema:
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 30
|
||||
default: 10
|
||||
description: The number of items to return.
|
||||
responses:
|
||||
200:
|
||||
description: Success.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/PostListResponse"
|
||||
examples:
|
||||
Not authenticated:
|
||||
value:
|
||||
{
|
||||
"pages": 1,
|
||||
"data":
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"user": { "username": "Admin" },
|
||||
"content": "Hey,\r\nGästebucher sind cool…\r\nDas Gästebuch ist freigegeben.\r\nIch hoffe auf viele Beiträge!",
|
||||
"postedAt":
|
||||
{
|
||||
"date": "2020-03-03 09:03:00.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"user": { "username": "Max" },
|
||||
"content": "Bin über Google auf deine Seite gestoßen, danke für das geniale Gästebuch. Werde in Zukunft des Öftern vorbeischaun…\r\n\r\nLiebe Grüsse, Max",
|
||||
"postedAt":
|
||||
{
|
||||
"date": "2020-03-04 12:26:40.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
Authenticated:
|
||||
value:
|
||||
{
|
||||
"pages": 1,
|
||||
"data":
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"user":
|
||||
{
|
||||
"id": 1,
|
||||
"username": "Admin",
|
||||
"status": 1,
|
||||
"email": "marvin@zedat.fu-berlin.de",
|
||||
"image": "669d41fbdb56b.png",
|
||||
"isAdmin": true,
|
||||
"memberSince":
|
||||
{
|
||||
"date": "2024-07-22 14:02:49.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
"postCount": 3,
|
||||
},
|
||||
"content": "Hey,\r\nGästebucher sind cool…\r\nDas Gästebuch ist freigegeben.\r\nIch hoffe auf viele Beiträge!",
|
||||
"postedAt":
|
||||
{
|
||||
"date": "2020-03-03 09:03:00.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"user":
|
||||
{
|
||||
"id": 2,
|
||||
"username": "Max",
|
||||
"status": 1,
|
||||
"email": "max@moritz.net",
|
||||
"image": "profilbilder/max.svg",
|
||||
"isAdmin": false,
|
||||
"memberSince":
|
||||
{
|
||||
"date": "2024-07-22 03:07:41.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
"postCount": 2,
|
||||
},
|
||||
"content": "Bin über Google auf deine Seite gestoßen, danke für das geniale Gästebuch. Werde in Zukunft des Öftern vorbeischaun…\r\n\r\nLiebe Grüsse, Max",
|
||||
"postedAt":
|
||||
{
|
||||
"date": "2020-03-04 12:26:40.000000",
|
||||
"timezone_type": 3,
|
||||
"timezone": "Europe/Berlin",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
tags:
|
||||
- Post
|
||||
externalDocs:
|
||||
url: https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/docs/
|
||||
security: []
|
||||
@ -430,9 +570,40 @@ components:
|
||||
type: string
|
||||
format: uuid4
|
||||
UserListResponse:
|
||||
type: object
|
||||
properties:
|
||||
pages:
|
||||
type: number
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
PostResponse:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: number
|
||||
user:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
postedAt:
|
||||
type: object
|
||||
properties:
|
||||
date:
|
||||
type: string
|
||||
format: date-time
|
||||
timezone_type:
|
||||
type: number
|
||||
timezone:
|
||||
type: string
|
||||
PostListResponse:
|
||||
type: object
|
||||
properties:
|
||||
pages:
|
||||
type: number
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/PostResponse"
|
||||
securitySchemes:
|
||||
BasicAuth:
|
||||
type: apiKey
|
||||
@ -442,3 +613,4 @@ tags:
|
||||
- name: Login/Logout
|
||||
- name: Register
|
||||
- name: User
|
||||
- name: Post
|
||||
|
||||
File diff suppressed because one or more lines are too long
29
exam/classes/Auth/OptAuth.php
Normal file
29
exam/classes/Auth/OptAuth.php
Normal file
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Khofmann\Auth;
|
||||
|
||||
use Exception;
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Khofmann\Models\User\User;
|
||||
use Khofmann\Response\Response;
|
||||
|
||||
class OptAuth implements IMiddleware
|
||||
{
|
||||
public function handle(Request $request): void
|
||||
{
|
||||
$token = $request->getHeader("token");
|
||||
|
||||
// No token
|
||||
if ($token === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
User::getByToken($token);
|
||||
} catch (Exception $err) {
|
||||
// No user with this token exists
|
||||
Response::response()->httpCode(401)->json(["message" => "Not Authorized"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -9,24 +9,24 @@ class Input
|
||||
public static function post(string $index, $defaultValue = null)
|
||||
{
|
||||
$value = Request::request()->getInputHandler()->post($index, $defaultValue);
|
||||
return empty($value) ? null : $value->getValue();
|
||||
return !is_object($value) ? $value : $value->getValue();
|
||||
}
|
||||
|
||||
public static function patch(string $index, $defaultValue = null)
|
||||
{
|
||||
$value = Request::request()->getInputHandler()->post($index, $defaultValue);
|
||||
return empty($value) ? null : $value->getValue();
|
||||
return !is_object($value) ? $value : $value->getValue();
|
||||
}
|
||||
|
||||
public static function get(string $index, $defaultValue = null)
|
||||
{
|
||||
$value = Request::request()->getInputHandler()->get($index, $defaultValue);
|
||||
return empty($value) ? null : $value->getValue();
|
||||
return !is_object($value) ? $value : $value->getValue();
|
||||
}
|
||||
|
||||
public static function file(string $index, $defaultValue = null)
|
||||
{
|
||||
$value = Request::request()->getInputHandler()->file($index, $defaultValue);
|
||||
return empty($value) ? null : $value->getValue();
|
||||
return !is_object($value) ? $value : $value->getValue();
|
||||
}
|
||||
}
|
||||
|
||||
107
exam/classes/Models/Post/Post.php
Normal file
107
exam/classes/Models/Post/Post.php
Normal file
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Khofmann\Models\Post;
|
||||
|
||||
use DateTime;
|
||||
use Khofmann\Models\User\User;
|
||||
use JsonSerializable;
|
||||
use Khofmann\Database\Database;
|
||||
use PDO;
|
||||
|
||||
class Post implements JsonSerializable
|
||||
{
|
||||
private int $id;
|
||||
// User is set if the post was fetched by an authenticated user
|
||||
private ?User $user;
|
||||
private ?string $name;
|
||||
private string $content;
|
||||
private DateTime $postedAt;
|
||||
|
||||
public function __construct(int $id, ?User $user, ?string $name, string $content, string $postedAt)
|
||||
{
|
||||
$this->id = $id;
|
||||
$this->user = $user;
|
||||
$this->name = $name;
|
||||
$this->content = $content;
|
||||
$this->postedAt = new DateTime($postedAt);
|
||||
}
|
||||
|
||||
/*
|
||||
* Statics
|
||||
*/
|
||||
|
||||
public static function list(int $page, int $limit, bool $authed = false)
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$stmt = $db->prepare(
|
||||
"SELECT
|
||||
COUNT(*)
|
||||
FROM
|
||||
egb_gaestebuch"
|
||||
);
|
||||
$stmt->execute();
|
||||
$count = $stmt->fetch(PDO::FETCH_COLUMN, 0);
|
||||
$stmt = $db->prepare(
|
||||
"SELECT
|
||||
*
|
||||
FROM
|
||||
egb_gaestebuch
|
||||
LIMIT $limit
|
||||
OFFSET " . ($page * $limit)
|
||||
);
|
||||
$stmt->execute();
|
||||
$data = $stmt->fetchAll();
|
||||
|
||||
$list = array_map(
|
||||
function ($item) use ($authed) {
|
||||
$user = User::getByID($item["benutzer_id"]);
|
||||
return new Post($item["id"], $authed ? $user : null, !$authed ? $user->getUsername() : null, $item["beitrag"], $item["zeitstempel"]);
|
||||
},
|
||||
$data
|
||||
);
|
||||
|
||||
return ["pages" => intdiv($count, $limit) + 1, "data" => $list];
|
||||
}
|
||||
|
||||
/*
|
||||
* Getters
|
||||
*/
|
||||
|
||||
public function getId(): int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getUser(): User
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
public function getContent(): string
|
||||
{
|
||||
return $this->content;
|
||||
}
|
||||
|
||||
public function getPostedAt(): DateTime
|
||||
{
|
||||
return $this->postedAt;
|
||||
}
|
||||
|
||||
/*
|
||||
* JSON
|
||||
*/
|
||||
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$user = $this->user ? $this->user : [
|
||||
"username" => $this->name,
|
||||
];
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'user' => $user,
|
||||
'content' => $this->content,
|
||||
'postedAt' => $this->postedAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -226,9 +226,17 @@ class User implements JsonSerializable
|
||||
return $stmt->execute();
|
||||
}
|
||||
|
||||
public static function list()
|
||||
public static function list(int $page, int $limit)
|
||||
{
|
||||
$db = Database::getInstance();
|
||||
$stmt = $db->prepare(
|
||||
"SELECT
|
||||
COUNT(*)
|
||||
FROM
|
||||
egb_gaestebuch"
|
||||
);
|
||||
$stmt->execute();
|
||||
$count = $stmt->fetch(PDO::FETCH_COLUMN, 0);
|
||||
$stmt = $db->prepare(
|
||||
"SELECT
|
||||
b.id, b.benutzer, b.status, b.email, b.image, b.isadmin, b.zeitstempel,
|
||||
@ -239,10 +247,12 @@ class User implements JsonSerializable
|
||||
$stmt->execute();
|
||||
$data = $stmt->fetchAll();
|
||||
|
||||
return array_map(
|
||||
$list = array_map(
|
||||
fn ($item) => new User($item["id"], $item["benutzer"], $item["status"], $item["email"], $item["zeitstempel"], $item["image"], $item["isadmin"] === 1, $item["postCount"]),
|
||||
$data
|
||||
);
|
||||
|
||||
return ["pages" => intdiv($count, $limit) + 1, "data" => $list];
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@ -21,4 +21,13 @@ class Response
|
||||
}
|
||||
SimpleRouter::response()->json($value, $options, $dept);
|
||||
}
|
||||
|
||||
public static function redirect(string $url, ?int $code = null): void
|
||||
{
|
||||
if ($code !== null) {
|
||||
Response::response()->httpCode($code);
|
||||
}
|
||||
|
||||
Response::response()->redirect($url);
|
||||
}
|
||||
}
|
||||
|
||||
@ -10,7 +10,7 @@ SimpleRouter::error(function (Request $request, Exception $exception) {
|
||||
});
|
||||
// Index
|
||||
SimpleRouter::all("/", function () {
|
||||
redirect("docs", 301);
|
||||
Response::redirect("docs", 301);
|
||||
});
|
||||
|
||||
/*
|
||||
@ -18,15 +18,23 @@ SimpleRouter::all("/", function () {
|
||||
*/
|
||||
// Login
|
||||
SimpleRouter::post("/login", [Api\Login\Login::class, "post"]);
|
||||
// Register and confirm
|
||||
SimpleRouter::post("/register", [Api\Register\Register::class, "post"]);
|
||||
SimpleRouter::patch("/register", [Api\Register\Register::class, "patch"]);
|
||||
/*
|
||||
* Optional Auth
|
||||
*/
|
||||
SimpleRouter::group(["middleware" => Khofmann\Auth\OptAuth::class], function () {
|
||||
// List posts with user data
|
||||
SimpleRouter::get("/posts", [Api\Posts\Posts::class, "get"]);
|
||||
});
|
||||
/*
|
||||
* Normal Auth routes
|
||||
*/
|
||||
SimpleRouter::group(["middleware" => Khofmann\Auth\Auth::class], function () {
|
||||
// Login
|
||||
// Logout
|
||||
SimpleRouter::post("/logout", [Api\Logout\Logout::class, "post"]);
|
||||
// Get any user
|
||||
// Get user
|
||||
SimpleRouter::get("/user/{id}", [Api\User\User::class, "get"]);
|
||||
// Update self
|
||||
SimpleRouter::patch("/user/self", [Api\User\User::class, "patchSelf"]);
|
||||
|
||||
@ -26,15 +26,7 @@ function url(?string $name = null, $parameters = null, ?array $getParams = null)
|
||||
return Router::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $url
|
||||
* @param int|null $code
|
||||
*/
|
||||
function redirect(string $url, ?int $code = null): void
|
||||
function constrain(int $min, int $max, $n): int
|
||||
{
|
||||
if ($code !== null) {
|
||||
response()->httpCode($code);
|
||||
}
|
||||
|
||||
response()->redirect($url);
|
||||
return max(min($max, $n), $min);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user