aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Security/RateLimiting/Backend/DatabaseBackend.php
blob: 9fb237f2f720a1048b542889fd789a785562a29f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OC\Security\RateLimiting\Backend;

use OCP\AppFramework\Utility\ITimeFactory;
use OCP\DB\Exception;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IConfig;
use OCP\IDBConnection;

class DatabaseBackend implements IBackend {
	private const TABLE_NAME = 'ratelimit_entries';

	public function __construct(
		private IConfig $config,
		private IDBConnection $dbConnection,
		private ITimeFactory $timeFactory,
	) {
	}

	private function hash(
		string $methodIdentifier,
		string $userIdentifier,
	): string {
		return hash('sha512', $methodIdentifier . $userIdentifier);
	}

	/**
	 * @throws Exception
	 */
	private function getExistingAttemptCount(
		string $identifier,
	): int {
		$currentTime = $this->timeFactory->getDateTime();

		$qb = $this->dbConnection->getQueryBuilder();
		$qb->delete(self::TABLE_NAME)
			->where(
				$qb->expr()->lte('delete_after', $qb->createNamedParameter($currentTime, IQueryBuilder::PARAM_DATETIME_MUTABLE))
			)
			->executeStatement();

		$qb = $this->dbConnection->getQueryBuilder();
		$qb->select($qb->func()->count())
			->from(self::TABLE_NAME)
			->where(
				$qb->expr()->eq('hash', $qb->createNamedParameter($identifier, IQueryBuilder::PARAM_STR))
			);

		$cursor = $qb->executeQuery();
		$row = $cursor->fetchOne();
		$cursor->closeCursor();

		return (int)$row;
	}

	/**
	 * {@inheritDoc}
	 */
	public function getAttempts(
		string $methodIdentifier,
		string $userIdentifier,
	): int {
		$identifier = $this->hash($methodIdentifier, $userIdentifier);
		return $this->getExistingAttemptCount($identifier);
	}

	/**
	 * {@inheritDoc}
	 */
	public function registerAttempt(
		string $methodIdentifier,
		string $userIdentifier,
		int $period,
	): void {
		$identifier = $this->hash($methodIdentifier, $userIdentifier);
		$deleteAfter = $this->timeFactory->getDateTime()->add(new \DateInterval("PT{$period}S"));

		$qb = $this->dbConnection->getQueryBuilder();

		$qb->insert(self::TABLE_NAME)
			->values([
				'hash' => $qb->createNamedParameter($identifier, IQueryBuilder::PARAM_STR),
				'delete_after' => $qb->createNamedParameter($deleteAfter, IQueryBuilder::PARAM_DATETIME_MUTABLE),
			]);

		if (!$this->config->getSystemValueBool('ratelimit.protection.enabled', true)) {
			return;
		}

		$qb->executeStatement();
	}
}