Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Google OAuth support #7430

Merged
merged 5 commits into from
Dec 2, 2022
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
15 changes: 15 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,21 @@
'url' => '/api/outbox/{id}',
'verb' => 'POST'
],
[
'name' => 'googleIntegration#configure',
'url' => '/api/integration/google',
'verb' => 'POST',
],
[
'name' => 'googleIntegration#unlink',
'url' => '/api/integration/google',
'verb' => 'DELETE',
],
[
'name' => 'googleIntegration#oauthRedirect',
'url' => '/integration/google-auth',
'verb' => 'GET',
],
],
'resources' => [
'accounts' => ['url' => '/api/accounts'],
Expand Down
7 changes: 7 additions & 0 deletions doc/admin.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ occ config:app:set mail abuse_number_of_messages_per_1h --value=30
occ config:app:set mail abuse_number_of_messages_per_1d --value=100
```

## Google OAuth

This app can allow users to connect their Google accounts with OAuth. This makes it possible to use accounts without 2FA or app password.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we mention app passwords as well? Or are they not going to work any longer?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They work, but only if you use 2FA.

1) [Create authorization credentials](https://developers.google.com/identity/protocols/oauth2/web-server#prerequisites). You will receive a client ID and a client secret.
2) Open the Nextcloud settings page. Navigate to *Groupware* and scroll down to *Gmail integration*. Enter and save the client ID and client secret.

## Troubleshooting

### Logging
Expand Down
3 changes: 3 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use OCA\Mail\Contracts\IUserPreferences;
use OCA\Mail\Dashboard\ImportantMailWidget;
use OCA\Mail\Dashboard\UnreadMailWidget;
use OCA\Mail\Events\BeforeImapClientCreated;
use OCA\Mail\Events\BeforeMessageSentEvent;
use OCA\Mail\Events\DraftMessageCreatedEvent;
use OCA\Mail\Events\DraftSavedEvent;
Expand All @@ -50,6 +51,7 @@
use OCA\Mail\Listener\AddressCollectionListener;
use OCA\Mail\Listener\AntiAbuseListener;
use OCA\Mail\Listener\HamReportListener;
use OCA\Mail\Listener\OauthTokenRefreshListener;
use OCA\Mail\Listener\SpamReportListener;
use OCA\Mail\Listener\DeleteDraftListener;
use OCA\Mail\Listener\FlagRepliedMessageListener;
Expand Down Expand Up @@ -104,6 +106,7 @@ public function register(IRegistrationContext $context): void {
$context->registerServiceAlias(ITrustedSenderService::class, TrustedSenderService::class);
$context->registerServiceAlias(IUserPreferences::class, UserPreferenceService::class);

$context->registerEventListener(BeforeImapClientCreated::class, OauthTokenRefreshListener::class);
$context->registerEventListener(BeforeMessageSentEvent::class, AntiAbuseListener::class);
$context->registerEventListener(DraftSavedEvent::class, DeleteDraftListener::class);
$context->registerEventListener(DraftMessageCreatedEvent::class, DeleteDraftListener::class);
Expand Down
165 changes: 165 additions & 0 deletions lib/Controller/GoogleIntegrationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
<?php

declare(strict_types=1);

/*
* @copyright 2022 Christoph Wurst <[email protected]>
*
* @author 2022 Christoph Wurst <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace OCA\Mail\Controller;

use OCA\Mail\AppInfo\Application;
use OCA\Mail\Exception\ClientException;
use OCA\Mail\Http\JsonResponse;
use OCA\Mail\Integration\GoogleIntegration;
use OCA\Mail\Service\AccountService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\StandaloneTemplateResponse;
use OCP\IRequest;
use Psr\Log\LoggerInterface;
use function filter_var;

class GoogleIntegrationController extends Controller {
private ?string $userId;
private GoogleIntegration $googleIntegration;
private AccountService $accountService;
private LoggerInterface $logger;

public function __construct(IRequest $request,
?string $UserId,
GoogleIntegration $googleIntegration,
AccountService $accountService,
LoggerInterface $logger) {
parent::__construct(Application::APP_ID, $request);
$this->userId = $UserId;
$this->googleIntegration = $googleIntegration;
$this->accountService = $accountService;
$this->logger = $logger;
}

/**
* @param string $clientId
* @param string $clientSecret
*
* @return JsonResponse
*/
public function configure(string $clientId, string $clientSecret): JsonResponse {
if (empty($clientId) || empty($clientSecret)) {
return JsonResponse::fail(null, Http::STATUS_UNPROCESSABLE_ENTITY);
}

$this->googleIntegration->configure(
$clientId,
$clientSecret,
);

return JsonResponse::success([
'clientId' => $clientId,
]);
}

/*
* @return JsonResponse
*/
public function unlink(): JsonResponse {
$this->googleIntegration->unlink();

return JsonResponse::success([]);
}

/**
* @param int $id
* @param string|null $code
* @param string|null $state
* @param string|null $scope
* @param string|null $error
*
* @NoAdminRequired
* @NoCSRFRequired
*
* @return Response
*/
public function oauthRedirect(?string $code, ?string $state, ?string $scope, ?string $error): Response {
if ($this->userId === null) {
// TODO: redirect to main nextcloud page
return new StandaloneTemplateResponse(
Application::APP_ID,
'google_oauth_done',
[],
'guest',
);
}

if (!isset($code, $state, $scope)) {
// TODO: handle error
return new StandaloneTemplateResponse(
Application::APP_ID,
'google_oauth_done',
[],
'guest',
);
}
if (!filter_var($state, FILTER_VALIDATE_INT)) {
$this->logger->warning('Can not link Google account due to invalid state/account id {state}', [
'state' => $state,
]);
// TODO: redirect to main nextcloud page
return new StandaloneTemplateResponse(
Application::APP_ID,
'google_oauth_done',
[],
'guest',
);
}

try {
$account = $this->accountService->find(
$this->userId,
(int) $state,
);
} catch (ClientException $e) {
$this->logger->warning('Attempted Google authentication redirect for account: ' . $e->getMessage(), [
'exception' => $e,
]);
// TODO: redirect to main nextcloud page
return new StandaloneTemplateResponse(
Application::APP_ID,
'google_oauth_done',
[],
'guest',
);
}

$updated = $this->googleIntegration->finishConnect(
$account,
$code,
);
$this->accountService->update($updated->getMailAccount());

return new StandaloneTemplateResponse(
Application::APP_ID,
'google_oauth_done',
[],
'guest',
);
}
}
18 changes: 18 additions & 0 deletions lib/Controller/PageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

namespace OCA\Mail\Controller;

use OCA\Mail\AppInfo\Application;
use OCA\Mail\Contracts\IMailManager;
use OCA\Mail\Contracts\IUserPreferences;
use OCA\Mail\Service\OutboxService;
Expand All @@ -50,6 +51,7 @@
use Psr\Log\LoggerInterface;
use Throwable;
use function class_exists;
use function http_build_query;
use function json_decode;

class PageController extends Controller {
Expand Down Expand Up @@ -184,6 +186,22 @@ public function index(): TemplateResponse {
'outbox-messages',
$this->outboxService->getMessages($user->getUID())
);
$clientId = $this->config->getAppValue(Application::APP_ID, 'google_oauth_client_id');
if (!empty($clientId)) {
$this->initialStateService->provideInitialState(
'google-oauth-url',
'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
'client_id' => $clientId,
'redirect_uri' => $this->urlGenerator->linkToRouteAbsolute('mail.googleIntegration.oauthRedirect'),
'response_type' => 'code',
'prompt' => 'consent',
'state' => '_accountId_', // Replaced by frontend
'scope' => 'https://mail.google.com/',
'access_type' => 'offline',
'login_hint' => '_email_', // Replaced by frontend
]),
);
}

// Disable scheduled send in frontend if ajax cron is used because it is unreliable
$cronMode = $this->config->getAppValue('core', 'backgroundjobs_mode', 'ajax');
Expand Down
46 changes: 46 additions & 0 deletions lib/Events/BeforeImapClientCreated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

/*
* @copyright 2022 Christoph Wurst <[email protected]>
*
* @author 2022 Christoph Wurst <[email protected]>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace OCA\Mail\Events;

use OCA\Mail\Account;
use OCP\EventDispatcher\Event;

class BeforeImapClientCreated extends Event {
/** @var Account */
private $account;

public function __construct(Account $account) {
parent::__construct();
$this->account = $account;
}

/**
* @return Account
*/
public function getAccount(): Account {
return $this->account;
}
}
14 changes: 13 additions & 1 deletion lib/IMAP/IMAPClientFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
use Horde_Imap_Client_Socket;
use OCA\Mail\Account;
use OCA\Mail\Cache\Cache;
use OCA\Mail\Events\BeforeImapClientCreated;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\Security\ICrypto;
Expand All @@ -42,15 +44,22 @@ class IMAPClientFactory {
/** @var ICacheFactory */
private $cacheFactory;

/** @var IEventDispatcher */
private $eventDispatcher;

/**
* @param ICrypto $crypto
* @param IConfig $config
* @param ICacheFactory $cacheFactory
*/
public function __construct(ICrypto $crypto, IConfig $config, ICacheFactory $cacheFactory) {
public function __construct(ICrypto $crypto,
IConfig $config,
ICacheFactory $cacheFactory,
IEventDispatcher $eventDispatcher) {
$this->crypto = $crypto;
$this->config = $config;
$this->cacheFactory = $cacheFactory;
$this->eventDispatcher = $eventDispatcher;
}

/**
Expand All @@ -65,6 +74,9 @@ public function __construct(ICrypto $crypto, IConfig $config, ICacheFactory $cac
* @return Horde_Imap_Client_Socket
*/
public function getClient(Account $account, bool $useCache = true): Horde_Imap_Client_Socket {
$this->eventDispatcher->dispatchTyped(
new BeforeImapClientCreated($account)
);
$host = $account->getMailAccount()->getInboundHost();
$user = $account->getMailAccount()->getInboundUser();
$decryptedPassword = $this->crypto->decrypt($account->getMailAccount()->getInboundPassword());
Expand Down
Loading