Skip to content

Commit

Permalink
Add active at date to user (#127)
Browse files Browse the repository at this point in the history
Added datetime when user had interaction with API last time.
  • Loading branch information
vokomarov authored Sep 6, 2023
2 parents cc2edcf + 6414c4e commit da27b96
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace App;

use Cycle\Migrations\Migration;

class AddActiveAtColumnToUsersTableMigration extends Migration
{
public function up(): void
{
$this->table('users')
->addColumn('active_at', 'datetime', [
'nullable' => true,
'default' => null,
])
->update();
}

public function down(): void
{
$this->table('users')
->dropColumn('active_at')
->update();
}
}
17 changes: 14 additions & 3 deletions app/src/Auth/AuthMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Database\User;
use App\Service\UserOptionsService;
use App\Service\UserService;
use Laminas\Diactoros\Response\JsonResponse;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
Expand All @@ -23,6 +24,7 @@ class AuthMiddleware implements MiddlewareInterface
const USER_LOCALE = 'X-Internal-UserLocale';

public function __construct(
private readonly UserService $userService,
private readonly UserOptionsService $userOptionsService,
) {
}
Expand All @@ -44,19 +46,28 @@ public function process(Request $request, RequestHandlerInterface $handler): Res
return $this->unauthenticated();
}

$this->trackActiveAt($actor);

return $handler->handle(
$request->withAddedHeader(self::HEADER_USER_ID, (string) $actor->id)
->withAttribute(self::USER_LOCALE, $this->userOptionsService->getLocale($actor))
);
}

/**
* @return \Psr\Http\Message\ResponseInterface
*/
private function unauthenticated(): Response
{
return new JsonResponse([
'message' => $this->say('error_authentication_required'),
], 401);
}

private function trackActiveAt(User $user): void
{
$user->activeAt = new \DateTimeImmutable();

try {
$this->userService->store($user);
} catch (\Throwable) {
}
}
}
3 changes: 3 additions & 0 deletions app/src/Database/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ class User implements PasswordContainerInterface
#[ORM\Column(type: 'datetime', name: 'updated_at')]
public \DateTimeImmutable $updatedAt;

#[ORM\Column(type: 'datetime', name: 'active_at', nullable: true, default: null)]
public ?\DateTimeImmutable $activeAt = null;

#[ORM\Relation\BelongsTo(target: Currency::class, innerKey: 'default_currency_code', cascade: true, load: 'eager')]
private Currency $defaultCurrency;

Expand Down

0 comments on commit da27b96

Please sign in to comment.