Skip to content
Merged
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@ The backend expects these named parameters:
- `:search` for disabled-user listing
- `:hash` for password updates

### Linking existing accounts

An account is linked to WordPress by the user preference `wordpress_login` of
the app `wordpress_login_backend`, holding the account uid. Admin Group Manager
records it when it creates the account that owns a group.

To link the accounts created before that, run:

```bash
occ wordpress-login-backend:link-users --dry-run
occ wordpress-login-backend:link-users
```

The command links each account that is sub-admin of the group with the same id
as its uid and has a WordPress user with exactly that login. Members of the
groups are never linked and are listed as skipped. With `--dry-run` it only
lists the accounts.

## Support, customization and enterprise

If you need help using this app, or if you want custom development, priority
Expand Down
3 changes: 3 additions & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ Integrate WordPress accounts with Nextcloud]]></description>
<dependencies>
<nextcloud min-version="32" max-version="35"/>
</dependencies>
<commands>
<command>OCA\WordPressLoginBackend\Command\LinkUsers</command>
</commands>
</info>
1 change: 1 addition & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

class Application extends App implements IBootstrap {
public const APP_ID = 'wordpress_login_backend';
public const LINKED_LOGIN_KEY = 'wordpress_login';

public function __construct(array $urlParams = array()) {
parent::__construct(Application::APP_ID, $urlParams);
Expand Down
42 changes: 42 additions & 0 deletions lib/Command/LinkUsers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\WordPressLoginBackend\Command;

use OCA\WordPressLoginBackend\Service\UserLinker;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class LinkUsers extends Command {
public function __construct(
private UserLinker $userLinker,
) {
parent::__construct();
}

protected function configure(): void {
$this
->setName('wordpress-login-backend:link-users')
->setDescription('Link the accounts that own a group of the same name to the WordPress user with that login')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'List the accounts without linking them');
}

protected function execute(InputInterface $input, OutputInterface $output): int {
$dryRun = (bool)$input->getOption('dry-run');
$result = $this->userLinker->link($dryRun);
foreach ($result['linked'] as $uid) {
$output->writeln(($dryRun ? 'Would link: ' : 'Linked: ') . $uid);
}
foreach ($result['skipped'] as $uid) {
$output->writeln('Skipped: ' . $uid);
}
return 0;
}
}
50 changes: 50 additions & 0 deletions lib/Db/WordPressUsers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\WordPressLoginBackend\Db;

use OCA\WordPressLoginBackend\Config\QueryConfig;
use OCP\IConfig;
use PDO;

class WordPressUsers {
private ?PDO $pdo = null;
private QueryConfig $queryConfig;

public function __construct(
private IConfig $config,
) {
$this->queryConfig = new QueryConfig($this->config);
}

public function findByLogin(string $login): ?array {
$database = $this->getDatabase();
if (!$database) {
return null;
}
$statement = $database->prepare($this->queryConfig->getWordPressUserQuery());
$statement->execute(['username' => $login]);
foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
if ((string)$row['uid'] === $login) {
return $row;
}
}
return null;
}

private function getDatabase(): ?PDO {
$dsn = (string)$this->config->getSystemValue('wordpress_dsn', '');
if ($dsn === '') {
return null;
}
if (!$this->pdo instanceof PDO) {
$this->pdo = new PDO($dsn);
}
return $this->pdo;
}
}
59 changes: 59 additions & 0 deletions lib/Service/UserLinker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\WordPressLoginBackend\Service;

use OCA\WordPressLoginBackend\AppInfo\Application;
use OCA\WordPressLoginBackend\Db\WordPressUsers;
use OCP\Group\ISubAdmin;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;

class UserLinker {
public function __construct(
private IConfig $config,
private IGroupManager $groupManager,
private ISubAdmin $subAdmin,
private IUserManager $userManager,
private WordPressUsers $wordPressUsers,
) {
}

/**
* @return array{linked: list<string>, skipped: list<string>}
*/
public function link(bool $dryRun): array {
$linked = [];
$skipped = [];
foreach ($this->groupManager->search('') as $group) {
$groupId = $group->getGID();
$owner = $this->userManager->get($groupId);
if ($owner instanceof IUser
&& $owner->getUID() === $groupId
&& $this->subAdmin->isSubAdminOfGroup($owner, $group)
&& $this->wordPressUsers->findByLogin($groupId) !== null) {
$linked[$groupId] = $groupId;
}
foreach ($group->getUsers() as $member) {
$skipped[$member->getUID()] = $member->getUID();
}
}
$skipped = array_diff_key($skipped, $linked);
if (!$dryRun) {
foreach ($linked as $uid) {
$this->config->setUserValue($uid, Application::APP_ID, Application::LINKED_LOGIN_KEY, $uid);
}
}
return [
'linked' => array_values($linked),
'skipped' => array_values($skipped),
];
}
}
139 changes: 139 additions & 0 deletions tests/Unit/Service/UserLinkerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php

declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\WordPressLoginBackend\Tests\Unit\Service;

use OCA\WordPressLoginBackend\Db\WordPressUsers;
use OCA\WordPressLoginBackend\Service\UserLinker;
use OCP\Group\ISubAdmin;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUser;
use OCP\IUserManager;
use PDO;
use PHPUnit\Framework\TestCase;

class UserLinkerTest extends TestCase {
private string $databaseFile;
private PDO $database;
private array $users = [];
private array $groups = [];
private array $subAdmins = [];
private array $linkedLogins = [];

protected function setUp(): void {
$this->databaseFile = tempnam(sys_get_temp_dir(), 'wordpress');
$this->database = new PDO('sqlite:' . $this->databaseFile);
$this->database->exec('CREATE TABLE wp_users (ID INTEGER PRIMARY KEY, user_login TEXT, user_email TEXT, user_pass TEXT, display_name TEXT)');
$this->database->exec('CREATE TABLE wp_wc_orders (customer_id INTEGER, status TEXT, type TEXT)');
}

protected function tearDown(): void {
unlink($this->databaseFile);
}

public function testLinksTheGroupOwnerThatHasAWordPressLogin(): void {
$this->createWordPressUser('ana');
$this->createGroup('ana', ['ana'], 'ana');

$result = $this->link(false);

$this->assertSame(['ana'], $result['linked']);
$this->assertSame(['ana' => 'ana'], $this->linkedLogins);
}

public function testDoesNotLinkAGroupMemberEvenWithAWordPressLogin(): void {
$this->createWordPressUser('ana');
$this->createWordPressUser('bruno');
$this->createGroup('ana', ['ana', 'bruno'], 'ana');

$result = $this->link(false);

$this->assertSame(['bruno'], $result['skipped']);
$this->assertArrayNotHasKey('bruno', $this->linkedLogins);
}

public function testDoesNotLinkAGroupOwnerThatIsNotItsSubAdmin(): void {
$this->createWordPressUser('ana');
$this->createGroup('ana', ['ana'], null);

$result = $this->link(false);

$this->assertSame([], $result['linked']);
$this->assertSame([], $this->linkedLogins);
}

public function testDoesNotLinkAGroupOwnerWithoutAWordPressLogin(): void {
$this->createWordPressUser('bruno', 'ana');
$this->createGroup('ana', ['ana'], 'ana');

$result = $this->link(false);

$this->assertSame(['ana'], $result['skipped']);
$this->assertSame([], $this->linkedLogins);
}

public function testDryRunListsWithoutLinking(): void {
$this->createWordPressUser('ana');
$this->createGroup('ana', ['ana'], 'ana');

$result = $this->link(true);

$this->assertSame(['ana'], $result['linked']);
$this->assertSame([], $this->linkedLogins);
}

private function createWordPressUser(string $login, ?string $email = null): void {
$statement = $this->database->prepare('INSERT INTO wp_users (user_login, user_email, user_pass, display_name) VALUES (:login, :email, :hash, :login)');
$statement->execute(['login' => $login, 'email' => $email ?? $login . '@example.org', 'hash' => 'hash']);
}

private function createGroup(string $groupId, array $memberIds, ?string $subAdminId): void {
$members = array_map(fn (string $uid) => $this->user($uid), $memberIds);
$group = $this->createMock(IGroup::class);
$group->method('getGID')->willReturn($groupId);
$group->method('getUsers')->willReturn($members);
$this->groups[] = $group;
if ($subAdminId !== null) {
$this->subAdmins[] = [$subAdminId, $groupId];
}
}

private function user(string $uid): IUser {
if (!isset($this->users[$uid])) {
$user = $this->createMock(IUser::class);
$user->method('getUID')->willReturn($uid);
$this->users[$uid] = $user;
}
return $this->users[$uid];
}

private function link(bool $dryRun): array {
$config = $this->createMock(IConfig::class);
$config->method('getSystemValue')->willReturnMap([
['wordpress_dsn', '', 'sqlite:' . $this->databaseFile],
['wordpress_queries', [], []],
]);
$config->method('setUserValue')->willReturnCallback(function (string $uid, string $appName, string $key, string $value): void {
if ($appName === 'wordpress_login_backend' && $key === 'wordpress_login') {
$this->linkedLogins[$uid] = $value;
}
});
$groupManager = $this->createMock(IGroupManager::class);
$groupManager->method('search')->with('')->willReturn($this->groups);
$userManager = $this->createMock(IUserManager::class);
$userManager->method('get')->willReturnCallback(fn (string $uid) => $this->users[$uid] ?? null);
$subAdmin = $this->createMock(ISubAdmin::class);
$subAdmin->method('isSubAdminOfGroup')->willReturnCallback(
fn (IUser $user, IGroup $group) => in_array([$user->getUID(), $group->getGID()], $this->subAdmins, true),
);

return (new UserLinker($config, $groupManager, $subAdmin, $userManager, new WordPressUsers($config)))->link($dryRun);
}
}
Loading
Loading