summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/OATHAuth/includes/OATHAuthHooks.php
blob: 8842b16a22a5c377a8fa6fb585d684e39357d0b5 (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 */

use MediaWiki\Auth\AuthenticationRequest;
use MediaWiki\MediaWikiServices;
use Wikimedia\Rdbms\IDatabase;

/**
 * Hooks for Extension:OATHAuth
 *
 * @ingroup Extensions
 */
class OATHAuthHooks {
	/**
	 * Get the singleton OATH user repository
	 *
	 * @return OATHUserRepository
	 */
	public static function getOATHUserRepository() {
		global $wgOATHAuthDatabase;

		static $service = null;

		if ( $service == null ) {
			$factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
			$service = new OATHUserRepository(
				$factory->getMainLB( $wgOATHAuthDatabase ),
				new HashBagOStuff(
					[
						'maxKeys' => 5,
					]
				)
			);
		}

		return $service;
	}

	/**
	 * @param AuthenticationRequest[] $requests
	 * @param array $fieldInfo Field information array (union of the
	 *    AuthenticationRequest::getFieldInfo() responses).
	 * @param array &$formDescriptor HTMLForm descriptor. The special key 'weight' can be set
	 *   to change the order of the fields.
	 * @param string $action One of the AuthManager::ACTION_* constants.
	 * @return bool
	 */
	public static function onAuthChangeFormFields(
		array $requests, array $fieldInfo, array &$formDescriptor, $action
	) {
		if ( isset( $fieldInfo['OATHToken'] ) ) {
			$formDescriptor['OATHToken'] += [
				'cssClass' => 'loginText',
				'id' => 'wpOATHToken',
				'size' => 20,
				'autofocus' => true,
				'persistent' => false,
				'autocomplete' => false,
				'spellcheck' => false,
			];
		}
		return true;
	}

	/**
	 * Determine if two-factor authentication is enabled for $wgUser
	 *
	 * This isn't the preferred mechanism for controlling access to sensitive features
	 * (see AuthManager::securitySensitiveOperationStatus() for that) but there is no harm in
	 * keeping it.
	 *
	 * @param bool &$isEnabled Will be set to true if enabled, false otherwise
	 * @return bool False if enabled, true otherwise
	 */
	public static function onTwoFactorIsEnabled( &$isEnabled ) {
		global $wgUser;

		$user = self::getOATHUserRepository()->findByUser( $wgUser );
		if ( $user && $user->getKey() !== null ) {
			$isEnabled = true;
			# This two-factor extension is enabled by the user,
			# we don't need to check others.
			return false;
		} else {
			$isEnabled = false;
			# This two-factor extension isn't enabled by the user,
			# but others may be.
			return true;
		}
	}

	/**
	 * Add the necessary user preferences for OATHAuth
	 *
	 * @param User $user
	 * @param array &$preferences
	 * @return bool
	 */
	public static function onGetPreferences( User $user, array &$preferences ) {
		$oathUser = self::getOATHUserRepository()->findByUser( $user );

		// If there is no existing key, and the user is not allowed to enable it,
		// we have nothing to show. (
		if ( $oathUser->getKey() === null && !$user->isAllowed( 'oathauth-enable' ) ) {
			return true;
		}

		$title = SpecialPage::getTitleFor( 'OATH' );
		$msg = $oathUser->getKey() !== null ? 'oathauth-disable' : 'oathauth-enable';

		$preferences[$msg] = [
			'type' => 'info',
			'raw' => 'true',
			'default' => Linker::link(
				$title,
				wfMessage( $msg )->escaped(),
				[],
				[ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ]
			),
			'label-message' => 'oathauth-prefs-label',
			'section' => 'personal/info', ];

		return true;
	}

	/**
	 * @param DatabaseUpdater $updater
	 * @return bool
	 */
	public static function onLoadExtensionSchemaUpdates( $updater ) {
		$base = dirname( __DIR__ );
		switch ( $updater->getDB()->getType() ) {
			case 'mysql':
			case 'sqlite':
				$updater->addExtensionTable( 'oathauth_users', "$base/sql/mysql/tables.sql" );
				$updater->addExtensionUpdate( [ [ __CLASS__, 'schemaUpdateOldUsersFromInstaller' ] ] );
				$updater->dropExtensionField(
					'oathauth_users',
					'secret_reset',
					"$base/sql/mysql/patch-remove_reset.sql"
				);
				break;

			case 'oracle':
				$updater->addExtensionTable( 'oathauth_users', "$base/sql/oracle/tables.sql" );
				break;

			case 'postgres':
				$updater->addExtensionTable( 'oathauth_users', "$base/sql/postgres/tables.sql" );
				break;
		}

		return true;
	}

	/**
	 * Helper function for converting old users to the new schema
	 * @see OATHAuthHooks::OATHAuthSchemaUpdates
	 *
	 * @param DatabaseUpdater $updater
	 *
	 * @return bool
	 */
	public static function schemaUpdateOldUsersFromInstaller( DatabaseUpdater $updater ) {
		return self::schemaUpdateOldUsers( $updater->getDB() );
	}

	/**
	 * Helper function for converting old users to the new schema
	 * @see OATHAuthHooks::OATHAuthSchemaUpdates
	 *
	 * @param IDatabase $db
	 * @return bool
	 */
	public static function schemaUpdateOldUsers( IDatabase $db ) {
		if ( !$db->fieldExists( 'oathauth_users', 'secret_reset' ) ) {
			return true;
		}

		$res = $db->select(
			'oathauth_users',
			[ 'id', 'scratch_tokens' ],
			[ 'is_validated != 0' ],
			__METHOD__
		);

		foreach ( $res as $row ) {
			Wikimedia\suppressWarnings();
			$scratchTokens = unserialize( base64_decode( $row->scratch_tokens ) );
			Wikimedia\restoreWarnings();
			if ( $scratchTokens ) {
				$db->update(
					'oathauth_users',
					[ 'scratch_tokens' => implode( ',', $scratchTokens ) ],
					[ 'id' => $row->id ],
					__METHOD__
				);
			}
		}

		// Remove rows from the table where user never completed the setup process
		$db->delete( 'oathauth_users', [ 'is_validated' => 0 ], __METHOD__ );

		return true;
	}
}