Skip to content

Commit

Permalink
Automatically expire UserRoles
Browse files Browse the repository at this point in the history
To ensure that people do not retain privileges on the website for
too long, `UserRole`s will not automatically expire on a specified
date.
  • Loading branch information
tomudding committed Nov 1, 2023
1 parent 1586d86 commit 33b7a20
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
2 changes: 2 additions & 0 deletions module/Application/test/BaseControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Company\Model\Company;
use Company\Model\CompanyLocalisedText;
use DateInterval;
use DateTime;
use Decision\Model\Enums\MembershipTypes;
use Decision\Model\Member;
Expand Down Expand Up @@ -237,6 +238,7 @@ private function setUpMockIdentity(string $role): CompanyUser|User|null
if ('user' !== $role) {
$roleModel = new UserRole();
$roleModel->setRole(UserRoles::from($role));
$roleModel->setExpiration((new DateTime('now'))->add(new DateInterval('P1D')));

$roles = new ArrayCollection([$roleModel]);
} else {
Expand Down
6 changes: 5 additions & 1 deletion module/User/src/Model/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public function getMember(): MemberModel
}

/**
* Get the user's role names.
* Get the user's active role names.
*
* @return string[] Role names
*/
Expand All @@ -157,6 +157,10 @@ public function getRoleNames(): array
$names = [];

foreach ($this->getRoles() as $role) {
if (!$role->isActive()) {
continue;
}

$names[] = $role->getRole()->value;
}

Expand Down
35 changes: 35 additions & 0 deletions module/User/src/Model/UserRole.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace User\Model;

use Application\Model\Traits\IdentifiableTrait;
use DateTime;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\JoinColumn;
Expand Down Expand Up @@ -43,6 +44,15 @@ enumType: UserRoles::class,
)]
protected UserRoles $role;

/**
* Date after which this role has expired.
*/
#[Column(
type: 'datetime',
nullable: true,
)]
protected ?DateTime $expiration = null;

/**
* Get the membership number.
*/
Expand Down Expand Up @@ -74,4 +84,29 @@ public function setRole(UserRoles $role): void
{
$this->role = $role;
}

/**
* Get the expiration, `null` means invalid (and thus inactive).
*/
public function getExpiration(): ?DateTime
{
return $this->expiration;
}

/**
* Set the expiration date.
*/
public function setExpiration(DateTime $expiration): void
{
$this->expiration = $expiration;
}

/**
* Determine whether this role is active (i.e. has not expired).
*/
public function isActive(): bool
{
return null !== $this->expiration
&& (new DateTime('now')) < $this->expiration;
}
}

0 comments on commit 33b7a20

Please sign in to comment.