Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added API endpoint to retrieve visible users #602

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,52 @@
},
"servers": [],
"paths": {
"/users": {
"get": {
"tags": [
"User management"
],
"summary": "Get all visible users",
"description": "Get all the usernames of the visible users to the current request based on the authentication. If the request doesn't contain a valid token, only public users will be returned.",
"responses": {
"200": {
"description": "All visible usernames",
"content": {
"application/json": {
"schema": {
"type": "array",
"description": "Array of objects containing the username of the visible users",
"items": {
"description": "Username",
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "Username 1"
}
}
},
"example": [
{
"name": "Username 1"
},
{
"name": "Username 2"
},
{
"name": "Username 3"
}
]
}
}
}
},
"204": {
"description": "There are no visible users"
}
}
}
},
"\/users\/{username}\/history\/movies": {
"get": {
"tags": [
Expand Down
2 changes: 2 additions & 0 deletions settings/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,8 @@ function addApiRoutes(RouterService $routerService, FastRoute\RouteCollector $ro
$routes->add('DELETE', '/authentication/token', [Api\AuthenticationController::class, 'destroyToken']);
$routes->add('GET', '/authentication/token', [Api\AuthenticationController::class, 'getTokenData']);

$routes->add('GET', '/users', [Api\UsersController::class, 'getVisibleUsers']);

$routeUserHistory = '/users/{username:[a-zA-Z0-9]+}/history/movies';
$routes->add('GET', $routeUserHistory, [Api\HistoryController::class, 'getHistory'], [Api\Middleware\IsAuthorizedToReadUserData::class]);
$routes->add('POST', $routeUserHistory, [Api\HistoryController::class, 'addToHistory'], [Api\Middleware\IsAuthorizedToWriteUserData::class]);
Expand Down
96 changes: 69 additions & 27 deletions src/Domain/User/Service/Authentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Movary\Domain\User\UserApi;
use Movary\Domain\User\UserEntity;
use Movary\Domain\User\UserRepository;
use Movary\HttpController\Api\ValueObject\AuthenticationObject;
use Movary\HttpController\Web\CreateUserController;
use Movary\Util\SessionWrapper;
use Movary\ValueObject\DateTime;
Expand All @@ -29,6 +30,52 @@ public function __construct(
) {
}

public function createAuthenticationObjectFromCookie() : ?AuthenticationObject
{
$token = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);
$authenticationMethod = AuthenticationObject::COOKIE_AUTHENTICATION;
if (empty($token) === true || $this->isValidToken((string)$token) === true) {
unset($_COOKIE[self::AUTHENTICATION_COOKIE_NAME]);
setcookie(self::AUTHENTICATION_COOKIE_NAME, '', -1);
return null;
}
$user = $this->userApi->findByToken($token);
if(empty($user) === true) {
return null;
}
return AuthenticationObject::createAuthenticationObject($token, $authenticationMethod, $user);
}

public function createAuthenticationObjectDynamically(Request $request) : ?AuthenticationObject
{
$token = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME) ?? $request->getHeaders()['X-Movary-Token'] ?? null;
if (empty($token) === true || $this->isValidToken($token) === false) {
unset($_COOKIE[self::AUTHENTICATION_COOKIE_NAME]);
setcookie(self::AUTHENTICATION_COOKIE_NAME, '', -1);
return null;
}
$authenticationMethod = empty($request->getHeaders()['X-Movary-Token']) === true ? AuthenticationObject::COOKIE_AUTHENTICATION : AuthenticationObject::HEADER_AUTHENTICATION;
$user = $this->userApi->findByToken($token);
if(empty($user) === true) {
return null;
}
return AuthenticationObject::createAuthenticationObject($token, $authenticationMethod, $user);
}

public function createAuthenticationObjectFromHeader(Request $request) : ?AuthenticationObject
{
$token = $request->getHeaders()['X-Movary-Token'] ?? null;
$authenticationMethod = AuthenticationObject::HEADER_AUTHENTICATION;
if (empty($token) === true || $this->isValidToken((string)$token) === false) {
return null;
}
$user = $this->userApi->findByToken($token);
if(empty($user) === true) {
return null;
}
return AuthenticationObject::createAuthenticationObject($token, $authenticationMethod, $user);
}

public function createExpirationDate(int $days = 1) : DateTime
{
$timestamp = strtotime('+' . $days . ' day');
Expand Down Expand Up @@ -84,28 +131,27 @@ public function getCurrentUser() : UserEntity
public function getCurrentUserId() : int
{
$userId = $this->sessionWrapper->find('userId');
$token = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);

if ($userId === null && $token !== null) {
$userId = $this->repository->findUserIdByAuthToken((string)$token);
$this->sessionWrapper->set('userId', $userId);
if ($userId === null) {

$authenticationObject = $this->createAuthenticationObjectFromCookie();
if($authenticationObject === null) {
throw new RuntimeException('Could not find a current user');
}
$this->sessionWrapper->set('userId', $authenticationObject->getUser()->getId());
}

if ($userId === null) {
throw new RuntimeException('Could not find a current user');
}

return $userId;
}

public function getToken(Request $request) : ?string
{
$tokenInCookie = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);
if ($tokenInCookie !== false && $tokenInCookie !== null) {
return $tokenInCookie;
}
$authenticationObject = $this->createAuthenticationObjectDynamically($request);

return $request->getHeaders()['X-Movary-Token'] ?? null;
return $authenticationObject?->getToken();
}

public function getUserIdByApiToken(Request $request) : ?int
Expand All @@ -115,7 +161,7 @@ public function getUserIdByApiToken(Request $request) : ?int
return null;
}

if ($this->isValidAuthToken($apiToken) === false) {
if ($this->isValidToken($apiToken) === false) {
return null;
}

Expand All @@ -124,18 +170,11 @@ public function getUserIdByApiToken(Request $request) : ?int

public function isUserAuthenticatedWithCookie() : bool
{
$token = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);

if (empty($token) === false && $this->isValidAuthToken((string)$token) === true) {
return true;
}

if (empty($token) === false) {
unset($_COOKIE[self::AUTHENTICATION_COOKIE_NAME]);
setcookie(self::AUTHENTICATION_COOKIE_NAME, '', -1);
$authenticationObject = $this->createAuthenticationObjectFromCookie();
if($authenticationObject === null) {
return false;
}

return false;
return true;
}

public function isUserPageVisibleForApiRequest(Request $request, UserEntity $targetUser) : bool
Expand All @@ -155,16 +194,19 @@ public function isUserPageVisibleForWebRequest(UserEntity $targetUser) : bool
return $this->isUserPageVisibleForUser($targetUser, $requestUserId);
}

public function isValidAuthToken(string $token) : bool
public function isValidToken(string $token) : bool
{
$tokenExpirationDate = $this->repository->findAuthTokenExpirationDate($token);

if ($tokenExpirationDate === null || $tokenExpirationDate->isAfter(DateTime::create()) === false) {
if ($tokenExpirationDate !== null) {
if ($tokenExpirationDate === null) {
if($this->repository->findUserByApiToken($token) === null) {
return false;
}
} else {
if($tokenExpirationDate->isAfter(DateTime::create()) === false) {
$this->repository->deleteAuthToken($token);
return false;
}

return false;
}

return true;
Expand Down
11 changes: 6 additions & 5 deletions src/Domain/User/Service/UserPageAuthorizationChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
namespace Movary\Domain\User\Service;

use Movary\Domain\User\UserApi;
use Movary\ValueObject\Http\Request;

class UserPageAuthorizationChecker
readonly class UserPageAuthorizationChecker
{
public function __construct(
private readonly UserApi $userApi,
private readonly Authentication $authenticationService,
private UserApi $userApi,
private Authentication $authenticationService,
) {
}

Expand All @@ -30,9 +31,9 @@ public function fetchAllHavingWatchedMovieWithPersonVisibleUsernamesForCurrentVi
return $this->userApi->fetchAllHavingWatchedMovieWithPersonInternVisibleUsernames($personId);
}

public function fetchAllVisibleUsernamesForCurrentVisitor() : array
public function fetchAllVisibleUsernamesForCurrentVisitor(Request $request) : array
{
if ($this->authenticationService->isUserAuthenticatedWithCookie() === false) {
if ($this->authenticationService->createAuthenticationObjectDynamically($request) === null) {
return $this->userApi->fetchAllPublicVisibleUsernames();
}

Expand Down
18 changes: 18 additions & 0 deletions src/Domain/User/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,24 @@ public function findUserByName(string $name) : ?UserEntity
return UserEntity::createFromArray($data);
}

public function findUserByApiToken(string $apiToken) : ?UserEntity
{
$data = $this->dbConnection->fetchAssociative(
'SELECT user.*
FROM user
LEFT JOIN user_api_token ON user.id = user_api_token.user_id
LEFT JOIN user_auth_token ON user.id = user_auth_token.user_id
WHERE user_api_token.token = ?',
[$apiToken],
);

if (empty($data) === true) {
return null;
}

return UserEntity::createFromArray($data);
}

public function findUserByToken(string $apiToken) : ?UserEntity
{
$data = $this->dbConnection->fetchAssociative(
Expand Down
2 changes: 1 addition & 1 deletion src/HttpController/Api/AuthenticationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public function getTokenData(Request $request) : Response
return Response::createUnauthorized();
}

if ($this->authenticationService->isUserAuthenticatedWithCookie() && $this->authenticationService->isValidAuthToken($token) === false) {
if($this->authenticationService->isUserAuthenticatedWithCookie() && $this->authenticationService->isValidToken($token) === false) {
return Response::createUnauthorized();
}

Expand Down
30 changes: 30 additions & 0 deletions src/HttpController/Api/UsersController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace Movary\HttpController\Api;

use Movary\Domain\User\Service\Authentication;
use Movary\Domain\User\Service\UserPageAuthorizationChecker;
use Movary\Domain\User\UserApi;
use Movary\Util\Json;
use Movary\ValueObject\Http\Request;
use Movary\ValueObject\Http\Response;

readonly class UsersController
{
public function __construct(
private UserPageAuthorizationChecker $userPageAuthorizationChecker
) {}

public function getVisibleUsers(Request $request) : Response
{
$visibleUsers = $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor($request);
if(empty($visibleUsers) === true) {
return Response::createNoContent();
}
return Response::createJson(
Json::encode(
$visibleUsers
)
);
}
}
46 changes: 46 additions & 0 deletions src/HttpController/Api/ValueObject/AuthenticationObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Movary\HttpController\Api\ValueObject;

use Movary\Domain\User\UserEntity;

class AuthenticationObject
{
public const INT COOKIE_AUTHENTICATION = 1;
public const INT HEADER_AUTHENTICATION = 2;
public function __construct(
public readonly string $token,
public readonly int $authenticationMethod,
public readonly UserEntity $user,
) { }

public static function createAuthenticationObject(string $token, int $authenticationMethod, UserEntity $user) : self
{
return new self($token, $authenticationMethod, $user);
}

public function getToken() : string
{
return $this->token;
}

public function getAuthenticationMethod() : int
{
return $this->authenticationMethod;
}

public function getUser() : UserEntity
{
return $this->user;
}

public function hasCookieAuthentication() : bool
{
return $this->authenticationMethod === self::COOKIE_AUTHENTICATION;
}

public function hasHeaderAuthentication() : bool
{
return $this->authenticationMethod === self::HEADER_AUTHENTICATION;
}
}
2 changes: 1 addition & 1 deletion src/HttpController/Web/ActorsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function renderPage(Request $request) : Response
return Response::create(
StatusCode::createOk(),
$this->twig->render('page/actors.html.twig', [
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor(),
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor($request),
'mostWatchedActors' => $actors,
'paginationElements' => $paginationElements,
'searchTerm' => $requestData->getSearchTerm(),
Expand Down
2 changes: 1 addition & 1 deletion src/HttpController/Web/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function render(Request $request) : Response
return Response::create(
StatusCode::createOk(),
$this->twig->render('page/dashboard.html.twig', [
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor(),
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor($request),
'totalPlayCount' => $this->movieApi->fetchTotalPlayCount($userId),
'uniqueMoviesCount' => $this->movieApi->fetchTotalPlayCountUnique($userId),
'totalHoursWatched' => $this->movieHistoryApi->fetchTotalHoursWatched($userId),
Expand Down
2 changes: 1 addition & 1 deletion src/HttpController/Web/DirectorsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function renderPage(Request $request) : Response
return Response::create(
StatusCode::createOk(),
$this->twig->render('page/directors.html.twig', [
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor(),
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor($request),
'mostWatchedDirectors' => $directors,
'paginationElements' => $paginationElements,
'searchTerm' => $requestData->getSearchTerm(),
Expand Down
2 changes: 1 addition & 1 deletion src/HttpController/Web/HistoryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public function renderHistory(Request $request) : Response
return Response::create(
StatusCode::createOk(),
$this->twig->render('page/history.html.twig', [
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor(),
'users' => $this->userPageAuthorizationChecker->fetchAllVisibleUsernamesForCurrentVisitor($request),
'historyEntries' => $historyPaginated,
'paginationElements' => $paginationElements,
'searchTerm' => $searchTerm,
Expand Down
Loading
Loading