-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-authenticator.php
102 lines (84 loc) · 2.53 KB
/
class-authenticator.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
<?php
namespace Myrotvorets\WordPress\SecEnh;
use WildWolf\Utils\Singleton;
use WP_Error;
use WP_User;
final class Authenticator {
use Singleton;
private function __construct() {
$this->init();
}
public function init(): void {
add_filter( 'authenticate', [ $this, 'authenticate' ], 0, 2 );
add_filter( 'login_errors', [ $this, 'login_errors' ], PHP_INT_MAX );
add_filter( 'wp_login_errors', [ $this, 'wp_login_errors' ], PHP_INT_MAX );
}
/**
* @param null|WP_User|WP_Error $user WP_User if the user is authenticated.
* WP_Error or null otherwise.
* @param string $username Username or email address.
* @return null|WP_User|WP_Error
*/
public function authenticate( $user, $username ) {
if ( ! is_wp_error( $user ) ) {
$ra = Utils::get_ip();
$ua = Utils::get_ua();
$acc = Utils::get_server_var( 'HTTP_ACCEPT' );
$sua = sanitize_text_field( $ua );
if ( empty( $ra ) || empty( $ua ) || empty( $acc ) || $ua !== $sua ) {
return new WP_Error( 'failure', '<strong>Error</strong>: The credentials provided are incorrect.' );
}
}
if ( $username ) {
$is_restricted_username = Utils::is_restricted_username( (string) $username );
if ( $is_restricted_username ) {
$user = new WP_Error( 'failure', '<strong>Error</strong>: The credentials provided are incorrect.' );
}
}
return $user;
}
/**
* @param string $error Login error message.
* @return string
*/
public function login_errors( $error ): string {
global $errors;
if ( ! is_wp_error( $errors ) ) {
return (string) $error;
}
$codes = $errors->get_error_codes();
$triggers = $this->get_triggers();
/** @var int|string $code */
foreach ( $codes as $code ) {
if ( isset( $triggers[ $code ] ) ) {
$error = '<strong>Error</strong>: The credentials provided are incorrect.';
break;
}
}
return (string) $error;
}
public function wp_login_errors( WP_Error $errors ): WP_Error {
$triggers = $this->get_triggers();
$codes = $errors->get_error_codes();
$found = false;
/** @var int|string $code */
foreach ( $codes as $code ) {
if ( isset( $triggers[ $code ] ) ) {
$errors->remove( $code );
$found = true;
}
}
if ( $found ) {
$errors->add( 'failure', '<strong>Error</strong>: The credentials provided are incorrect.' );
}
return $errors;
}
private function get_triggers(): array {
return [
'invalid_username' => 1,
'invalid_email' => 1,
'incorrect_password' => 1,
'invalidcombo' => 1,
];
}
}