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

Centralize authentication process #598

Open
wants to merge 8 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
117 changes: 86 additions & 31 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,61 @@ public function __construct(
) {
}

public function createAuthenticationObjectFromCookie() : ?AuthenticationObject
{
$token = filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);
$authenticationMethod = AuthenticationObject::COOKIE_AUTHENTICATION;
/**
* @psalm-suppress RedundantCast
*/
if (empty($token) === true || $this->isValidToken((string)$token) === false) {
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);
}

/**
* This method will 'dynamically' create an authentication object.
* It will first check if cookie authentication is possible and if not, it'll check if header authentication is possible.
* If neither are possible and/or the authentication token is invalid, then the cookie is deleted and null is returned.
* @param Request $request
* @return AuthenticationObject|null
*/
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 +140,28 @@ public function getCurrentUser() : UserEntity
public function getCurrentUserId() : int
{
$userId = $this->sessionWrapper->find('userId');
$token = (string)filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);

if ($userId === null && $token !== '') {
$userId = $this->repository->findUserIdByAuthToken($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());
$userId = $authenticationObject->getUser()->getId();
}

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

return $userId;
}

public function getToken(Request $request) : ?string
{
$tokenInCookie = (string)filter_input(INPUT_COOKIE, self::AUTHENTICATION_COOKIE_NAME);
if ($tokenInCookie !== '') {
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 +171,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 +180,11 @@ public function getUserIdByApiToken(Request $request) : ?int

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

if ($token !== '' && $this->isValidAuthToken($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 +204,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 Expand Up @@ -203,10 +255,13 @@ public function login(

public function logout() : void
{
$token = (string)filter_input(INPUT_COOKIE, 'id');
$token = filter_input(INPUT_COOKIE, 'id');

if ($token !== '') {
$this->deleteToken($token);
if ($token !== null) {
/**
* @psalm-suppress RedundantCast
*/
$this->deleteToken((string)$token);
unset($_COOKIE[self::AUTHENTICATION_COOKIE_NAME]);
setcookie(self::AUTHENTICATION_COOKIE_NAME, '', -1);
}
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
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;
}
}