-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfreemius-wordpress-sso.php
457 lines (382 loc) · 14.5 KB
/
freemius-wordpress-sso.php
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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
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
448
449
450
451
452
453
454
455
456
457
<?php
/**
* Plugin Name: Freemius SSO (Single Sign-On)
* Plugin URI: https://freemius.com/
* Description: SSO for Freemius powered shops.
* Version: 1.0.0
* Author: Freemius
* Author URI: https://freemius.com
* License: MIT
*/
/**
* @package Freemius SSO
* @copyright Copyright (c) 2018, Freemius, Inc.
* @license https://opensource.org/licenses/mit MIT License
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_SSO {
#region Properties
/**
* @var number
*/
private $_store_id;
/**
* @var number
*/
private $_developer_id;
/**
* @var string
*/
private $_developer_secret_key;
/**
* @var bool
*/
private $_use_localhost_api;
#endregion
#region Singleton
/**
* @var FS_SSO
*/
private static $instance;
/**
* @return FS_SSO
*/
static function instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
#endregion
private function __construct() {
add_filter( 'authenticate', array( &$this, 'authenticate' ), 30, 3 );
// Clean up the stored access token upon logout.
add_action( 'clear_auth_cookie', array( &$this, 'clear_access_token' ), 30, 3 );
}
/**
* @param number $store_id
* @param number $developer_id
* @param string $developer_secret_key
* @param bool $use_localhost_api
*/
public function init(
$store_id,
$developer_id,
$developer_secret_key,
$use_localhost_api = false
) {
$this->_store_id = $store_id;
$this->_developer_id = $developer_id;
$this->_developer_secret_key = $developer_secret_key;
$this->_use_localhost_api = $use_localhost_api;
}
/**
* This logic assumes that if a user exists in WP, there's a matching user (based on email) in Freemius.
*
* @param WP_User|null|WP_Error $user
* @param string $username Username or email.
* @param string $password Plain text password.
*
* @return WP_User|null|WP_Error
*/
public function authenticate( $user, $username, $password ) {
$is_login_by_email = strpos( $username, '@' );
$wp_user_found = ( $user instanceof WP_User );
/**
* If there's no matching user in WP and the login is by a username and not an email address, there's no way for us to fetch an access token for the user.
*/
if ( ! $wp_user_found &&
! $is_login_by_email
) {
return $user;
}
if ( is_wp_error( $user ) &&
! in_array( $user->get_error_code(), array(
'authentication_failed',
'invalid_email',
'invalid_password',
'incorrect_password',
) )
) {
return $user;
}
$email = $is_login_by_email ?
$username :
$user->user_email;
/**
*
*/
$fs_user_token = null;
$fs_user_id = null;
$fetch_access_token = true;
if ( $wp_user_found ) {
$fs_user_id = get_user_meta( $user->ID, 'fs_user_id', true );
if ( is_numeric( $fs_user_id ) ) {
$fs_user_token = get_user_meta( $user->ID, 'fs_token', true );
if ( ! empty( $fs_user_token ) ) {
// Validate access token didn't yet to expire.
if ( $fs_user_token->expires > time() ) {
// No need to get a new access token for now, we can use the cached token.
$fetch_access_token = false;
}
}
}
}
if ( $fetch_access_token ) {
// Fetch user's info and access token from Freemius.
$result = $this->fetch_user_access_token(
$email,
( $wp_user_found ? '' : $password )
);
if ( is_wp_error( $result ) ) {
return $user;
}
$result = json_decode( $result['body'] );
if ( isset( $result->error ) ) {
if ( $wp_user_found ) {
return $user;
} else {
return new WP_Error( $result->error->code, __( '<strong>ERROR</strong>: ' . $result->error->message ) );
}
}
$fs_user = $result->user_token->person;
$fs_user_id = $fs_user->id;
$fs_user_token = $result->user_token->token;
if ( ! $wp_user_found ) {
// Check if there's a user with a matching email address.
$user_by_email = get_user_by( 'email', $email );
if ( is_object( $user_by_email ) ) {
$user = $user_by_email;
} else {
/**
* No user in WP with a matching email address. Therefore, create the user.
*/
$username = strtolower( $fs_user->first . ( empty( $fs_user->last ) ? '' : '.' . $fs_user->last ) );
if ( empty( $username ) ) {
$username = substr( $fs_user->email, 0, strpos( $fs_user->email, '@' ) );
}
$username = $this->generate_unique_username( $username );
$user_id = wp_create_user( $username, $password, $email );
if ( is_wp_error( $user_id ) ) {
return $user;
}
$user = get_user_by( 'ID', $user_id );
do_action( 'fs_sso_after_user_creation', $user );
}
}
/**
* Store the token and user ID locally.
*/
update_user_meta( $user->ID, 'fs_token', $fs_user_token );
update_user_meta( $user->ID, 'fs_user_id', $fs_user_id );
}
if ( $user instanceof WP_User ) {
$has_any_active_licenses = 'no';
if ( $this->get_freemius_has_any_license( $user->ID ) ) {
$has_any_licenses = 'yes';
} else {
$has_any_licenses = 'no';
$result = $this->fetch_user_store_licenses( $fs_user_id, $fs_user_token->access );
if ( ! is_wp_error( $result ) ) {
$result = json_decode( $result['body'] );
if ( is_object( $result ) &&
! isset( $result->error ) &&
! empty( $result->licenses )
) {
$has_any_licenses = 'yes';
/**
* Check if license is active to save an API call.
*/
$license = $result->licenses[0];
if ( false === $license->is_cancelled &&
! $this->has_license_expired( $license )
) {
$has_any_active_licenses = 'yes';
}
}
}
update_user_meta( $user->ID, 'fs_has_licenses', $has_any_licenses );
}
if ('yes' !== $has_any_active_licenses && 'yes' === $has_any_licenses) {
$result = $this->fetch_user_store_licenses(
$fs_user_id,
$fs_user_token->access,
'active'
);
if ( ! is_wp_error( $result ) ) {
$result = json_decode( $result['body'] );
if ( is_object( $result ) &&
! isset( $result->error ) &&
! empty( $result->licenses )
) {
$has_any_active_licenses = 'yes';
}
}
}
update_user_meta( $user->ID, 'fs_has_active_licenses', $has_any_active_licenses );
}
do_action( 'fs_sso_after_successful_login', $user );
return $user;
}
/**
* Clean up the stored user access token.
*/
public function clear_access_token() {
delete_user_meta( get_current_user_id(), 'fs_token' );
}
/**
* Current logged in user's Freemius user ID.
*
* @return number
*/
public function get_freemius_user_id() {
return get_user_meta( get_current_user_id(), 'fs_user_id', true );
}
/**
* Current logged in user's Freemius access token.
*
* @return object
*/
public function get_freemius_access_token() {
return get_user_meta( get_current_user_id(), 'fs_token', true );
}
/**
* Is currently logged in user has any store licenses on Freemius.
*
* @param int|null $user_id
*
* @return bool
*/
public function get_freemius_has_any_license( $user_id = null ) {
if (is_null( $user_id )) {
$user_id = get_current_user_id();
}
return ( 'yes' === get_user_meta( $user_id, 'fs_has_licenses', 'no' ) );
}
/**
* Is currently logged in user has any store licenses on Freemius.
*
* @param int|null $user_id
*
* @return bool
*/
public function get_freemius_has_any_active_license( $user_id = null ) {
if (is_null( $user_id )) {
$user_id = get_current_user_id();
}
return ( 'yes' === get_user_meta( $user_id, 'fs_has_active_licenses', 'no' ) );
}
#region Helper Methods
/**
* @param string $email
* @param string $password
*
* @return array|WP_Error
*/
private function fetch_user_access_token( $email, $password = '' ) {
$api_root = $this->get_api_root();
// Fetch user's info and access token from Freemius.
return wp_remote_post(
"{$api_root}/v1/users/login.json",
array(
'method' => 'POST',
'blocking' => true,
'body' => array(
'email' => $email,
'password' => $password,
'store_id' => $this->_store_id,
'developer_id' => $this->_developer_id,
'developer_secret_key' => $this->_developer_secret_key,
)
)
);
}
/**
* @param number $fs_user_id
* @param string $access_token
* @param string $type
* @param int $count
*
* @return array|\WP_Error
*/
private function fetch_user_store_licenses( $fs_user_id, $access_token, $type = 'all', $count = 1 ) {
$api_root = $this->get_api_root();
// Fetch user's info and access token from Freemius.
return wp_remote_post(
"{$api_root}/v1/users/{$fs_user_id}/licenses.json?" . http_build_query( array(
'count' => $count,
'store_id' => $this->_store_id,
'type' => $type,
'authorization' => "FSA {$fs_user_id}:$access_token",
), null, '&', PHP_QUERY_RFC3986 ),
array(
'method' => 'GET',
'blocking' => true,
)
);
}
/**
* @return string
*/
private function get_api_root() {
return $this->_use_localhost_api ?
'http://api.freemius-local.com:8080' :
'https://fast-api.freemius.com';
}
/**
* @param string $base_username
*
* @return string
*/
private function generate_unique_username( $base_username ) {
// Sanitize.
$base_username = sanitize_user( $base_username );
$numeric_suffix = 0;
do {
$username = ( 0 == $numeric_suffix ) ?
$base_username :
sprintf( '%s%s', $base_username, $numeric_suffix );
$numeric_suffix ++;
} while ( username_exists( $username ) );
return $username;
}
/**
* @param object $license
*
* @return bool
*/
private function has_license_expired( $license ) {
if ( is_null( $license->expiration ) ) {
// Lifetime license.
return false;
}
return ( time() >= $this->get_timestamp_from_datetime( $license->expiration ) );
}
/**
* @param string $datetime
*
* @return int
*/
private function get_timestamp_from_datetime( $datetime ) {
$timezone = date_default_timezone_get();
if ( 'UTC' !== $timezone ) {
// Temporary change time zone.
date_default_timezone_set( 'UTC' );
}
$timestamp = date( 'Y-m-d H:i:s', strtotime( $datetime ) );
if ( 'UTC' !== $timezone ) {
// Revert timezone.
date_default_timezone_set( $timezone );
}
return $timestamp;
}
#endregion
}
FS_SSO::instance()->init(
'<STORE_ID>',
'<DEVELOPER_ID>',
'<DEVELOPER_SECRET_KEY>'
);