From e029728d696267b295e4e427c6c425127cd59583 Mon Sep 17 00:00:00 2001 From: Craig Williams Date: Tue, 15 Feb 2022 14:56:45 +0000 Subject: [PATCH] Allow reverting a completed token to an un-complete state (undo "deny" scenario) --- src/Repository/BasicTokenRepository.php | 48 +++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/Repository/BasicTokenRepository.php b/src/Repository/BasicTokenRepository.php index 498a021..dfcf00d 100644 --- a/src/Repository/BasicTokenRepository.php +++ b/src/Repository/BasicTokenRepository.php @@ -264,6 +264,54 @@ abstract class BasicTokenRepository return $model; } + /** + * Reverts a completed token request to its previously incomplete state. + * + * @param TokenOwnerInterface $tokenOwner The owner of the token to revert. + * + * @return Model|false + */ + public function revert(TokenOwnerInterface $tokenOwner) + { + if ($this->tokenLogger) { + $this->tokenLogger->debug('Reverting token for {{owner}}', [ + 'owner' => $tokenOwner + ]); + } + + // Find an unexpired, incomplete tokens for the specified owner. + // Using first() works because owners can only have at most 1 active token + $model = $this->classMapper->getClassMapping($this->modelIdentifier)::query() + ->where('owner_id', $tokenOwner->getId()) + ->where('completed', true) + ->where(function($query) { + return $query->where('expires_at', '>', Carbon::now())->orWhereNull('expires_at'); + }) + ->first(); + + if ($model === null) { + if ($this->tokenLogger) { + $this->tokenLogger->warn('Token not found!'); + } + return false; + } + + if ($this->tokenLogger) { + $this->tokenLogger->debug('Found:', [ + 'model' => $model + ]); + } + + $model->fill([ + 'completed' => false, + 'completed_at' => null, + ]); + + $model->save(); + + return $model; + } + /** * Determine if a specified token owner has an incomplete and unexpired token. *