ПОЛЬЗОВАТЕЛИ САЙТА / Авторизация Пользователя сайта на любой странице

Заметка создана: 13 февраля 2024 г.

Делаем Блок авторизации на сайте без перехода в Личный кабинет.

В шапку Основного Макета сайта добавляем код, который будет показывать кнопку с иконкой для открытия формы авторизации

<?php
               // Если модуль пользователей сайта доступен
               if (Core::moduleIsActive('siteuser'))
               {
                    if (is_null(Core_Entity::factory('Siteuser')->getCurrent()))
                    {
                         ?>
                             <button type="button" class="site_user me-3">
                             <span class="svg_icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="17px"><path style="fill:#444" d="M313.6 288c-28.7 0-42.5 16-89.6 16-47.1 0-60.8-16-89.6-16C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4zM416 464c0 8.8-7.2 16-16 16H48c-8.8 0-16-7.2-16-16v-41.6C32 365.9 77.9 320 134.4 320c19.6 0 39.1 16 89.6 16 50.4 0 70-16 89.6-16 56.5 0 102.4 45.9 102.4 102.4V464zM224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm0-224c52.9 0 96 43.1 96 96s-43.1 96-96 96-96-43.1-96-96 43.1-96 96-96z"/></svg></span>
                             <span class="small">Войти</span>
                            </button>
                         
                            <div id="site_user_autorisation" class="d-none">
                            <form method="post" action="/users/">
                              <div><input type="text" name="login" id="login" class="form-control mb-2" placeholder="Логин" /></div>
                              <div><input type="password" name="password" id="password" class="form-control mb-2" placeholder="Пароль" /></div>
                              <div>
                                  <button type="submit" name="apply" class="btn btn-primary btn-sm">Авторизоваться</button>
                              </div>
                              <a href="/users/registration/" class="small"> +Зарегистироваться</a>
                            </form>
                            </div>
                            <div id="site_user_autorisation" class="d-none">
                             
                            </div>
                         <?php
                    }
                    else
                    {?>
                        <a class="site_user" href="/users/">
                             <span class="svg_icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="18px"><path d="M313.6 288c-28.7 0-42.5 16-89.6 16-47.1 0-60.8-16-89.6-16C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4zM416 464c0 8.8-7.2 16-16 16H48c-8.8 0-16-7.2-16-16v-41.6C32 365.9 77.9 320 134.4 320c19.6 0 39.1 16 89.6 16 50.4 0 70-16 89.6-16 56.5 0 102.4 45.9 102.4 102.4V464zM224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm0-224c52.9 0 96 43.1 96 96s-43.1 96-96 96-96-43.1-96-96 43.1-96 96-96z"/></svg></span>
                             <span class="small">Кабинет</span>
                         </a>
                    <?php
                    }
                 }  
               ?>

В ТДС "ПользователиСайта" добавляем код

// ADD АВТОРИЗАЦИЯ ВО ВСПЛЫВАЮЩЕМ ОКНЕ
// Ajax Авторизация по логину и паролю
if (Core_Array::getRequest('ajaxapply')){
$oSiteuser = $oSiteuser->Site->Siteusers->getByLoginAndPassword(
strval(Core_Array::getPost('login')), strval(Core_Array::getPost('password'))
);
if (!is_null($oSiteuser)){
if ($oSiteuser->active){
$expires = Core_Array::getPost('remember')
? 2678400 // 31 день
: 86400; // 1 день
$oSiteuser->setCurrent($expires);
}
else{
$sError = 'Пользователь не активирован!';
}
}
else{
$sError = 'Введите корректный логин и пароль!';
}
$aResult = array();
if (!empty($sError)){
$aResult['error'] = $sError;
}
else{
$aResult['success'] = 1;
$aResult['userName'] = $oSiteuser->login;
}
echo json_encode($aResult);
exit();
}
//~END ADD
Пишем код jQuery, который будет у нас обрабатывать запрос на авторизацию с помощью ajax
$(function() {
$('#site_user_autorisation [type="submit"]').on('click', function(){
var form = $(this).parents('form:eq(0)');
form.parents('div:eq(0)').find('.alert-danger').remove();
$.loadingScreen('show');


$.ajax({
url : form.attr('action') + '?ajaxapply=1',
type : 'POST',
data : form.serialize(),
dataType : 'json',
success : function (ajaxData) {
if (ajaxData.success == 1){
form.parents('.fancybox-skin:eq(0)').find('.fancybox-close').click();
$('.register').hide();
$('#authorization').empty().append($('<a>', {href:form.attr('action'), class:'fancy'}).text(' Здравствуйте, '+ajaxData.userName));
}
else{
if (ajaxData.error != undefined){
form.before($('<div>', {class: 'alert alert-danger', role:'alert'}).html(ajaxData.error));
}
}
$.loadingScreen('hide');
},
error : function (){$.loadingScreen('hide');return false}
});
return false;
});
});
php,