authy-wp.php 13.3 KB
Newer Older
Erick Hitter's avatar
Erick Hitter committed
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
<?php
/*
 * Plugin Name: Authy for WordPress
 * Plugin URI: http://www.ethitter.com/plugins/authy-for-wordpress/
 * Description: Add <a href="http://www.authy.com/">Authy</a> two-factor authentication to WordPress.
 * Author: Erick Hitter
 * Version: 0.1
 * Author URI: http://www.ethitter.com/
 * License: GPL2+

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 St, Fifth Floor, Boston, MA  02110-1301  USA
*/

class Authy_WP {
	/**
	 * Class variables
	 */
	// Oh look, a singleton
	private static $__instance = null;

33
34
35
	private $settings = null;

	// Authy API
Erick Hitter's avatar
Erick Hitter committed
36
	protected $api = null;
37
38
	protected $api_key = null;
	protected $api_endpoint = null;
39
	protected $environment = 'production';
40
41

	// Commong plugin elements
Erick Hitter's avatar
Erick Hitter committed
42
43
44
45
46
	protected $settings_page = 'authy-for-wp';
	protected $users_page = 'authy-for-wp-user';

	protected $settings_key = 'authy_for_wp';
	protected $users_key = 'authy_for_wp_user';
Erick Hitter's avatar
Erick Hitter committed
47

48
49
50
51
52
53
54
55
56
57
	protected $settings_fields = array();

	protected $settings_field_defaults = array(
		'label'    => null,
		'type'     => 'text',
		'sanitizer' => 'sanitize_text_field',
		'section'  => 'default',
		'class'    => null
	);

Erick Hitter's avatar
Erick Hitter committed
58
59
60
61
62
63
64
	protected $user_defaults = array(
		'email'        => null,
		'phone'        => null,
		'country_code' => null,
		'authy_id'     => null
	);

Erick Hitter's avatar
Erick Hitter committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
	/**
	 * Singleton implementation
	 *
	 * @uses this::setup
	 * @return object
	 */
	public static function instance() {
		if ( ! is_a( self::$__instance, 'Authy_WP' ) ) {
			self::$__instance = new Authy_WP;
			self::$__instance->setup();
		}

		return self::$__instance;
	}

	/**
	 * Silence is golden.
	 */
	private function __construct() {}

	/**
	 *
	 */
Erick Hitter's avatar
Erick Hitter committed
88
	private function setup() {
Erick Hitter's avatar
Erick Hitter committed
89
90
		require( 'authy-wp-api.php' );

91
92
93
		$this->register_settings_fields();
		$this->prepare_api();

Erick Hitter's avatar
Erick Hitter committed
94
		// Plugin settings
Erick Hitter's avatar
Erick Hitter committed
95
		add_action( 'admin_init', array( $this, 'action_admin_init' ) );
Erick Hitter's avatar
Erick Hitter committed
96
		add_action( 'admin_menu', array( $this, 'action_admin_menu' ) );
Erick Hitter's avatar
Erick Hitter committed
97
98
99

		// User settings
		add_action( 'show_user_profile', array( $this, 'action_show_user_profile' ) );
100
		add_action( 'edit_user_profile', array( $this, 'action_edit_user_profile' ) );
Erick Hitter's avatar
Erick Hitter committed
101
		add_action( 'personal_options_update', array( $this, 'action_personal_options_update' ) );
102
		add_action( 'edit_user_profile_update', array( $this, 'action_edit_user_profile_update' ) );
103
104
105
106

		// Authentication
		add_action( 'login_form', array( $this, 'action_login_form' ), 50 );
		add_filter( 'authenticate', array( $this, 'action_authenticate' ), 9999, 2 );
Erick Hitter's avatar
Erick Hitter committed
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
	/**
	 *
	 */
	protected function register_settings_fields() {
		$this->settings_fields = array(
			 array(
				'name'      => 'api_key_production',
				'label'     => __( 'Production API Key', 'authy_wp' ),
				'type'      => 'text',
				'sanitizer' => 'alphanumeric'
			),
			array(
				'name'      => 'api_key_development',
				'label'     => __( 'Development API Key', 'authy_wp' ),
				'type'      => 'text',
				'sanitizer' => 'alphanumeric'
			)
		);
	}

	/**
	 *
	 */
	protected function prepare_api() {
		$endpoints = array(
			'production'  => 'https://api.authy.com',
			'development' => 'http://sandbox-api.authy.com'
		);

138
		$this->environment = $this->get_setting( 'environment' );
139

140
		$api_key = $this->get_setting( 'api_key_' . $this->environment );
141

142
		if ( $api_key && isset( $endpoints[ $this->environment ] ) ) {
143
			$this->api_key = $api_key;
144
			$this->api_endpoint = $endpoints[ $this->environment ];
145
		}
Erick Hitter's avatar
Erick Hitter committed
146
147

		$this->api = Authy_WP_API::instance( $this->api_key, $this->api_endpoint );
148
149
	}

Erick Hitter's avatar
Erick Hitter committed
150
151
152
153
	/**
	 * COMMON PLUGIN ELEMENTS
	 */

Erick Hitter's avatar
Erick Hitter committed
154
155
156
157
	/**
	 *
	 */
	public function action_admin_init() {
158
159
		register_setting( $this->settings_page, $this->settings_key, array( $this, 'validate_plugin_settings' ) );
		add_settings_section( 'default', '', array( $this, 'register_settings_page_sections' ), $this->settings_page );
Erick Hitter's avatar
Erick Hitter committed
160
161
	}

Erick Hitter's avatar
Erick Hitter committed
162
163
164
165
	/**
	 *
	 */
	public function action_admin_menu() {
Erick Hitter's avatar
Erick Hitter committed
166
		add_options_page( 'Authy for WP', 'Authy for WP', 'manage_options', $this->settings_page, array( $this, 'plugin_settings_page' ) );
Erick Hitter's avatar
Erick Hitter committed
167
168
	}

169
170
171
172
173
174
175
176
177
178
179
	/**
	 *
	 */
	public function get_setting( $key ) {
		$value = false;

		if ( is_null( $this->settings ) || ! is_array( $this->settings ) ) {
			$this->settings = get_option( $this->settings_key );
			$this->settings = wp_parse_args( $this->settings, array(
				'api_key_production'  => '',
				'api_key_development' => '',
180
				'environment'         => apply_filters( 'authy_wp_environment', 'production' )
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
222
			) );
		}

		if ( isset( $this->settings[ $key ] ) )
			$value = $this->settings[ $key ];

		return $value;
	}

	/**
	 * GENERAL OPTIONS PAGE
	 */

	/**
	 *
	 */
	public function register_settings_page_sections() {
		foreach ( $this->settings_fields as $args ) {
			$args = wp_parse_args( $args, $this->settings_field_defaults );

			add_settings_field( $args['name'], $args['label'], array( $this, 'form_field_' . $args['type'] ), $this->settings_page, $args['section'], $args );
		}
	}

	/**
	 *
	 */
	public function form_field_text( $args ) {
		$args = wp_parse_args( $args, $this->settings_field_defaults );

		$name = esc_attr( $args['name'] );
		if ( empty( $name ) )
			return;

		if ( is_null( $args['class'] ) )
			$args['class'] = 'regular-text';

		$value = $this->get_setting( $args['name'] );

		?><input type="text" name="<?php echo esc_attr( $this->settings_key ); ?>[<?php echo $name; ?>]" class="<?php echo esc_attr( $args['class'] ); ?>" id="field-<?php echo $name; ?>" value="<?php echo esc_attr( $value ); ?>" /><?php
	}

Erick Hitter's avatar
Erick Hitter committed
223
224
225
226
	/**
	 *
	 */
	public function plugin_settings_page() {
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
		?>
		<div class="wrap">
			<?php screen_icon(); ?>
			<h2><?php echo esc_html( get_admin_page_title() ); ?></h2>

			<form action="options.php" method="post">

				<?php settings_fields( $this->settings_page ); ?>

				<?php do_settings_sections( $this->settings_page ); ?>

				<?php submit_button(); ?>
			</form>
		</div>
		<?php
Erick Hitter's avatar
Erick Hitter committed
242
	}
Erick Hitter's avatar
Erick Hitter committed
243
244
245
246
247

	/**
	 *
	 */
	public function validate_plugin_settings( $settings ) {
248
249
		check_admin_referer( $this->settings_page . '-options' );

Erick Hitter's avatar
Erick Hitter committed
250
251
		$settings_validated = array();

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
		foreach ( $this->settings_fields as $field ) {
			$field = wp_parse_args( $field, $this->settings_field_defaults );

			if ( ! isset( $settings[ $field['name'] ] ) )
				continue;

			switch ( $field['type'] ) {
				case 'text' :
						switch ( $field['sanitizer'] ) {
							case 'alphanumeric' :
								$value = preg_replace( '#[^a-z0-9]#i', '', $settings[ $field['name' ] ] );
								break;

							default:
							case 'sanitize_text_field' :
								$value = sanitize_text_field( $settings[ $field['name'] ] );
								break;
						}
					break;

				default:
					$value = sanitize_text_field( $settings[ $field['name'] ] );
					break;
			}

			if ( isset( $value ) && ! empty( $value ) )
				$settings_validated[ $field['name'] ] = $value;
		}

Erick Hitter's avatar
Erick Hitter committed
281
282
283
		return $settings_validated;
	}

284
285
286
287
	/**
	 * USER SETTINGS PAGE
	 */

Erick Hitter's avatar
Erick Hitter committed
288
289
290
	/**
	 *
	 */
Erick Hitter's avatar
Erick Hitter committed
291
292
293
294
295
296
297
298
	public function action_show_user_profile() {
		$meta = get_user_meta( get_current_user_id(), $this->users_key, true );
		$meta = wp_parse_args( $meta, $this->user_defaults );
	?>
		<h3>Authy Two-factor Authentication</h3>

		<table class="form-table">
			<tr>
299
				<th><label for="phone">Mobile number</label></th>
Erick Hitter's avatar
Erick Hitter committed
300
301
302
303
304
305
				<td>
					<input type="tel" name="<?php echo esc_attr( $this->users_key ); ?>[phone]" value="<?php echo esc_attr( $meta['phone'] ); ?>" />
				</td>
			</tr>

			<tr>
306
				<th><label for="phone">Country code</label></th>
Erick Hitter's avatar
Erick Hitter committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
				<td>
					<input type="text" name="<?php echo esc_attr( $this->users_key ); ?>[country_code]" value="<?php echo esc_attr( $meta['country_code'] ); ?>" />
				</td>
			</tr>
		</table>

		<input type="hidden" name="<?php echo esc_attr( $this->users_key ); ?>[authy_id]" value="<?php echo esc_attr( $meta['authy_id'] ); ?>" />
		<?php wp_nonce_field( $this->users_key . 'edit_own', $this->users_key . '[nonce]' ); ?>
	<?php
	}

	/**
	 *
	 */
	public function action_personal_options_update( $user_id ) {
		check_admin_referer( 'update-user_' . $user_id );

		// Check if we have data to work with
		$authy_data = isset( $_POST[ $this->users_key ] ) ? $_POST[ $this->users_key ] : false;

		// Parse for nonce and API existence
		if ( is_array( $authy_data ) && array_key_exists( 'nonce', $authy_data ) && wp_verify_nonce( $authy_data['nonce'], $this->users_key . 'edit_own' ) ) {
			// Email address
			$userdata = get_userdata( $user_id );
			if ( is_object( $userdata ) && ! is_wp_error( $userdata ) )
				$email = $userdata->data->user_email;
			else
				$email = null;

			// Phone number
			$phone = preg_replace( '#[^\d]#', '', $authy_data['phone'] );
			$country_code = preg_replace( '#[^\d\+]#', '', $authy_data['country_code'] );

			// Process information with Authy
			$this->set_authy_data( $user_id, $email, $phone, $country_code );
		}
	}

	/**
	 *
	 */
	public function set_authy_data( $user_id, $email, $phone, $country_code ) {
		// Retrieve user's existing Authy ID, or get one from Authy
		if ( $this->user_has_authy_id( $user_id ) ) {
			$authy_id = $this->get_user_authy_id( $user_id );
		} else {
			// Request an Authy ID with given user information
			$authy_id = (int) $this->api->get_id( $email, $phone, $country_code );

			if ( ! $authy_id )
				unset( $authy_id );
		}

		// Record Authy data, or clear out if empty
		$data_sanitized = array(
			'email'        => $email,
			'phone'        => $phone,
			'country_code' => $country_code
		);

		if ( isset( $authy_id ) )
			$data_sanitized['authy_id'] = $authy_id;

		$data_sanitized = wp_parse_args( $data_sanitized, $this->user_defaults );

		if ( empty( $data_sanitized ) )
			delete_user_meta( $user_id, $this->users_key );
		else
			update_user_meta( $user_id, $this->users_key, $data_sanitized );
	}

	/**
	 * Check if a given user has an Authy ID set
	 *
	 * @param int $user_id
	 * @uses this::get_user_authy_id
	 * @return bool
	 */
	protected function user_has_authy_id( $user_id ) {
		return (bool) $this->get_user_authy_id( $user_id );
	}

	/**
	 * Retrieve a given user's Authy ID
	 *
	 * @param int $user_id
	 * @uses get_user_meta
	 * @return int|bool
	 */
	protected function get_user_authy_id( $user_id ) {
		$data = get_user_meta( $user_id, $this->users_key, true );

		if ( is_array( $data ) && array_key_exists( 'authy_id', $data ) )
			return (int) $data['authy_id'];

		return false;
	}

	/**
	 *
	 */
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
	public function action_edit_user_profile( $user ) {
		if ( current_user_can( 'create_users' ) ) {
		?>
			<h3>Authy Two-factor Authentication</h3>

			<table class="form-table">
				<?php if ( $this->user_has_authy_id( $user->ID ) ) :
					$meta = get_user_meta( get_current_user_id(), $this->users_key, true );
					$meta = wp_parse_args( $meta, $this->user_defaults );

					$name = esc_attr( $this->users_key );
				?>
				<tr>
					<th><label for="<?php echo $name; ?>">Disable user's Authy connection?</label></th>
					<td>
						<input type="checkbox" id="<?php echo $name; ?>" name="<?php echo $name; ?>" value="1" />
						<label for="<?php echo $name; ?>">Yes, force user to reset the Authy connection</label>
					</td>
				</tr>
				<?php else : ?>
				<tr>
					<th>This user has not enabled Authy.</th>
					<td></td>
				</tr>
				<?php endif; ?>
			</table>
		<?php

			wp_nonce_field( $this->users_key . '_disable', "_{$this->users_key}_wpnonce" );
		}
	}

	/**
	 *
	 */
	public function action_edit_user_profile_update( $user_id ) {
		if ( isset( $_POST["_{$this->users_key}_wpnonce"] ) && check_admin_referer( $this->users_key . '_disable', "_{$this->users_key}_wpnonce" ) ) {
			if ( isset( $_POST[ $this->users_key ] ) )
				delete_user_meta( $user_id, $this->users_key );
		}
Erick Hitter's avatar
Erick Hitter committed
448
	}
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493

	/**
	 *
	 */
	public function action_login_form() {
		?>
		<p>
			<label for="authy_token">Authy Token<br>
			<input type="text" name="authy_token" id="authy_token" class="input" value="" size="20"></label>
		</p>
		<?php
	}

	/**
	 *
	 */
	public function action_authenticate( $user, $username ) {
		// If we don't have a username yet, or the method isn't supported, stop.
		if ( empty( $username ) || ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) || ( defined( 'APP_REQUEST' ) && APP_REQUEST ) )
			return $user;

		// Don't bother if WP can't provide a user object.
		if ( ! is_object( $user ) || ! property_exists( $user, 'ID' ) )
			return $user;

		// User must opt in.
		if ( ! $this->user_has_authy_id( $user->ID ) )
			return $user;

		// If a user has opted in, he/she must provide a token
		if ( ! isset( $_POST['authy_token'] ) || empty( $_POST['authy_token'] ) )
			return new WP_Error( 'authentication_failed', sprintf( __('<strong>ERROR</strong>: To log in as <strong>%s</strong>, you must provide an Authy token.'), $username ) );

		// Check the specified token
		$authy_id = $this->get_user_authy_id( $user->ID );
		$authy_token = preg_replace( '#[^\d]#', '', $_POST['authy_token'] );
		$api_check = $this->api->check_token( $authy_id, $authy_token );

		if ( false === $api_check )
			return null;
		elseif ( is_string( $api_check ) )
			return new WP_Error( 'authentication_failed', __('<strong>ERROR</strong>: ' . $api_check ) );

		return $user;
	}
Erick Hitter's avatar
Erick Hitter committed
494
495
496
}

Authy_WP::instance();