Repository navigation
Expand file tree
/
Copy pathbasic-auth.php
More file actions
87 lines (72 loc) · 2.13 KB
/
Copy pathbasic-auth.php
File metadata and controls
87 lines (72 loc) · 2.13 KB
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
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class JSON_Basic_Auth {
private static $instance;
private $auth_error = null;
/**
* Singleton instance.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Hook into WordPress filters.
*/
public function init() {
add_filter( 'determine_current_user', [ $this, 'handle_basic_auth' ], 20 );
add_filter( 'rest_authentication_errors', [ $this, 'handle_auth_errors' ] );
}
/**
* Handle Basic Authentication.
*
* @param mixed $user
* @return mixed
*/
public function handle_basic_auth( $user ) {
// Don't authenticate twice.
if ( ! empty( $user ) ) {
return $user;
}
// Check that we're trying to authenticate.
if ( ! isset( $_SERVER['PHP_AUTH_USER'] ) ) {
return $user;
}
$username = sanitize_text_field( $_SERVER['PHP_AUTH_USER'] );
$password = sanitize_text_field( $_SERVER['PHP_AUTH_PW'] );
/**
* Prevent infinite recursion in multi-site by temporarily removing the filter.
*/
remove_filter( 'determine_current_user', [ $this, 'handle_basic_auth' ], 20 );
$user = wp_authenticate( $username, $password );
add_filter( 'determine_current_user', [ $this, 'handle_basic_auth' ], 20 );
if ( is_wp_error( $user ) ) {
$this->auth_error = $user;
return null;
}
$this->auth_error = true;
return $user->ID;
}
/**
* Handle authentication errors.
*
* @param mixed $error
* @return mixed
*/
public function handle_auth_errors( $error ) {
// Passthrough other errors.
if ( ! empty( $error ) ) {
return $error;
}
return $this->auth_error;
}
}
// Initialize the class and hook into WordPress.
add_action( 'init', function () {
$auth = JSON_Basic_Auth::get_instance();
$auth->init();
} );