forked from usefulteam/jwt-auth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
class-setup.php
91 lines (77 loc) · 2.47 KB
/
class-setup.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
<?php
/**
* Setup JWT Auth.
*
* @package jwt-auth
*/
namespace JWTAuth;
/**
* Setup JWT Auth.
*/
class Setup {
private static $instance;
public $auth;
public $devices;
/**
* Constructs singleton.
*/
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Setup action & filter hooks.
*/
public function __construct() {
add_action( 'init', array( $this, 'setup_text_domain' ) );
$this->auth = new Auth();
$this->devices = new Devices();
add_action( 'rest_api_init', array( $this->auth, 'register_rest_routes' ) );
add_filter( 'rest_api_init', array( $this->auth, 'add_cors_support' ) );
add_filter( 'rest_pre_dispatch', array( $this->auth, 'rest_pre_dispatch' ), 10, 3 );
add_filter( 'determine_current_user', array( $this->auth, 'determine_current_user' ) );
if ( ! wp_next_scheduled( 'jwt_auth_purge_expired_refresh_tokens' )) {
wp_schedule_event( time(), 'weekly', 'jwt_auth_purge_expired_refresh_tokens' );
}
add_action( 'jwt_auth_purge_expired_refresh_tokens', array( $this, 'cron_purge_expired_refresh_tokens' ) );
}
/**
* Setup textdomain.
*/
public function setup_text_domain() {
load_plugin_textdomain( 'jwt-auth', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
}
/**
* Cleans expired refresh tokens from user accounts.
*/
public function cron_purge_expired_refresh_tokens() {
global $wpdb;
$now = time();
$user_ids = $wpdb->get_col( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta}
WHERE meta_key = 'jwt_auth_refresh_tokens_expires_next'
AND meta_value <= %d
", $now ) );
foreach ($user_ids as $user_id) {
$user_refresh_tokens = get_user_meta( $user_id, 'jwt_auth_refresh_tokens', true );
if ( is_array( $user_refresh_tokens ) ) {
$expires_next = 0;
foreach ( $user_refresh_tokens as $key => $device ) {
if ( $device['expires'] <= $now ) {
unset( $user_refresh_tokens[ $key ] );
} elseif ( $expires_next === 0 || $device['expires'] <= $expires_next ) {
$expires_next = $device['expires'];
}
}
if ( $user_refresh_tokens ) {
update_user_meta( $user_id, 'jwt_auth_refresh_tokens', $user_refresh_tokens );
update_user_meta( $user_id, 'jwt_auth_refresh_tokens_expires_next', $expires_next );
} else {
delete_user_meta( $user_id, 'jwt_auth_refresh_tokens' );
delete_user_meta( $user_id, 'jwt_auth_refresh_tokens_expires_next' );
}
}
}
}
}