<?php
|
namespace JVBase\managers;
|
|
use JVBase\blocks\CustomBlocks;
|
use JVBase\forms\TaxonomySelector;
|
use JVBase\meta\MetaManager;
|
use JVBase\meta\MetaForm;
|
use JVBase\managers\AjaxRateLimiter;
|
use JVBase\utility\Features;
|
use WP_Error;
|
use WP_User;
|
|
if (!defined('ABSPATH')) {
|
exit;
|
}
|
|
class LoginManager
|
{
|
protected Features $siteFeatures;
|
protected ?MetaForm $metaForm = null;
|
protected Cache $cache;
|
|
|
protected array $forms =[];
|
protected array $labels = [];
|
protected array $fields = [];
|
protected ?string $action = null;
|
protected string $title = '';
|
|
// Token handlers registry
|
protected array $messageHandlers = [];
|
|
private array $allowed_file_types = [
|
'image/jpeg',
|
'image/png',
|
'image/gif',
|
'application/pdf'
|
];
|
private int $max_file_size = 5242880; // 5MB in bytes
|
|
public function __construct()
|
{
|
$this->siteFeatures = Features::forSite();
|
|
|
$this->cache = Cache::for('login');
|
|
// Initialize magic link support if enabled
|
if ($this->siteFeatures->has('magicLink')) {
|
$this->initMagicLinkSupport();
|
}
|
|
// Create login page if it doesn't exist
|
$this->ensureLoginPageExists();
|
|
|
// Redirect wp-login.php to custom page
|
add_action('login_init', [$this, 'redirectToCustomLogin']);
|
add_action('template_include', [$this, 'renderLoginPage']);
|
|
add_action('wp_enqueue_scripts', [$this, 'enqueueScripts'], 15);
|
|
// Login success handling
|
add_action('wp_login', [$this, 'handleSuccessfulLogin'], 10, 2);
|
|
add_filter( 'login_url', [$this, 'loginUrl'], 10, 3 );
|
add_filter( 'logout_url', [$this, 'logoutUrl'], 10, 2 );
|
// Allow other features to register handlers
|
do_action('jvbLoginManagerInit', $this);
|
add_action('user_register', array($this, 'saveRegistrationFields'), 999, 2);
|
add_filter('the_seo_framework_sitemap_exclude_ids', [$this, 'excludeLoginSitemap'], 10, 1);
|
}
|
|
public function excludeLoginSitemap(array $ids): array
|
{
|
$ids[] = $this->getLoginPage();
|
return $ids;
|
}
|
/**************************************************************************
|
* SETUP & CONFIGURATION
|
**************************************************************************/
|
|
/**
|
* Redirect wp-login.php to custom login page
|
*/
|
public function redirectToCustomLogin(): void
|
{
|
// Handle interim login
|
if (isset($_GET['interim-login'])) {
|
// Don't redirect - let WP handle it
|
return;
|
}
|
// Don't redirect if AJAX or REST
|
if ((defined('DOING_AJAX') && DOING_AJAX) || (defined('REST_REQUEST') && REST_REQUEST)) {
|
return;
|
}
|
// Build custom login URL with all query args
|
$custom_login_page = home_url('/login/');
|
$query_args = $_GET;
|
|
// Remove WordPress internal args
|
unset($query_args['interim-login'], $query_args['wp-auth-check']);
|
|
if (!empty($query_args)) {
|
$custom_login_page = add_query_arg($query_args, $custom_login_page);
|
}
|
|
wp_safe_redirect($custom_login_page);
|
exit;
|
}
|
protected function getRegistrationFormFields():array
|
{
|
$form = get_option(BASE.'registration_form_fields');
|
if (!$form) {
|
$form = [];
|
|
$select = [];
|
//Basic fields, for any
|
$fields = [
|
'user_name' => [
|
'type' => 'text',
|
'required' => true,
|
'label' => 'Your Name',
|
'placeholder'=> 'Mister Meseeks'
|
],
|
'user_email' => [
|
'type' => 'email',
|
'required' => true,
|
'label' => 'Your Email',
|
'placeholder'=> 'look@me.com'
|
]
|
];
|
if (Features::forSite()->has('referrals')) {
|
$fields['referral_code'] = [
|
'type' => 'text',
|
'required'=> false,
|
'label' => 'Referral Code',
|
'hint' => 'Have a referral code? Paste it here!'
|
];
|
}
|
if (count(JVB_USER) > 1) {
|
foreach (JVB_USER as $slug => $config) {
|
if (!array_key_exists('can_register', $config) || !$config['can_register']) {
|
continue;
|
}
|
$icon = $config['icon'] ?? '';
|
$icon = ($icon !== '') ? jvbIcon($icon) : '';
|
$select[$slug] = '<span class="label">'.$icon.$config['label'].'</span><span class="text">'.$config['register']['text']??''.'</span>';
|
if (!empty($config['register']['fields']??[])){
|
foreach ($config['register']['fields'] as $field) {
|
$field['condition'] = [
|
'field' => 'user_select',
|
'value' => $slug,
|
'operator' => '=='
|
];
|
$fields[] = $field;
|
}
|
}
|
}
|
if (!empty($select)) {
|
$select = array_merge(
|
[
|
'subscriber' => 'Subscriber',
|
],
|
$select
|
);
|
$form = array_merge(
|
[
|
'user_select' => [
|
'type' => 'radio',
|
'label' => 'Register as',
|
'options' => $select,
|
'required' => true,
|
'default' => 'subscriber'
|
]
|
],
|
$fields
|
);
|
}
|
}else {
|
$form = $fields;
|
}
|
update_option(BASE.'registration_form_fields', $form);
|
}
|
return $form;
|
|
}
|
|
protected function setupFields():void
|
{
|
$fields = [];
|
switch($this->action) {
|
case 'register':
|
$fields = $this->getRegistrationFormFields();
|
break;
|
case 'lostpassword':
|
case 'magic':
|
$fields = [
|
'user_email' => [
|
'type' => 'email',
|
'label' => __('Email Address', 'jvb'),
|
'required' => true,
|
'placeholder' => 'look@me.com',
|
],
|
];
|
break;
|
case 'rp':
|
case 'resetpass':
|
$fields = [
|
'pass1' => [
|
'type' => 'text',
|
'subtype' => 'password',
|
'label' => __('New Password', 'jvb'),
|
'required' => true,
|
],
|
'pass2' => [
|
'type' => 'text',
|
'subtype' => 'password',
|
'label' => __('Confirm Password', 'jvb'),
|
'required' => true,
|
],
|
];
|
break;
|
case 'login':
|
$fields = [
|
'user_email' => [
|
'type' => 'email',
|
'label' => __('Email Address', 'jvb'),
|
'required' => true,
|
'autocomplete' => 'email',
|
'placeholder' => 'look@me.com',
|
],
|
'user_password' => [
|
'type' => 'text',
|
'subtype'=> 'password',
|
'label' => __('Password', 'jvb'),
|
'autocomplete' => 'current-password',
|
'required' => true,
|
],
|
'remember_me' => [
|
'type' => 'true_false',
|
'label' => __('Remember Me', 'jvb'),
|
'default' => true
|
]
|
];
|
break;
|
case 'postpass':
|
$fields = [
|
'post_password' => [
|
'type' => 'text',
|
'subtype' => 'password',
|
'label' => __('Password', 'jvb'),
|
'required' => true,
|
'hint' => 'This post is password protected. Please enter the password to view it.',
|
],
|
];
|
break;
|
case 'confirmaction':
|
|
break;
|
|
}
|
$this->fields = $fields;
|
}
|
|
/**
|
* Ensure login page exists
|
*/
|
protected function ensureLoginPageExists(): void
|
{
|
$login_page = $this->getLoginPage();
|
|
if (!$login_page || !is_int($login_page)) {
|
$page_id = get_page_by_path('login');
|
if (!$page_id) {
|
$page_id = wp_insert_post([
|
'post_title' => 'Login',
|
'post_name' => 'login',
|
'post_content' => '[jvb_login_form]',
|
'post_status' => 'publish',
|
'post_type' => 'page',
|
'post_author' => 1
|
]);
|
}
|
|
if ($page_id && !is_wp_error($page_id)) {
|
if (is_object($page_id)) {
|
$page_id = (int)$page_id->ID;
|
}
|
update_option(BASE.'login_page', $page_id);
|
// Hide from menus/search
|
update_post_meta($page_id, '_wp_page_template', 'default');
|
update_post_meta($page_id, BASE . 'exclude_from_search', true);
|
}
|
}
|
}
|
public function loginUrl(string $login_url, string $redirect, bool $force_reauth):string
|
{
|
// This will append /custom-login/ to you main site URL as configured in general settings (ie https://domain.com/custom-login/)
|
$login_url = site_url( '/login/', 'login' );
|
if ( ! empty( $redirect ) ) {
|
$login_url = add_query_arg( 'redirect_to', urlencode( $redirect ), $login_url );
|
}
|
if ( $force_reauth ) {
|
$login_url = add_query_arg( 'reauth', '1', $login_url );
|
}
|
return $login_url;
|
}
|
|
public function logoutUrl(string $logout_url, string $redirect): string
|
{
|
// Build custom logout URL
|
$logout_url = site_url('/login/', 'login');
|
$logout_url = add_query_arg('action', 'logout', $logout_url);
|
|
if (!empty($redirect)) {
|
$logout_url = add_query_arg('redirect_to', urlencode($redirect), $logout_url);
|
}
|
|
// Add nonce for security
|
return wp_nonce_url($logout_url, 'log-out');
|
}
|
public function getLoginPage():int|false
|
{
|
return (int)get_option(BASE.'login_page');
|
}
|
|
public function isLoginPage():bool
|
{
|
return is_page($this->getLoginPage());
|
}
|
|
public static function isLogin():bool
|
{
|
$self = new self;
|
return $self->isLoginPage();
|
}
|
|
protected function initMagicLinkSupport(): void
|
{
|
if (!Features::forSite()->has('magicLink')) {
|
return;
|
}
|
}
|
|
/*********************************************************************
|
RENDERING
|
*********************************************************************/
|
public function renderLoginPage(string $template):string
|
{
|
if (!$this->isLoginPage()) {
|
return $template;
|
}
|
$this->setup();
|
$page = $this->cache->remember(
|
$this->getAction(),
|
function() {
|
return $this->renderPage();
|
},
|
5
|
);
|
|
echo $page;
|
return '';
|
}
|
protected function renderPage() {
|
ob_start();
|
jvbInlineStyles('nav');
|
jvbInlineStyles('dash');
|
jvbInlineStyles('forms');
|
$this->customStyles();
|
|
$this->renderHeader();
|
$this->renderForms();
|
$this->renderFooter();
|
|
return ob_get_clean();
|
}
|
|
protected function getAction():string
|
{
|
if (array_key_exists('action', $_GET)) {
|
switch ($_GET['action']){
|
case 'lostpassword':
|
case 'retrievepassword': // Alias
|
$action = 'lostpassword';
|
break;
|
case 'rp':
|
case 'resetpass':
|
$action = 'resetpass';
|
break;
|
default:
|
$action = $_GET['action'];
|
}
|
} else {
|
$action = 'login';
|
}
|
return $action;
|
}
|
|
protected function setup():void
|
{
|
$this->action = $this->getAction();
|
if ($this->action == 'logout' || array_key_exists('loggedout', $_GET)) {
|
wp_logout();
|
wp_redirect(esc_attr($_GET['redirect_to'] ?? get_home_url()));
|
exit;
|
}
|
if (in_array($this->action, ['rp', 'resetpass']) && !is_user_logged_in()) {
|
wp_redirect(wp_login_url());
|
exit;
|
} elseif (is_user_logged_in()) {
|
wp_redirect(get_home_url(null, '/dash/'));
|
}
|
$this->setupLabels();
|
$this->setupFields();
|
$this->setupTitle();
|
}
|
|
protected function setupTitle():void
|
{
|
switch ($this->action) {
|
case 'lostpassword':
|
$title = 'Lost Your Password?';
|
break;
|
case 'resetpass':
|
$title = 'Reset Your Password';
|
break;
|
case 'register':
|
$title = 'Create Your Account';
|
break;
|
default:
|
$title = 'Log In To Your Account';
|
}
|
$this->title = $title;
|
}
|
|
protected function customStyles():void
|
{
|
$logo = get_theme_mod('custom_logo');
|
$small = $large = '';
|
if ($logo) {
|
$small = wp_get_attachment_image_src($logo, 'medium')[0];
|
$large = wp_get_attachment_image_src($logo, 'large')[0];
|
|
}
|
echo '<style>
|
.login header,
|
.login footer {
|
display: none;
|
}
|
.login main {
|
display: flex;
|
flex-direction: column;
|
gap: 2rem;
|
justify-content: center;
|
position: relative;
|
}
|
.login .fstatus.fstatus {
|
--wrap: nowrap;
|
top:0;
|
bottom:unset;
|
right: 0;
|
}
|
.login main::before {
|
background-size: 20vw;
|
inset: 0;
|
z-index: 0;
|
content: "";
|
background-image: url("'.$small.'");
|
background-repeat: no-repeat;
|
position: absolute;
|
background-position: 40vw 1rem;
|
}
|
.login main .login-box {
|
--gap: .75rem;
|
padding: 1rem;
|
border-radius: var(--outerRadius);
|
background-color: var(--overlay-heavy);
|
box-shadow: var(--shadow-right), var(--shadow-down);
|
margin: 15vh auto 0!important;
|
}
|
.login main .login-box,
|
.login main .navigation {
|
z-index: 5;
|
max-width: 90vw!important;
|
}
|
.login main .navigation {
|
padding: 0 1rem;
|
margin: 0 auto!important;
|
font-size: var(--small);
|
}
|
.login-box .button {
|
--height: 2.5rem;
|
width: 100%;
|
}
|
.login-box .options {
|
padding: 0 .5rem;
|
}
|
label[for="user_select-subscriber"] {
|
position: absolute;
|
left: var(--offScreen);
|
}
|
|
@media (min-width:768px) {
|
.login main .navigation,
|
.login main .login-box {
|
max-width: 60vw!important;
|
margin: 0 2rem 0 auto!important;
|
}
|
.login main .login-box {
|
padding: 2rem;
|
--gap: 2rem;
|
}
|
.login main .navigation {
|
padding: 0 var(--offHeight);
|
}
|
|
.login-box .options {
|
padding: 0 4rem;
|
}
|
.login main::before {
|
background-size: 80vw;
|
inset: -5vw;
|
background-image: url("'.$large.'");
|
opacity: .25;
|
transform: rotate(-5deg);
|
background-position: -10vw center;
|
}
|
}
|
</style>';
|
}
|
|
protected function renderForms():void
|
{
|
$this->metaForm = new MetaForm();
|
$form = $this->action.'form';
|
?>
|
<section class="login-box col btw">
|
<h1><?=$this->labels['title']?></h1>
|
<?= $this->labels['description'] ?>
|
|
|
<form name="<?=$form?>" method="post" data-action="jvb_<?=$this->action?>">
|
<?= jvbFormStatus() ?>
|
<?php wp_nonce_field('jvb_'.$this->action, '_wpnonce'); ?>
|
<input type="hidden" name="action" value="jvb_<?=$this->action?>">
|
<input type="hidden" name="redirect_to" value="<?= esc_attr($_GET['redirect_to'] ?? '') ?>">
|
<input type="hidden" name="request_id" value="<?= wp_generate_password(16, false) ?>">
|
<?= ($this->action === 'magic') ? '<input type="hidden" name="type" value="login">' : '' ?>
|
<?php
|
do_action('jvb_add_token_inputs', $this->action);
|
|
foreach ($this->fields as $name => $config) {
|
$this->metaForm->render($name, '', $config);
|
}
|
|
$this->maybeTurnstile();
|
?>
|
<div class="row btw nowrap">
|
<button type="submit" class="button button-primary button-large"><?=$this->labels['submit']?></button>
|
<?php $this->maybeMagicLink(); ?>
|
</div>
|
</form>
|
|
<?php
|
if (is_array($this->labels['extra'])) {
|
echo '<div class="extra">';
|
foreach($this->labels['extra'] as $extra) {
|
echo '<p>'.$extra.'</p>';
|
}
|
echo '</div>';
|
} else if ($this->labels['extra']!=='') {
|
echo '<div class="extra">'.$this->labels['extra'].'</div>';
|
}
|
?>
|
|
<div class="options row btw">
|
<?php
|
switch ($this->action) {
|
case 'login': ?>
|
<a href="<?= add_query_arg('action', 'lostpassword', get_the_permalink()) ?>">Forgot Password?</a>
|
<a href="<?= add_query_arg('action', 'register', get_the_permalink()) ?>">Create Account</a>
|
<?php
|
break;
|
case 'register': ?>
|
<a href="<?= get_the_permalink() ?>">Or Login</a>
|
<a href="<?= add_query_arg('action', 'lostpassword', get_the_permalink()) ?>">Forgot Password?</a>
|
<?php
|
break;
|
case 'lostpassword':
|
case 'magic': ?>
|
<a href="<?= get_the_permalink() ?>">Login Instead</a>
|
<a href="<?= add_query_arg('action', 'register', get_the_permalink()) ?>">Create Account</a>
|
<?php
|
break;
|
|
}
|
?>
|
|
</div>
|
</section>
|
<div class="navigation row btw">
|
<a href="<?= get_home_url() ?>">Home</a>
|
<?php
|
$privacy = get_privacy_policy_url();
|
if ($privacy !== '') { ?>
|
<a href="<?= $privacy ?>">Our Privacy Policy</a>
|
<?php } ?>
|
</div>
|
<?php
|
}
|
protected function renderHeader():void
|
{
|
?>
|
<!DOCTYPE html>
|
<html <?php language_attributes(); ?>>
|
<head>
|
<title><?= $this->title ?> | <?= get_bloginfo('name') ?></title>
|
<meta charset="<?php bloginfo('charset'); ?>">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<link rel="preconnect" href="<?= get_home_url()?>"/>
|
<?php wp_head(); ?>
|
</head>
|
<body class="login">
|
<?php jvbAccessibility();?>
|
<header>
|
<?php
|
$checked = (is_user_logged_in() && current_user_can('prefers_dark_theme', true)) ? ' checked' : '';
|
$title = ($checked == '') ? 'Toggle Dark Mode' : 'Toggle Light Mode';
|
echo '<label title="'.$title.'" id="theme-switch" class="toggle-switch" for="theme-switcher">
|
<span class="screen-reader-text">Toggle dark mode</span>
|
<input class="theme-switch row" id="theme-switcher" name="theme-switcher" type="checkbox"'.$checked.' data-setting="theme" data-theme name="dark-mode" aria-label="Toggle dark mode"><span class="slider">'.
|
jvbIcon('sun-dim', ['title'=> 'Light Mode']).
|
jvbIcon('moon', ['title'=>'Dark Mode']).
|
'</span></label>';
|
?>
|
<p class="title">
|
<a href="<?= get_home_url(); ?>" rel="home" title="Back to Site">
|
<?php
|
$icon = (int) get_option( 'site_icon' );
|
$out = '';
|
if ($icon > 0) {
|
$url = wp_get_attachment_image_url( $icon);
|
if ($url) {
|
$out = '<img src="'.$url.'">';
|
}
|
}
|
if ($out == '') {
|
$out =jvbIcon('house');
|
}
|
?><?= $out ?>
|
</a>
|
</p>
|
</header>
|
<main>
|
<?php
|
}
|
|
protected function renderFooter():void
|
{
|
?>
|
|
<footer class="col">
|
<?= $this->labels['footer'] ?>
|
<?= jvbLoadingScreen() ?>
|
<?= TaxonomySelector::outputSelectorModal() ?>
|
<?php
|
do_action('jvbLoginFooter');
|
?>
|
<p>Made with ♡ by <a href="https://jakevan.ca/">JakeVan</a></p>
|
</footer>
|
|
<?php wp_footer(); ?>
|
|
</body>
|
</html>
|
|
<?php
|
}
|
|
/**********************************************************************
|
TOKEN PROCESSING
|
**********************************************************************/
|
protected function processTokenHandlers(int $user_id, string $email): void
|
{
|
foreach ($this->tokenHandlers as $priority => $handlers) {
|
foreach ($handlers as $token_key => $handler) {
|
if (isset($_POST[$token_key]) || isset($_GET[$token_key])) {
|
$token_value = $_POST[$token_key] ?? $_GET[$token_key];
|
call_user_func($handler, sanitize_text_field($token_value), $email, $user_id);
|
}
|
}
|
}
|
}
|
|
/*************************************************************************
|
* SECURITY & VALIDATION
|
*************************************************************************/
|
|
protected function checkRequestId(): bool
|
{
|
$request_id = $_POST['request_id'] ?? '';
|
if (empty($request_id)) {
|
return true; // No request_id provided, allow (for backward compat)
|
}
|
|
$cache_key = 'request_' . $request_id;
|
if (get_transient($cache_key)) {
|
return false; // Duplicate request
|
}
|
|
// Store request ID for 1 minute to prevent duplicates
|
set_transient($cache_key, true, 60);
|
return true;
|
}
|
|
protected function maybeTurnstile(): void
|
{
|
if (!Features::hasIntegration('cloudflare')) {
|
return;
|
}
|
JVB()->connect('cloudflare')->renderTurnstile();
|
}
|
|
protected function maybeTurnstileScripts(): void
|
{
|
if (!Features::hasIntegration('cloudflare')) {
|
return;
|
}
|
JVB()->connect('cloudflare')->enqueueTurnstileScripts();
|
}
|
|
protected function verifyTurnstile(): bool
|
{
|
if (!Features::hasIntegration('cloudflare')) {
|
return true; // Not enabled, pass verification
|
}
|
|
$token = $_POST['cf-turnstile-response'] ?? '';
|
if (empty($token)) {
|
return false;
|
}
|
|
return JVB()->connect('cloudflare')->verifyTurnstile($token);
|
}
|
|
/************************************************************************
|
LABELS & UI
|
************************************************************************/
|
protected function setupLabels(): void
|
{
|
$default = $this->getDefaultLabels();
|
$default = apply_filters('jvbLoginLabels', $default, $_GET);
|
|
if(array_key_exists('type', $_GET) && $_GET['type'] === 'favourites') {
|
if (array_key_exists('favourites', JVB_LOGIN)) {
|
foreach (JVB_LOGIN['favourites'] as $key => $value) {
|
$default[$key] = $value;
|
}
|
}
|
}
|
|
foreach (['description', 'footer', 'extra'] as $location) {
|
if ($default[$location] === '') {
|
continue;
|
}
|
if (empty($default[$location])) {
|
$default[$location] = '';
|
continue;
|
}
|
$text = (!is_array($default[$location])) ? [$default[$location]] : $default[$location];
|
|
if (!empty($text)) {
|
$default[$location] = '<div class="'.$location.'">';
|
foreach ($text as $d) {
|
$default[$location] .= '<p>'.$d.'</p>';
|
}
|
$default[$location] .= '</div>';
|
}
|
}
|
$this->labels = $default;
|
}
|
|
protected function getDefaultLabels(): array
|
{
|
switch ($this->action) {
|
case 'register':
|
return [
|
'title' => JVB_LOGIN['register']['title'] ?? 'Create Your Account',
|
'description' => JVB_LOGIN['register']['description'] ?? [],
|
'extra' => JVB_LOGIN['register']['extra'] ?? [],
|
'footer' => JVB_LOGIN['register']['footer'] ?? '',
|
'email' => JVB_LOGIN['register']['email']['subject'] ?? '['.get_bloginfo('name').'] Finish Creating Your Account',
|
'submit' => JVB_LOGIN['register']['submit'] ?? 'Create Account',
|
'successTitle' => JVB_LOGIN['register']['success']['title'] ?? 'Success!',
|
'successDescription' => JVB_LOGIN['register']['success']['description'] ?? ['See your email for next steps','(Check your spam folder if you cannot find it after a couple minutes.)'],
|
];
|
case 'lostpassword':
|
return [
|
'title' => JVB_LOGIN['forgot_password']['title'] ?? 'Reset Password',
|
'description' => JVB_LOGIN['forgot_password']['description'] ?? [],
|
'extra' => JVB_LOGIN['forgot_password']['extra'] ?? [],
|
'footer' => JVB_LOGIN['forgot_password']['footer'] ?? '',
|
'submit' => JVB_LOGIN['forgot_password']['submit'] ?? 'Send Reset Link',
|
'successTitle' => JVB_LOGIN['forgot_password']['success']['title'] ?? 'Success!',
|
'successDescription' => JVB_LOGIN['forgot_password']['success']['description'] ?? ['Check your email for reset instructions'],
|
];
|
case 'resetpass':
|
return [
|
'title' => JVB_LOGIN['reset_pass']['title'] ?? 'Reset Your Password',
|
'description' => JVB_LOGIN['reset_pass']['description'] ?? [],
|
'extra' => JVB_LOGIN['reset_pass']['extra'] ?? [],
|
'footer' => JVB_LOGIN['reset_pass']['footer'] ?? '',
|
'submit' => JVB_LOGIN['reset_pass']['submit'] ?? 'Reset Password',
|
];
|
case 'logout':
|
return [
|
'title' => JVB_LOGIN['logout']['title'] ?? 'Logged Out!',
|
'description' => JVB_LOGIN['logout']['description'] ?? [],
|
'extra' => JVB_LOGIN['logout']['extra'] ?? [],
|
'footer' => JVB_LOGIN['logout']['footer'] ?? '',
|
'submit' => JVB_LOGIN['logout']['submit'] ?? '',
|
];
|
case 'magic':
|
return [
|
'title' => JVB_LOGIN['magic']['title'] ?? 'Log in with Magic Link',
|
'description' => JVB_LOGIN['magic']['description'] ?? ['Enter your email.','You\'ll get an email with a magic link.','Click it, and you\'re logged in!'],
|
'extra' => JVB_LOGIN['magic']['extra'] ?? [],
|
'footer' => JVB_LOGIN['magic']['footer'] ?? '',
|
'submit' => JVB_LOGIN['magic']['submit'] ?? jvbIcon('magic-wand').'Send Magic Link',
|
|
];
|
case 'login':
|
default:
|
return [
|
'title' => JVB_LOGIN['login']['title'] ?? 'Sign in',
|
'description' => JVB_LOGIN['login']['description'] ?? [],
|
'extra' => JVB_LOGIN['login']['extra'] ?? [],
|
'footer' => JVB_LOGIN['login']['footer'] ?? '',
|
'submit' => JVB_LOGIN['login']['submit'] ?? 'Sign In',
|
];
|
}
|
}
|
|
protected function maybeMagicLink(): void
|
{
|
if (!JVB()->magicLink() || !in_array($this->action, ['login', 'lostpassword'])) {
|
return;
|
}
|
?>
|
<a class="button" href="<?= add_query_arg('action', 'magic', wp_login_url()) ?>" title="Email yourself a link to log you in auto-magically!">
|
<?= jvbIcon('magic-wand'); ?>
|
Magic Link
|
</a>
|
<?php
|
}
|
|
|
/************************************************************************
|
SCRIPTS
|
************************************************************************/
|
public function enqueueScripts(): void
|
{
|
if (!$this->isLoginPage()) {
|
return;
|
}
|
|
$this->maybeTurnstileScripts();
|
wp_enqueue_script('jvb-form');
|
$action = $this->getAction();
|
|
$redirect_to = isset($_GET['redirect_to']) ? esc_url_raw($_GET['redirect_to']) : '';
|
$has_turnstile = Features::hasIntegration('cloudflare');
|
|
ob_start();
|
?>
|
|
document.addEventListener('DOMContentLoaded', async function () {
|
const hasTurnstile = <?= json_encode($has_turnstile) ?>;
|
const redirectTo = <?= json_encode($redirect_to) ?>;
|
|
window.auth.subscribe(event => {
|
if (event === 'auth-loaded') {
|
const form = document.querySelector('.login form');
|
if (!form || !window.jvbForm) return;
|
|
window.jvbForm.registerForm(form, {
|
autosave: false,
|
endpoint: '<?= $action ?>',
|
formStatus: false,
|
cache: false,
|
});
|
|
window.jvbForm.subscribe((event, data) => {
|
if (event === 'form-submit') {
|
const { config } = data;
|
const formElement = config.element;
|
|
// Collect current form data
|
const formData = new FormData(formElement);
|
const formObject = Object.fromEntries(formData.entries());
|
|
// Add redirect_to from URL
|
if (redirectTo) {
|
formObject.redirect_to = redirectTo;
|
}
|
|
const submit = formElement.querySelector('[type=submit]');
|
const oldText = submit.textContent;
|
|
window.jvbForm.showFormStatus(config.id, 'uploading');
|
|
submit.disabled = true;
|
submit.textContent = 'Loading...';
|
|
window.auth.fetch(`${jvbSettings.api}auth/<?= $action ?>`, {
|
method: 'POST',
|
body: JSON.stringify(formObject)
|
})
|
.then(response => response.json().then(result => ({ response, result })))
|
.then(({ response, result }) => {
|
if (!response.ok) {
|
window.jvbForm.showFormStatus(config.id, 'error');
|
window.jvbForm.handleFormError(formElement, result);
|
return;
|
}
|
|
window.jvbForm.showFormStatus(config.id, 'submitted');
|
|
if (result.message) {
|
window.jvbForm.handleFormSuccess(formElement, result);
|
}
|
|
if (window.auth?.handleLogin && result.auth) {
|
return window.auth.handleLogin(result.auth).then(() => {
|
if (result.redirect) {
|
setTimeout(() => {
|
window.location.href = result.redirect;
|
}, 100);
|
}
|
});
|
} else if (result.redirect) {
|
setTimeout(() => {
|
window.location.href = result.redirect;
|
}, 100);
|
}
|
})
|
.catch(error => {
|
console.error('Form submission error:', error);
|
window.jvbForm.showFormStatus(config.id, 'error');
|
window.jvbForm.handleFormError(formElement, {
|
message: 'Network error. Please check your connection and try again.',
|
code: 'network_error'
|
});
|
})
|
.finally(() => {
|
submit.textContent = oldText;
|
submit.disabled = false;
|
});
|
}
|
});
|
}
|
});
|
});
|
|
<?php
|
$script = ob_get_clean();
|
wp_add_inline_script('jvb-form', $script);
|
}
|
|
/*************************************************************************
|
SUCCESS HANDLING
|
*************************************************************************/
|
public function handleSuccessfulLogin(string $username, WP_User $user): void
|
{
|
if (isOurPeople() && !user_can($user, 'manage_options')) {
|
wp_redirect(get_home_url(null, '/dash'));
|
exit;
|
}
|
}
|
|
|
/**
|
* Handle login errors
|
*/
|
protected function handleLoginError(WP_Error $error): void
|
{
|
$login_url = wp_login_url();
|
$login_url = add_query_arg('login_error', urlencode($error->get_error_code()), $login_url);
|
|
if (isset($_REQUEST['redirect_to'])) {
|
$login_url = add_query_arg('redirect_to', urlencode($_REQUEST['redirect_to']), $login_url);
|
}
|
|
wp_safe_redirect($login_url);
|
exit;
|
}
|
|
public function saveRegistrationFields(int $user_id, array $userdata):void
|
{
|
|
}
|
}
|
|
// Initialize the login manager
|
new LoginManager();
|