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
53 changes: 45 additions & 8 deletions core/Command/User/Profile.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use OCP\Accounts\PropertyDoesNotExistException;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Mail\IEmailValidator;
use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -25,6 +26,7 @@ class Profile extends Base {
public function __construct(
protected IUserManager $userManager,
protected IAccountManager $accountManager,
protected IEmailValidator $emailValidator,
) {
parent::__construct();
}
Expand Down Expand Up @@ -179,32 +181,67 @@ private function deleteProfileProperty(OutputInterface $output, IAccount $userAc
}

private function editProfileProperty(OutputInterface $output, IAccount $userAccount, string $key, string $value): int {
$user = $userAccount->getUser();
try {
// Through IUser, so system values and events follow; the account is written too, as it may have drifted.
if ($key === IAccountManager::PROPERTY_EMAIL) {
if ($value !== '' && !$this->emailValidator->isValid(trim($value))) {
$output->writeln('<error>Invalid email address</error>');
return self::FAILURE;
}
$user->setSystemEMailAddress($value);
$value = $user->getSystemEMailAddress() ?? '';
} elseif ($key === IAccountManager::PROPERTY_DISPLAYNAME) {
$value = trim($value);
if ($value === '') {
$output->writeln('<error>New display name can\'t be empty</error>');
return self::FAILURE;
}
if (!$user->setDisplayName($value) && $user->getDisplayName() !== $value) {
$output->writeln('<error>Could not set display name</error>');
return self::FAILURE;
}
$value = $user->getDisplayName();
}

$userAccount->getProperty($key)->setValue($value);
$this->accountManager->updateAccount($userAccount);
} catch (PropertyDoesNotExistException $exception) {
$output->writeln('<error>' . $exception->getMessage() . '</error>');
return self::FAILURE;
} catch (\InvalidArgumentException $exception) {
$output->writeln('<error>Could not save: ' . $exception->getMessage() . '</error>');
return self::FAILURE;
}

$this->accountManager->updateAccount($userAccount);
return self::SUCCESS;
}

private function getStoredValue(IAccount $userAccount, string $key): ?string {
try {
$property = $userAccount->getProperty($key);
} catch (PropertyDoesNotExistException) {
return null;
if ($key === IAccountManager::PROPERTY_EMAIL) {
$value = $userAccount->getUser()->getSystemEMailAddress() ?? '';
} elseif ($key === IAccountManager::PROPERTY_DISPLAYNAME) {
$value = $userAccount->getUser()->getDisplayName();
} else {
try {
$value = $userAccount->getProperty($key)->getValue();
} catch (PropertyDoesNotExistException) {
return null;
}
}
return $property->getValue() === '' ? null : $property->getValue();
return $value === '' ? null : $value;
}

private function getAllProfileProperties(IAccount $userAccount): array {
$properties = [];

foreach ($userAccount->getAllProperties() as $property) {
if ($property->getValue() !== '') {
$properties[$property->getName()] = $property->getValue();
$name = $property->getName();
$value = in_array($name, [IAccountManager::PROPERTY_EMAIL, IAccountManager::PROPERTY_DISPLAYNAME], true)
? $this->getStoredValue($userAccount, $name) ?? ''
: $property->getValue();
if ($value !== '') {
$properties[$name] = $value;
}
}

Expand Down
198 changes: 195 additions & 3 deletions tests/Core/Command/User/ProfileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use OCP\IDBConnection;
use OCP\IUser;
use OCP\IUserManager;
use OCP\Mail\IEmailValidator;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -26,6 +27,7 @@ class ProfileTest extends TestCase {

protected IAccountManager&MockObject $accountManager;
protected IUserManager&MockObject $userManager;
protected IEmailValidator&MockObject $emailValidator;
protected IDBConnection&MockObject $connection;
protected InputInterface&MockObject $consoleInput;
protected OutputInterface&MockObject $consoleOutput;
Expand All @@ -36,19 +38,21 @@ protected function setUp(): void {

$this->accountManager = $this->createMock(IAccountManager::class);
$this->userManager = $this->createMock(IUserManager::class);
$this->emailValidator = $this->createMock(IEmailValidator::class);
$this->connection = $this->createMock(IDBConnection::class);
$this->consoleInput = $this->createMock(InputInterface::class);
$this->consoleOutput = $this->createMock(OutputInterface::class);
}

public function getCommand(array $methods = []): Profile|MockObject {
if (empty($methods)) {
return new Profile($this->userManager, $this->accountManager);
return new Profile($this->userManager, $this->accountManager, $this->emailValidator);
} else {
return $this->getMockBuilder(Profile::class)
->setConstructorArgs([
$this->userManager,
$this->accountManager,
$this->emailValidator,
])
->onlyMethods($methods)
->getMock();
Expand Down Expand Up @@ -318,6 +322,191 @@ public function testExecuteSetProfileProperty(): void {
$this->assertEquals(0, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

/**
* Prepares a set (value given) or delete (value null) call for a key that must go through IUser.
* The account property is expected to receive $synced, or to stay untouched when $synced is null.
*
* @return array{0: Profile&MockObject, 1: IUser&MockObject}
*/
private function prepareUserBackedProperty(string $key, ?string $inputValue, ?string $synced, bool $errorIfNotExists = false, ?\Throwable $updateFails = null): array {
$command = $this->getCommand(['checkInput']);

$this->consoleInput->method('getArgument')
->willReturnMap([
['uid', 'username'],
['key', $key],
['value', $inputValue],
]);
$this->consoleInput->method('hasParameterOption')
->willReturnCallback(fn (string $option): bool => $inputValue === null
&& ($option === '--delete' || ($errorIfNotExists && $option === '--error-if-not-exists')));

$user = $this->createMock(IUser::class);
$property = $this->getAccountPropertyMock($key, 'drifted');
$account = $this->createMock(IAccount::class);
$account->method('getUser')->willReturn($user);
$account->method('getProperty')->with($key)->willReturn($property);
$this->accountManager->method('getAccount')->with($user)->willReturn($account);
$command->method('checkInput')->willReturn($user);

if ($synced === null) {
$property->expects($this->never())->method('setValue');
$this->accountManager->expects($this->never())->method('updateAccount');
} else {
$property->expects($this->once())->method('setValue')->with($synced);
$update = $this->accountManager->expects($this->once())->method('updateAccount')->with($account);
if ($updateFails !== null) {
$update->willThrowException($updateFails);
}
}

return [$command, $user];
}

public static function dataExecuteEmail(): array {
return [
'Setting email should update system address and account' => ['New@Example.com', 'old@example.com', 'new@example.com'],
'Setting unchanged email should still sync a drifted account' => ['old@example.com', 'old@example.com', 'old@example.com'],
'Deleting email should clear system address and account' => [null, 'old@example.com', ''],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('dataExecuteEmail')]
public function testExecuteEmail(?string $inputValue, string $systemValue, string $synced): void {
[$command, $user] = $this->prepareUserBackedProperty('email', $inputValue, $synced);
$this->emailValidator->method('isValid')->willReturn(true);

$user->expects($this->once())
->method('setSystemEMailAddress')
->with($inputValue ?? '');
$user->method('getSystemEMailAddress')->willReturnOnConsecutiveCalls($systemValue, $synced === '' ? null : $synced);

$this->assertEquals(Command::SUCCESS, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public function testExecuteEmailAccountUpdateFails(): void {
[$command, $user] = $this->prepareUserBackedProperty('email', 'new@example.com', 'new@example.com', false, new \InvalidArgumentException('phone'));
$this->emailValidator->method('isValid')->willReturn(true);
$user->method('getSystemEMailAddress')->willReturnOnConsecutiveCalls('old@example.com', 'new@example.com');
$this->consoleOutput->expects($this->once())
->method('writeln')
->with('<error>Could not save: phone</error>');

$this->assertEquals(Command::FAILURE, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public function testExecuteInvalidEmail(): void {
[$command, $user] = $this->prepareUserBackedProperty('email', 'no mail', null);
$this->emailValidator->method('isValid')->with('no mail')->willReturn(false);

$user->expects($this->never())->method('setSystemEMailAddress');
$this->consoleOutput->expects($this->once())
->method('writeln')
->with('<error>Invalid email address</error>');

$this->assertEquals(Command::FAILURE, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public static function dataExecuteDeleteEmailErrorIfNotExists(): array {
return [
'System address set should delete' => ['old@example.com', Command::SUCCESS],
'System address empty should fail' => [null, Command::FAILURE],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('dataExecuteDeleteEmailErrorIfNotExists')]
public function testExecuteDeleteEmailErrorIfNotExists(?string $systemValue, int $expectedReturn): void {
$success = $expectedReturn === Command::SUCCESS;
[$command, $user] = $this->prepareUserBackedProperty('email', null, $success ? '' : null, true);

$user->method('getSystemEMailAddress')->willReturnOnConsecutiveCalls($systemValue, null);
$user->expects($success ? $this->once() : $this->never())->method('setSystemEMailAddress')->with('');

$this->assertEquals($expectedReturn, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public static function dataExecuteGetEmail(): array {
return [
'Getting email should print the system address' => [null, 'new@example.com', 'new@example.com', Command::SUCCESS],
'Getting unset email should fail' => [null, null, '<error>The property does not exist for user "username".</error>', Command::FAILURE],
'Updating unset email with update-only should fail' => ['a@example.com', null, '<error>The property does not exist for user "username".</error>', Command::FAILURE],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('dataExecuteGetEmail')]
public function testExecuteGetEmail(?string $inputValue, ?string $systemValue, string $expectedLine, int $expectedReturn): void {
$command = $this->getCommand(['checkInput']);
$this->consoleInput->method('getArgument')
->willReturnMap([
['uid', 'username'],
['key', 'email'],
['value', $inputValue],
]);
$this->consoleInput->method('hasParameterOption')
->willReturnCallback(fn (string $option): bool => $option === '--update-only');

$user = $this->createMock(IUser::class);
$user->method('getSystemEMailAddress')->willReturn($systemValue);
$user->expects($this->never())->method('setSystemEMailAddress');
$account = $this->createMock(IAccount::class);
$account->method('getUser')->willReturn($user);
$account->expects($this->never())->method('getProperty');
$this->accountManager->method('getAccount')->willReturn($account);
$command->method('checkInput')->willReturn($user);

$this->consoleOutput->expects($this->once())
->method('writeln')
->with($expectedLine);

$this->assertEquals($expectedReturn, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public static function dataExecuteSetDisplayName(): array {
return [
'Setting new display name should succeed' => ['New Name', true, 'New Name'],
'Setting unchanged display name should still sync a drifted account' => ['Old Name', false, 'Old Name'],
'Surrounding whitespace should be ignored' => [' Old Name ', false, 'Old Name'],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('dataExecuteSetDisplayName')]
public function testExecuteSetDisplayName(string $inputValue, bool $changed, string $synced): void {
[$command, $user] = $this->prepareUserBackedProperty('displayname', $inputValue, $synced);

$user->expects($this->once())
->method('setDisplayName')
->with($synced)
->willReturn($changed);
$user->method('getDisplayName')->willReturn($synced);
$this->consoleOutput->expects($this->never())
->method('writeln');

$this->assertEquals(Command::SUCCESS, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public static function dataExecuteDisplayNameFailure(): array {
return [
'Setting display name rejected by backend should fail' => ['New Name', false, '<error>Could not set display name</error>'],
'Setting display name the backend throws on should fail' => ['New Name', true, '<error>Could not save: Invalid displayname</error>'],
'Deleting display name should fail' => [null, false, '<error>New display name can\'t be empty</error>'],
'Whitespace-only display name should fail' => [' ', false, '<error>New display name can\'t be empty</error>'],
];
}

#[\PHPUnit\Framework\Attributes\DataProvider('dataExecuteDisplayNameFailure')]
public function testExecuteDisplayNameFailure(?string $inputValue, bool $throws, string $expectedLine): void {
[$command, $user] = $this->prepareUserBackedProperty('displayname', $inputValue, null);

$setter = $user->method('setDisplayName');
$throws ? $setter->willThrowException(new \InvalidArgumentException('Invalid displayname')) : $setter->willReturn(false);
$user->method('getDisplayName')->willReturn('Old Name');
$this->consoleOutput->expects($this->once())
->method('writeln')
->with($expectedLine);

$this->assertEquals(Command::FAILURE, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}

public static function dataExecuteGet(): array {
return [
'Get property with set value should pass' => ['configkey', 'value', null, 'value', Command::SUCCESS],
Expand Down Expand Up @@ -390,15 +579,18 @@ public function testExecuteList(): void {
['key', ''],
]);

$mocks = $this->setupProfilePropertiesMock(['address' => $profileData['address'], 'pronouns' => $profileData['pronouns']]);
$mocks = $this->setupProfilePropertiesMock(['address' => $profileData['address'], 'pronouns' => $profileData['pronouns'], 'email' => 'drifted@example.com', 'displayname' => 'Drifted']);
$mocks['accountMock']->method('getUser')->willReturn($mocks['userMock']);
$mocks['userMock']->method('getSystemEMailAddress')->willReturn(null);
$mocks['userMock']->method('getDisplayName')->willReturn('System Name');

$command->expects($this->once())
->method('checkInput')
->willReturn($mocks['userMock']);

$command->expects($this->once())
->method('writeArrayInOutputFormat')
->with($this->consoleInput, $this->consoleOutput, $profileData);
->with($this->consoleInput, $this->consoleOutput, $profileData + ['displayname' => 'System Name']);

$this->assertEquals(0, $this->invokePrivate($command, 'execute', [$this->consoleInput, $this->consoleOutput]));
}
Expand Down