Skip to content
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
24 changes: 24 additions & 0 deletions app/Repositories/DoctrineUserTrustedDeviceRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,30 @@ private function buildActiveExpiryExpr(): Comparison
return Criteria::expr()->gt('expires_at', $now);
}

public function getByUserAndDeviceIdentifier(User $user, string $deviceIdentifier): ?UserTrustedDevice
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq('user', $user))
->andWhere(Criteria::expr()->eq('device_identifier', $deviceIdentifier))
->setMaxResults(1);

$result = $this->matching($criteria)->first();
return $result instanceof UserTrustedDevice ? $result : null;
}

public function revokeAllForUser(User $user): void
{
$this->getEntityManager()
->createQueryBuilder()
->update($this->getBaseEntity(), 'd')
->set('d.is_revoked', ':revoked')
->where('d.user = :user')
->setParameter('revoked', true)
->setParameter('user', $user)
->getQuery()
->execute();
}

public function getActiveByUserAndIdentifier(User $user, string $deviceIdentifier): ?UserTrustedDevice
{
$criteria = Criteria::create()
Expand Down
85 changes: 85 additions & 0 deletions app/Services/Auth/DeviceTrustService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php
namespace App\Services\Auth;
/**
* Copyright 2025 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use App\libs\Auth\Models\UserTrustedDevice;
use Auth\Repositories\IUserTrustedDeviceRepository;
use Auth\User;
use DateTime;
use DateInterval;
use DateTimeZone;

/**
* Class DeviceTrustService
* @package App\Services\Auth
*/
final class DeviceTrustService implements IDeviceTrustService
{
public function __construct(private readonly IUserTrustedDeviceRepository $repository)
{
}

public function generateDeviceIdentifier(string $token): string
{
return hash('sha256', $token);
}

public function trustDevice(User $user, string $userAgent, string $ipAddress): string
{
$rawToken = bin2hex(random_bytes(64));

$lifetimeDays = (int) config('two_factor.device_trust_lifetime_days', 30);
$now = new DateTime('now', new DateTimeZone('UTC'));
$expiresAt = clone $now;
$expiresAt->add(new DateInterval("P{$lifetimeDays}D"));

$device = new UserTrustedDevice();
$device->setUser($user);
$device->setDeviceIdentifier($this->generateDeviceIdentifier($rawToken));
$device->setDeviceName(substr($userAgent, 0, 255));
$device->setIpAddress($ipAddress);
$device->setUserAgent($userAgent);
$device->setTrustedAt($now);
$device->setExpiresAt($expiresAt);
$device->setLastSeenAt(clone $now);
$device->setIsRevoked(false);

$this->repository->add($device, true);

return $rawToken;
}

public function isDeviceTrusted(User $user, ?string $cookieToken): bool
{
if (empty($cookieToken)) {
return false;
}

$identifier = $this->generateDeviceIdentifier($cookieToken);
$device = $this->repository->getByUserAndDeviceIdentifier($user, $identifier);

if (!$device instanceof UserTrustedDevice || $device->isRevoked() || $device->isExpired()) {
return false;
}

$device->setLastSeenAt(new DateTime('now', new DateTimeZone('UTC')));
$this->repository->add($device, true);
return true;
}

public function removeTrustedDevices(User $user): void
{
$this->repository->revokeAllForUser($user);
}
}
45 changes: 45 additions & 0 deletions app/Services/Auth/IDeviceTrustService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php namespace App\Services\Auth;
/**
* Copyright 2025 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use Auth\User;

/**
* Interface IDeviceTrustService
* @package App\Services\Auth
*/
interface IDeviceTrustService
{
/**
* Checks whether the device identified by the given cookie token is trusted for the user.
* Updates last_seen_at on a valid match.
*/
public function isDeviceTrusted(User $user, ?string $cookieToken): bool;

/**
* Marks the current device as trusted for the user.
* Returns the raw 128-character hex token to be stored in the cookie.
* The SHA-256 hash of the token (not the raw token) is persisted.
*/
public function trustDevice(User $user, string $userAgent, string $ipAddress): string;

/**
* Revokes all trusted devices for the given user.
*/
public function removeTrustedDevices(User $user): void;

/**
* Returns the SHA-256 hash of the given token used as the stored device identifier.
*/
public function generateDeviceIdentifier(string $token): string;
}
41 changes: 41 additions & 0 deletions app/Services/Auth/TwoFactorServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php
namespace App\Services\Auth;
/**
* Copyright 2025 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;

/**
* Class TwoFactorServiceProvider
* @package App\Services\Auth
*/
final class TwoFactorServiceProvider extends ServiceProvider implements DeferrableProvider
{
public function boot(): void
{
}

public function register(): void
{
$this->app->singleton(IDeviceTrustService::class, DeviceTrustService::class);
}

public function provides(): array
{
return [
IDeviceTrustService::class,
];
}
}
9 changes: 8 additions & 1 deletion app/libs/Auth/Models/UserTrustedDevice.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
class UserTrustedDevice extends BaseEntity
{
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', onDelete: 'CASCADE')]
#[ORM\ManyToOne(targetEntity: \Auth\User::class)]
#[ORM\ManyToOne(targetEntity: User::class)]
private $user;

#[ORM\Column(name: 'device_identifier', type: 'string', length: 255)]
Expand Down Expand Up @@ -54,6 +54,7 @@ class UserTrustedDevice extends BaseEntity
public function __construct()
{
parent::__construct();
$this->last_seen_at = new \DateTime('now', new \DateTimeZone('UTC'));
$this->is_revoked = false;
}

Expand Down Expand Up @@ -137,4 +138,10 @@ public function setIsRevoked(bool $value): void
{
$this->is_revoked = $value;
}

public function isExpired(): bool
{
$now = new \DateTime('now', new \DateTimeZone('UTC'));
return $this->expires_at < $now;
}
}
12 changes: 11 additions & 1 deletion app/libs/Auth/Repositories/IUserTrustedDeviceRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,17 @@
interface IUserTrustedDeviceRepository extends IBaseRepository
{
/**
* Look up an active (non-revoked) trusted device for a user by its hashed identifier.
* Look up a trusted device record by user and hashed identifier (no revoked/expiry filter).
*/
public function getByUserAndDeviceIdentifier(User $user, string $deviceIdentifier): ?UserTrustedDevice;

/**
* Revoke all trusted devices for the given user (sets is_revoked = true).
*/
public function revokeAllForUser(User $user): void;

/**
* Look up an active (non-revoked, non-expired) trusted device for a user by its hashed identifier.
*/
public function getActiveByUserAndIdentifier(User $user, string $deviceIdentifier): ?UserTrustedDevice;

Expand Down
1 change: 1 addition & 0 deletions config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@
Services\OpenId\OpenIdProvider::class,
Auth\AuthenticationServiceProvider::class,
Services\ServicesProvider::class,
App\Services\Auth\TwoFactorServiceProvider::class,
Strategies\StrategyProvider::class,
OAuth2\OAuth2ServiceProvider::class,
OpenId\OpenIdServiceProvider::class,
Expand Down
8 changes: 8 additions & 0 deletions config/two_factor.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,12 @@
IGroupSlugs::OAuth2ServerAdminGroup,
IGroupSlugs::OpenIdServerAdminsGroup,
],

/*
|--------------------------------------------------------------------------
| Device Trust
|--------------------------------------------------------------------------
*/
'device_trust_lifetime_days' => env('DEVICE_TRUST_LIFETIME_DAYS', 30),
'cookie_name' => env('DEVICE_TRUST_COOKIE_NAME', 'device_trust_token'),
];
Loading
Loading