Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
14.56% |
23 / 158 |
|
36.36% |
4 / 11 |
CRAP | |
0.00% |
0 / 1 |
API | |
14.56% |
23 / 158 |
|
36.36% |
4 / 11 |
1424.93 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
add_autologin_to_message | |
0.00% |
0 / 11 |
|
0.00% |
0 / 1 |
6 | |||
get_wp_user | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
90 | |||
add_autologin_to_url | |
0.00% |
0 / 22 |
|
0.00% |
0 / 1 |
110 | |||
generate_code | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
generate_password | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
verify_autologin_password | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
delete_expired_codes | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
should_allow_login_attempt | |
0.00% |
0 / 40 |
|
0.00% |
0 / 1 |
20 | |||
get_ip_address | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
42 | |||
send_magic_link | |
0.00% |
0 / 39 |
|
0.00% |
0 / 1 |
42 |
1 | <?php |
2 | /** |
3 | * The core plugin functionality |
4 | * |
5 | * Contains functions relied on by other parts of the plugin and public for other plugin developers. |
6 | * |
7 | * @link https://BrianHenry.ie |
8 | * @since 1.0.0 |
9 | * |
10 | * @package brianhenryie/bh-wp-autologin-urls |
11 | */ |
12 | |
13 | namespace BrianHenryIE\WP_Autologin_URLs\API; |
14 | |
15 | use BrianHenryIE\WP_Autologin_URLs\API\Data_Stores\Transient_Data_Store; |
16 | use BrianHenryIE\WP_Autologin_URLs\API\Integrations\Autologin_URLs; |
17 | use BrianHenryIE\WP_Autologin_URLs\API_Interface; |
18 | use BrianHenryIE\WP_Autologin_URLs\RateLimit\Rate; |
19 | use BrianHenryIE\WP_Autologin_URLs\Settings_Interface; |
20 | use BrianHenryIE\WP_Autologin_URLs\WP_Includes\Login; |
21 | use BrianHenryIE\WP_Autologin_URLs\WP_Rate_Limiter\WordPress_Rate_Limiter; |
22 | use DateTimeImmutable; |
23 | use DateTimeInterface; |
24 | use DateTimeZone; |
25 | use Psr\Log\LoggerAwareTrait; |
26 | use Psr\Log\LoggerInterface; |
27 | use WC_Geolocation; |
28 | use WP_User; |
29 | |
30 | /** |
31 | * The core plugin functionality. |
32 | */ |
33 | class API implements API_Interface { |
34 | |
35 | use LoggerAwareTrait; |
36 | |
37 | /** |
38 | * Plugin settings as [maybe] configured by the user. |
39 | * |
40 | * @var Settings_Interface $settings The plugin settings from the database. |
41 | */ |
42 | protected $settings; |
43 | |
44 | /** |
45 | * Briefly caches generated codes to save regenerating multiple codes per email. |
46 | * |
47 | * @var array<string,string> Dictionary ["user_id~seconds_valid" : code] |
48 | */ |
49 | protected $cache = array(); |
50 | |
51 | /** |
52 | * Class for saving, retrieving and expiring passwords. |
53 | * |
54 | * @var Data_Store_Interface |
55 | */ |
56 | protected Data_Store_Interface $data_store; |
57 | |
58 | /** |
59 | * API constructor. |
60 | * |
61 | * @param Settings_Interface $settings The plugin settings from the database. |
62 | * @param LoggerInterface $logger The logger instance. |
63 | * @param Data_Store_Interface|null $data_store Class for saving, retrieving and expiring passwords. |
64 | */ |
65 | public function __construct( Settings_Interface $settings, LoggerInterface $logger, Data_Store_Interface $data_store = null ) { |
66 | |
67 | $this->setLogger( $logger ); |
68 | $this->data_store = $data_store ?? new Transient_Data_Store( $logger ); |
69 | |
70 | $this->settings = $settings; |
71 | } |
72 | |
73 | /** |
74 | * Adds autologin codes to every url for this site in a string. |
75 | * |
76 | * @param string $message A string to update the URLs in. |
77 | * @param int|string|WP_User $user A user id, email, username or user object. |
78 | * @param int|null $expires_in Number of seconds the password should work for. |
79 | * |
80 | * @return string |
81 | */ |
82 | public function add_autologin_to_message( string $message, $user, ?int $expires_in = null ): string { |
83 | |
84 | $replace_with = function ( $matches ) use ( $user, $expires_in ) { |
85 | |
86 | $url = $matches[0]; |
87 | |
88 | $login_url = $this->add_autologin_to_url( $url, $user, $expires_in ); |
89 | |
90 | return $login_url; |
91 | }; |
92 | |
93 | $escaped_site_url = preg_quote( get_site_url(), '/' ); |
94 | |
95 | $updated = preg_replace_callback( '/[\s\"](' . $escaped_site_url . '[^\s\"<]*)/m', $replace_with, $message ); |
96 | |
97 | if ( is_null( $updated ) ) { |
98 | $this->logger->warning( 'Failed to update message', array( 'message' => $message ) ); |
99 | } else { |
100 | $message = $updated; |
101 | } |
102 | |
103 | return $message; |
104 | } |
105 | |
106 | /** |
107 | * Get the actual WP_User object from the id/username/email. Null when not found. |
108 | * |
109 | * @param null|int|string|WP_User $user A valid user id, email, login or user object. |
110 | */ |
111 | public function get_wp_user( $user ): ?WP_User { |
112 | |
113 | if ( $user instanceof WP_User ) { |
114 | return $user; |
115 | } |
116 | |
117 | if ( is_int( $user ) ) { |
118 | |
119 | $user = get_user_by( 'ID', $user ); |
120 | |
121 | } elseif ( is_numeric( $user ) && 0 !== intval( $user ) ) { |
122 | |
123 | // When string '123' is passed as the user id, convert it to an int. |
124 | $user = absint( $user ); |
125 | $user = get_user_by( 'ID', $user ); |
126 | |
127 | } elseif ( is_string( $user ) && is_email( $user ) ) { |
128 | |
129 | // When a string which is an email is passed. |
130 | $user = get_user_by( 'email', $user ); |
131 | |
132 | } elseif ( is_string( $user ) ) { |
133 | |
134 | // When any other string is passed, assume it is a username. |
135 | $user = get_user_by( 'login', $user ); |
136 | } |
137 | |
138 | return $user instanceof WP_User ? $user : null; |
139 | } |
140 | |
141 | |
142 | /** |
143 | * Public function for other plugins to use on links. |
144 | * |
145 | * @param string $url The url to append the autologin code to. This must be a link to this site. |
146 | * @param null|int|string|WP_User $user A valid user id, email, login or user object. |
147 | * @param ?int $expires_in The number of seconds the code will work for. |
148 | * |
149 | * @return string |
150 | */ |
151 | public function add_autologin_to_url( string $url, $user, ?int $expires_in = null ): string { |
152 | |
153 | if ( ! stristr( $url, get_site_url() ) ) { |
154 | return $url; |
155 | } |
156 | |
157 | /** |
158 | * If The Newsletter Plugin tracking is already added to the link, use the integration to handle logging in, |
159 | * rather than adding an autologin code. |
160 | */ |
161 | if ( stristr( $url, 'nltr=' ) ) { |
162 | return $url; |
163 | } |
164 | |
165 | $user = $this->get_wp_user( $user ); |
166 | |
167 | if ( is_null( $user ) ) { |
168 | return $url; |
169 | } |
170 | |
171 | // Although this method could return null, the checks to prevent that have already |
172 | // taken place in this method. |
173 | $autologin_code = $this->generate_code( $user, $expires_in ); |
174 | |
175 | /** |
176 | * The typical `wp-login.php` can be configured to be a different URL. |
177 | * |
178 | * @var array{host:string,path:string} $parsed_wp_login_url |
179 | */ |
180 | $parsed_wp_login_url = wp_parse_url( wp_login_url() ); |
181 | $parsed_url = wp_parse_url( $url ); |
182 | |
183 | // Redirecting to wp-login.php always send the user to a login screen, defeating the point of this plugin. |
184 | while ( isset( $parsed_url['host'], $parsed_url['path'] ) && $parsed_url['host'] === $parsed_wp_login_url['host'] && $parsed_url['path'] === $parsed_wp_login_url['path'] ) { |
185 | |
186 | if ( isset( $parsed_url['query'] ) ) { |
187 | parse_str( $parsed_url['query'], $query_get ); |
188 | |
189 | if ( isset( $query_get['redirect_to'] ) ) { |
190 | $url = $query_get['redirect_to']; |
191 | } else { |
192 | $url = get_site_url(); |
193 | } |
194 | } else { |
195 | // There must be a neater way of assigning $url but today I want to work on something else. |
196 | $url = get_site_url(); |
197 | } |
198 | |
199 | $parsed_url = wp_parse_url( $url ); |
200 | } |
201 | |
202 | if ( ! $this->settings->get_should_use_wp_login() ) { |
203 | $user_link = add_query_arg( Autologin_URLs::QUERYSTRING_PARAMETER_NAME, $autologin_code, $url ); |
204 | } else { |
205 | // TODO: If it is already a wp-login.php URL, deconstruct to avoid a Russian doll situation. |
206 | $user_link = add_query_arg( Autologin_URLs::QUERYSTRING_PARAMETER_NAME, $autologin_code, wp_login_url( $url ) ); |
207 | } |
208 | |
209 | return $user_link; |
210 | } |
211 | |
212 | /** |
213 | * Returns a code that can be verified, containing the user id and a single-use password separated |
214 | * by ~, e.g. 11~mdBpC879oJSs. |
215 | * |
216 | * If the user does not exist, null is returned. |
217 | * |
218 | * @param ?WP_User $user WordPress user. |
219 | * @param ?int $seconds_valid Number of seconds after which the password will expire. |
220 | * |
221 | * @return ?string |
222 | */ |
223 | public function generate_code( $user, ?int $seconds_valid ): ?string { |
224 | |
225 | if ( is_null( $user ) || ! ( $user instanceof WP_User ) ) { |
226 | return null; |
227 | } |
228 | |
229 | if ( is_null( $seconds_valid ) ) { |
230 | $seconds_valid = $this->settings->get_expiry_age(); |
231 | } |
232 | |
233 | $user_id = $user->ID; |
234 | |
235 | if ( array_key_exists( "$user_id~$seconds_valid", $this->cache ) ) { |
236 | return $this->cache[ "$user_id~$seconds_valid" ]; |
237 | } |
238 | |
239 | $password = $this->generate_password( $user_id, $seconds_valid ); |
240 | |
241 | $code = "$user_id~$password"; |
242 | |
243 | $this->cache[ "$user_id~$seconds_valid" ] = $code; |
244 | |
245 | return $code; |
246 | } |
247 | |
248 | /** |
249 | * Generates a password that can be used in autologin links, never stored, expires after $seconds_valid. |
250 | * |
251 | * @param int $user_id WordPress user id. |
252 | * @param int $seconds_valid Number of seconds after which the password will expire. |
253 | * |
254 | * @return string password |
255 | */ |
256 | protected function generate_password( int $user_id, int $seconds_valid ): string { |
257 | |
258 | // Generate a password using only alphanumerics (to avoid urlencoding worries). |
259 | // Length of 12 was chosen arbitrarily. |
260 | $password = wp_generate_password( 12, false ); |
261 | |
262 | $this->data_store->save( $user_id, $password, $seconds_valid ); |
263 | |
264 | return $password; |
265 | } |
266 | |
267 | /** |
268 | * Verifies the autologin code. |
269 | * The datastore deletes codes when found to prevent reuse. |
270 | * |
271 | * @param int $user_id WordPress user id. |
272 | * @param string $password Plugin generated password to verify. |
273 | * |
274 | * @return bool |
275 | */ |
276 | public function verify_autologin_password( int $user_id, string $password ): bool { |
277 | /** |
278 | * Filter to enable reuse of autologin codes. |
279 | * |
280 | * The codes continue to be deleted at their expiry date, but returning false here allows each code to be used |
281 | * an unlimited number of times until then. |
282 | * |
283 | * @param bool $delete Indicate if the code should be deleted after use. |
284 | * @param int $user_id The id of the user we are attempting to log in. |
285 | */ |
286 | $delete = apply_filters( 'bh_wp_autologin_urls_should_delete_code_after_use', true, $user_id ); |
287 | |
288 | $saved_details = $this->data_store->get_value_for_code( $password, $delete ); |
289 | |
290 | if ( null === $saved_details ) { |
291 | return false; |
292 | } |
293 | |
294 | $provided_details = hash( 'sha256', $user_id . $password ); |
295 | |
296 | return hash_equals( $provided_details, $saved_details ); |
297 | } |
298 | |
299 | /** |
300 | * Purge codes that are no longer valid. |
301 | * |
302 | * @param ?DateTimeInterface $before The date from which to purge old codes. |
303 | * |
304 | * @return array{deleted_count:int|null} |
305 | * @throws \Exception A DateTime exception when 'now' is used. I.e. never. |
306 | */ |
307 | public function delete_expired_codes( ?DateTimeInterface $before = null ): array { |
308 | $before = $before ?? new DateTimeImmutable( 'now', new DateTimeZone( 'UTC' ) ); |
309 | return $this->data_store->delete_expired_codes( $before ); |
310 | } |
311 | |
312 | /** |
313 | * Records each login attempt and checks if the same user/ip/querystring has been used too many times today. |
314 | * |
315 | * Transient e.g. `_transient_bh-wp-autologin-urls/bh-wp-autologin-urlsip-127.0.0.1-86400`. |
316 | * Transient e.g. `_transient_bh-wp-autologin-urls/bh-wp-autologin-urlswp_user-1-86400`. |
317 | * |
318 | * @param string $identifier An IP address or user login name to rate limit by. |
319 | */ |
320 | public function should_allow_login_attempt( string $identifier ): bool { |
321 | |
322 | $allowed_access_count = Login::MAX_BAD_LOGIN_ATTEMPTS; |
323 | $interval = Login::MAX_BAD_LOGIN_PERIOD_SECONDS; |
324 | |
325 | $rate = Rate::custom( $allowed_access_count, $interval ); |
326 | |
327 | static $rate_limiter; |
328 | |
329 | if ( empty( $rate_limiter ) ) { |
330 | $rate_limiter = new WordPress_Rate_Limiter( $rate, 'bh-wp-autologin-urls' ); |
331 | } |
332 | |
333 | try { |
334 | $status = $rate_limiter->limitSilently( $identifier ); |
335 | } catch ( \RuntimeException $e ) { |
336 | $this->logger->error( |
337 | 'Rate Limiter encountered an error when storing the access count.', |
338 | array( |
339 | 'exception' => $e, |
340 | 'identifier' => $identifier, |
341 | 'interval' => $interval, |
342 | 'allowed_access_count' => $allowed_access_count, |
343 | ) |
344 | ); |
345 | |
346 | // Play it safe and don't log them in. |
347 | return false; |
348 | } |
349 | |
350 | /** |
351 | * TODO: Log the $_REQUEST data. |
352 | */ |
353 | if ( $status->limitExceeded() ) { |
354 | |
355 | $this->logger->notice( |
356 | "{$identifier} blocked with {$status->getRemainingAttempts()} remaining attempts for rate limit {$allowed_access_count} per {$interval} seconds.", |
357 | array( |
358 | 'identifier' => $identifier, |
359 | 'interval' => $interval, |
360 | 'allowed_access_count' => $allowed_access_count, |
361 | 'status' => $status, |
362 | '_SERVER' => $_SERVER, |
363 | ) |
364 | ); |
365 | |
366 | return false; |
367 | |
368 | } else { |
369 | |
370 | $this->logger->debug( |
371 | "{$identifier} allowed with {$status->getRemainingAttempts()} remaining attempts for rate limit {$allowed_access_count} per {$interval} seconds.", |
372 | array( |
373 | 'identifier' => $identifier, |
374 | 'interval' => $interval, |
375 | 'allowed_access_count' => $allowed_access_count, |
376 | 'status' => $status, |
377 | ) |
378 | ); |
379 | } |
380 | |
381 | return true; |
382 | } |
383 | |
384 | /** |
385 | * Finds the IP address of the current request. |
386 | * |
387 | * A copy of WooCommerce's IP address logic. |
388 | * If behind Cloudflare, the Cloudflare plugin should be installed. |
389 | * |
390 | * @return ?string |
391 | */ |
392 | public function get_ip_address(): ?string { |
393 | |
394 | if ( class_exists( WC_Geolocation::class ) ) { |
395 | $ip_address = WC_Geolocation::get_ip_address(); |
396 | } elseif ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) { |
397 | $ip_address = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) ); |
398 | } elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { |
399 | $ip_address = (string) rest_is_ip_address( trim( current( preg_split( '/,/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ) ); |
400 | } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) { |
401 | $ip_address = filter_var( wp_unslash( $_SERVER['REMOTE_ADDR'] ), FILTER_VALIDATE_IP ); |
402 | } |
403 | |
404 | // Return null, not false, or the string. |
405 | return empty( $ip_address ) ? null : $ip_address; |
406 | } |
407 | |
408 | /** |
409 | * Maybe send email to the wp_user with a "magic link" to log in. |
410 | * |
411 | * TODO: Add settings options: enable/disable feature, configure subject, configure expiry time. |
412 | * |
413 | * @param string $username_or_email_address The username or email as entered by the user in the login form. |
414 | * @param ?string $url The page the user should be sent, e.g. checkout, my-account. Defaults to site URL. |
415 | * @param int $expires_in Number of seconds the link should be valid. Defaults to 15 minutes. |
416 | * |
417 | * @return array{username_or_email_address:string, expires_in:int, expires_in_friendly:string, wp_user?:WP_User, template_path?:string, success:bool, error?:bool, message?:string} |
418 | */ |
419 | public function send_magic_link( string $username_or_email_address, ?string $url = null, int $expires_in = 900 ): array { |
420 | |
421 | $url = $url ?? get_site_url(); |
422 | |
423 | $expires_in_friendly = human_time_diff( time() - $expires_in ); |
424 | |
425 | $result = array( |
426 | 'username_or_email_address' => $username_or_email_address, |
427 | 'expires_in' => $expires_in, |
428 | 'expires_in_friendly' => $expires_in_friendly, |
429 | ); |
430 | |
431 | $wp_user = get_user_by( 'login', $username_or_email_address ); |
432 | |
433 | if ( ! ( $wp_user instanceof WP_User ) ) { |
434 | |
435 | $wp_user = get_user_by( 'email', $username_or_email_address ); |
436 | |
437 | if ( ! ( $wp_user instanceof WP_User ) ) { |
438 | |
439 | // NB: Do not tell the user if the username exists. |
440 | $result['success'] = false; |
441 | |
442 | $this->logger->debug( "No WP_User found for {$username_or_email_address}", array( 'result' => $result ) ); |
443 | |
444 | return $result; |
445 | } |
446 | } |
447 | |
448 | $result['wp_user'] = $wp_user; |
449 | |
450 | $to = $wp_user->user_email; |
451 | |
452 | $subject = __( 'Sign-in Link', 'bh-wp-autologin-urls' ); |
453 | |
454 | $template = 'email/magic-link.php'; |
455 | |
456 | $template_email_magic_link = WP_PLUGIN_DIR . '/' . plugin_dir_path( $this->settings->get_plugin_basename() ) . 'templates/' . $template; |
457 | |
458 | // Check the child theme for template overrides. |
459 | if ( file_exists( get_stylesheet_directory() . $template ) ) { |
460 | $template_email_magic_link = get_stylesheet_directory() . $template; |
461 | } elseif ( file_exists( get_stylesheet_directory() . 'templates/' . $template ) ) { |
462 | $template_email_magic_link = get_stylesheet_directory() . 'templates/' . $template; |
463 | } |
464 | |
465 | $autologin_url = $this->add_autologin_to_url( $url, $wp_user, $expires_in ); |
466 | |
467 | // Add a marker for later logging use of the email. |
468 | $autologin_url = add_query_arg( array( 'magic' => 'true' ), $autologin_url ); |
469 | |
470 | /** |
471 | * Allow overriding the email template. |
472 | * |
473 | * @var string $autologin_url The URL which will log the user in. |
474 | * @var string $expires_in_friendly Human-readable form of the number of seconds until expiry. |
475 | */ |
476 | $template_email_magic_link = apply_filters( 'bh_wp_autologin_urls_magic_link_email_template', $template_email_magic_link ); |
477 | |
478 | $result['template_path'] = $template_email_magic_link; |
479 | |
480 | ob_start(); |
481 | |
482 | include $template_email_magic_link; |
483 | |
484 | // NB: Do not log the message because it contains a password! |
485 | $message = ob_get_clean(); |
486 | |
487 | $headers = array( 'Content-Type: text/html; charset=UTF-8' ); |
488 | |
489 | $mail_success = wp_mail( $to, $subject, $message, $headers ); |
490 | |
491 | $result['success'] = $mail_success; |
492 | |
493 | if ( false === $mail_success ) { |
494 | $result['error'] = true; |
495 | $this->logger->error( 'Failed sending magic login email.', array( 'result' => $result ) ); |
496 | } else { |
497 | |
498 | $result['message'] = 'If a user exists for `' . $username_or_email_address . '` an email has been sent to that user with a login link.'; |
499 | |
500 | $this->logger->info( "Magic login email sent to wp_user:{$wp_user->ID}." ); |
501 | } |
502 | |
503 | return $result; |
504 | } |
505 | } |