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
25 changes: 24 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@ occ config:system:set wordpress_dsn --value "mysql:host=myserverhostname;port=33

Replace the values by your database settings.

The database user only needs `SELECT` on the tables read by the queries
(`wp_users` and `wp_wc_orders` with the default ones) and `UPDATE` on
`wp_users.user_pass`:

```sql
GRANT SELECT ON woocommerce.wp_users TO 'nextcloud'@'%';
GRANT SELECT ON woocommerce.wp_wc_orders TO 'nextcloud'@'%';
GRANT UPDATE (user_pass) ON woocommerce.wp_users TO 'nextcloud'@'%';
```

### Linked accounts

Only accounts linked to a WordPress user can log in with the WordPress
password, and only their password changes are written back to WordPress. The
WordPress user is the one whose `user_login` is exactly the account uid. See
[Linking existing accounts](#linking-existing-accounts).

### Custom SQL queries (optional)

You can override default SQL queries using the `wordpress_queries` system key,
Expand All @@ -31,7 +48,7 @@ Supported query keys:
Example:

```bash
occ config:system:set wordpress_queries --type json --value '{"get_wordpress_user":"SELECT user_pass AS password, user_login AS uid, display_name AS displayname, 1 AS enabled FROM wp_users WHERE user_login = :username OR user_email = :username","get_disabled_users":"SELECT user_login AS uid FROM wp_users WHERE user_login LIKE :search","set_wordpress_password":"UPDATE wp_users SET user_pass = :hash WHERE user_login = :username"}'
occ config:system:set wordpress_queries --type json --value '{"get_wordpress_user":"SELECT user_pass AS password, user_login AS uid, display_name AS displayname, 1 AS enabled FROM wp_users WHERE user_login = :username","get_disabled_users":"SELECT user_login AS uid FROM wp_users WHERE user_login LIKE :search","set_wordpress_password":"UPDATE wp_users SET user_pass = :hash WHERE user_login = :username"}'
```

The backend expects these named parameters:
Expand All @@ -46,6 +63,12 @@ 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.

When upgrading from a version that did not require the link, deploy in this
order, otherwise the existing customers cannot log in:

1. a version of Admin Group Manager that records the link;
2. this app, then run the command below to link the existing accounts.

To link the accounts created before that, run:

```bash
Expand Down
6 changes: 3 additions & 3 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@

namespace OCA\WordPressLoginBackend\AppInfo;

use OCA\WordPressLoginBackend\Listener\BeforePasswordUpdatedListener;
use OCA\WordPressLoginBackend\Listener\PasswordUpdatedListener;
use \OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\User\Events\BeforePasswordUpdatedEvent;
use OCP\User\Events\PasswordUpdatedEvent;

class Application extends App implements IBootstrap {
public const APP_ID = 'wordpress_login_backend';
Expand All @@ -28,6 +28,6 @@ public function boot(IBootContext $context): void {
}

public function register(IRegistrationContext $context): void {
$context->registerEventListener(BeforePasswordUpdatedEvent::class, BeforePasswordUpdatedListener::class);
$context->registerEventListener(PasswordUpdatedEvent::class, PasswordUpdatedListener::class);
}
}
33 changes: 14 additions & 19 deletions lib/Backend/UserBackend.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

namespace OCA\WordPressLoginBackend\Backend;

use OCA\WordPressLoginBackend\AppInfo\Application;
use OCA\WordPressLoginBackend\Config\QueryConfig;
use OCA\WordPressLoginBackend\Db\WordPressUsers;
use OCA\WordPressLoginBackend\Helper\HashPassword;
use OCP\Cache\CappedMemoryCache;
use OCP\IConfig;
Expand All @@ -28,6 +30,7 @@ public function __construct(
private CappedMemoryCache $cache,
private IConfig $config,
private IDBConnection $dbConn,
private WordPressUsers $wordPressUsers,
) {
$this->dsn = (string) $this->config->getSystemValue('wordpress_dsn', '');
$this->queryConfig = new QueryConfig($this->config);
Expand Down Expand Up @@ -82,7 +85,7 @@ public function checkPassword(string $loginName, string $password) {
$hashPassword = new HashPassword();
$isOk = $hashPassword->checkPassword($password, $user['password']);
if ($isOk) {
return $loginName;
return $user['uid'];
}
return false;
}
Expand Down Expand Up @@ -117,27 +120,19 @@ private function loadUser($uid) {
return false;
}

$db = $this->getDatabase();
if (!$db) {
$this->cache[$uid] = false;
return false;
}
$statement = $db->prepare($this->queryConfig->getWordPressUserQuery());
$statement->execute(['username' => $uid]);
$row = $statement->fetch(PDO::FETCH_ASSOC);

// "uid" is primary key, so there can only be a single result
if ($row !== false) {
$this->cache[$uid] = [
'uid' => (string)$row['uid'],
'displayname' => (string)$row['displayname'],
'password' => (string)$row['password'],
'enabled' => (bool)$row['enabled'],
];
} else {
$nextcloudUid = (string)$nextcloudUser['uid'];
$linkedLogin = $this->config->getUserValue($nextcloudUid, Application::APP_ID, Application::LINKED_LOGIN_KEY);
$row = $linkedLogin === $nextcloudUid ? $this->wordPressUsers->findByLogin($nextcloudUid) : null;
if ($row === null) {
$this->cache[$uid] = false;
return false;
}
$this->cache[$uid] = [
'uid' => (string)$row['uid'],
'displayname' => (string)$row['displayname'],
'password' => (string)$row['password'],
'enabled' => (bool)$row['enabled'],
];
}

return $this->cache[$uid];
Expand Down
13 changes: 9 additions & 4 deletions lib/Config/QueryConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,25 @@ class QueryConfig {
ELSE 0
END AS enabled
FROM wp_users u
WHERE (u.user_login = :username OR u.user_email = :username)
WHERE u.user_login = :username
AND HEX(u.user_login) = HEX(:username)
SQL;

public const DEFAULT_GET_DISABLED_USERS = <<<'SQL'
SELECT u.user_login AS uid
FROM wp_wc_orders o
JOIN wp_users u ON o.customer_id = u.ID
WHERE (o.status NOT IN ('wc-active') OR o.type <> 'shop_subscription')
AND (u.user_login LIKE :search OR u.user_email LIKE :search)
AND u.user_login LIKE :search
GROUP BY u.user_login
SQL;

public const DEFAULT_SET_WORDPRESS_PASSWORD =
'UPDATE wp_users SET user_pass = :hash WHERE user_login = :username';
public const DEFAULT_SET_WORDPRESS_PASSWORD = <<<'SQL'
UPDATE wp_users
SET user_pass = :hash
WHERE user_login = :username
AND HEX(user_login) = HEX(:username)
SQL;

public function __construct(
private IConfig $config,
Expand Down
11 changes: 11 additions & 0 deletions lib/Db/WordPressUsers.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ public function findByLogin(string $login): ?array {
return null;
}

public function updatePassword(string $login, string $hash): void {
$database = $this->getDatabase();
if (!$database) {
return;
}
$statement = $database->prepare($this->queryConfig->setWordPressPasswordQuery());
$statement->bindValue(':username', $login);
$statement->bindValue(':hash', $hash);
$statement->execute();
}

private function getDatabase(): ?PDO {
$dsn = (string)$this->config->getSystemValue('wordpress_dsn', '');
if ($dsn === '') {
Expand Down
73 changes: 0 additions & 73 deletions lib/Listener/BeforePasswordUpdatedListener.php

This file was deleted.

54 changes: 54 additions & 0 deletions lib/Listener/PasswordUpdatedListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

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

namespace OCA\WordPressLoginBackend\Listener;

use OCA\WordPressLoginBackend\AppInfo\Application;
use OCA\WordPressLoginBackend\Db\WordPressUsers;
use OCA\WordPressLoginBackend\Helper\HashPassword;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IConfig;
use OCP\User\Events\PasswordUpdatedEvent;
use PDOException;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<Event|PasswordUpdatedEvent>
*/
class PasswordUpdatedListener implements IEventListener {
public function __construct(
private IConfig $config,
private WordPressUsers $wordPressUsers,
private LoggerInterface $logger,
) {
}

public function handle(Event $event): void {
if (!$event instanceof PasswordUpdatedEvent) {
return;
}
$username = $event->getUser()->getUID();
if ($this->config->getUserValue($username, Application::APP_ID, Application::LINKED_LOGIN_KEY) !== $username) {
return;
}
$hashPassword = new HashPassword();
try {
$wordPressUser = $this->wordPressUsers->findByLogin($username);
if ($wordPressUser === null || $hashPassword->validate($event->getPassword(), (string)$wordPressUser['password'])) {
return;
}
$this->wordPressUsers->updatePassword($username, $hashPassword->hashPassword($event->getPassword()));
} catch (PDOException $exception) {
$this->logger->error('Could not update the WordPress password of {uid}', [
'uid' => $username,
'exception' => $exception,
]);
}
}
}
Loading
Loading