mixed CUser::Login( string login, string password, string remember = "N", string password_original = "Y" )
Метод проверяет логин и пароль и если они корректные, то авторизует пользователя. Если авторизация успешная, то возвращает «true», иначе если логин и пароль некорректные, то возвращает массив с ошибкой для функции ShowMessage. Если было превышено количество попыток подключения метод просто не будет авторизовывать пользователя с ошибкой «Неправильный логин или пароль». Нестатический метод.
Параметры
Параметр | Описание | С версии |
---|---|---|
login | Логин пользователя. | |
password | Пароль. Если параметр convert_password_to_md5 = «Y», то в данном параметре необходимо передавать оригинальный пароль, в противном случае необходимо передавать md5 от оригинального пароля. | |
remember | Если значение равно «Y», то авторизация пользователя будет сохранена в куках (при следующем заходе посетитель будет автоматически авторизован), в противном случае — авторизация не будет сохранена в куках. В куках сохраняется специальный хеш получаемый с помощью CUser::GetPasswordHash. Затем когда посетитель снова приходит на сайт, система его автоматически авторизует используя CUser::LoginByHash Необязательный. По умолчанию «N». |
|
password_original | Если значение равно «Y», то это означает что password ещё не сконвертирован в MD5 (т.е. в параметре password передается реальный пароль вводимый пользователем с клавиатуры), если значение равно «N», то это означает что password уже сконвертирован в MD5. Для текущего авторизованного пользователя MD5 от реального пароля можно получить с помощью метода $USER->GetParam(«PASSWORD_HASH»). Для произвольного пользователя MD5 от пароля можно получить с помощью CUser::GetByID (поле «PASSWORD»). Необязательный. По умолчанию «Y». До версии 4.0.6 назывался pass2md5. | 3.0.10 |
См. также
- CUser::Authorize
- CUser::IsAuthorized
- CUser::LoginByHash
- CUser::Logout
- Событие «OnBeforeUserLogin»
- Событие «OnAfterUserLogin»
Примеры использования
<? global $USER; if (!is_object($USER)) $USER = new CUser; $arAuthResult = $USER->Login("admin", "123456", "Y"); $APPLICATION->arAuthResult = $arAuthResult; ?>
dev.1c-bitrix.ru
User Registration Form
This code is to show the signup form to the user. When the user submits the form with his details, the JavaScript function will be called to validate user input. After successful validation, the PHP code will read the posted form data to execute database insert.
<?php if (! empty($response)) { ?> <div id="response" class="<?php echo $response["type"]; ?> "> <?php echo $response["message"]; ?> </div> <?php } ?> <form action="" method="POST" onsubmit="return signupvalidation()"> <div class="row"> <label>Name</label><span id="name_error"></span> <div> <input type="text" class="form-control" name="name" id="name" placeholder="Enter your name"> </div> </div> <div class="row"> <label>Email</label><span id="email_error"></span> <div> <input type="text" name="email" id="email" class="form-control" placeholder="Enter your Email ID"> </div> .
word" class="form-control" placeholder="Re-enter your password"> </div> </div> <div class="row"> <div align="center"> <button type="submit" name="submit" class="btn signup">Sign Up</button> </div> </div> <div class="row"> <div> <a href="login.php"><button type="button" name="submit" class="btn login">Login</button></a> </div> </div> </form>
The JavaScript validation will take care of the mandatory fields’ non-empty check and also email format validation with regex pattern.
<script> function signupvalidation() { var name = document.getElementById('name').value; var email = document.getElementById('email').value; var password = document.getElementById('password').value; var confirm_pasword = document.getElementById('confirm_pasword').value; var emailRegex = /^[a-zA-Z0-9.!#$%&'.
} } if (password == "") { valid = false; document.getElementById('password_error').innerHTML = "required."; } if (confirm_pasword == "") { valid = false; document.getElementById('confirm_password_error').innerHTML = "required."; } if (password != confirm_pasword) { valid = false; document.getElementById('confirm_password_error').innerHTML = "Both passwords must be same."; } return valid; } </script>
This PHP code to create insert using the registration form data. After executing the database insert the success/error response will be sent to acknowledge the user.
<?php if (isset($_POST["submit"])) { include_once 'dbConnect.php'; $name = $_POST['name']; $email = $_POST['email']; $password = md5($_POST['password']); $database = new dbConnect(); $db = $database->openConnection(); $sql1 = "select name, email from tbl_registered_users where email='$em.
onse = array( "type" => "error", "message" => "Email already in use." ); } } ?>
Login Authentication using PHP
The registered user can login to the application via this login form. The login authentication is done by matching the login email and password with the registered user database. If match found then the application will allow the user to proceed further. Otherwise, the login panel will acknowledge the user about the invalid attempt.
<form action="" method="POST" onsubmit="return loginvalidation();"> <div class="row"> <label>Email</label> <span id="email_error"></span> <div> <input type="text" name="email" id="email" class="form-control" placeholder="Enter your Email ID".
; <a href="index.php"><button type="button" name="submit" class="btn signup">Signup</button></a> </div> </div> </form>
The PHP code for validating the user login with the database is shown below. After successful login, I redirect the user to the dashboard.php. The dashboard will show the welcome message by addressing the logged-in member. Also, there will be an option to log out current session.
<?php session_start(); if (isset($_POST["submit"])) { include_once 'dbConnect.php'; $email = $_POST['email']; $password = md5($_POST['password']); $database = new dbConnect(); $db = $database->openConnection(); $sql = "select * from tbl_registered_users where email = '$email' and password= '$password'"; $user = $db->query($sql); $result = $user->fetchAll(PDO::FETCH_ASSOC); $id = $result[0]['id']; $name = $result[0]['name']; $email = $result[0]['email']; $_SESSION['name'] = $name; $_SESSION['id'] = $id; $database->closeConnection(); header('location: dashboard.php'); } ?>
Download
This PHP code tutorial was published on April 5, 2018.
↑ Back to Top
phppot.com
@ Kent
harks back to XP days but this bit still works
@echo — —
@echo — Logging in …………………………………. — —
@echo ———————————————————-
:: comments for admin to tracks changes here
:: set file server and local server
Set FileSvr=File-02
:: Get the PCs IP address
call :GetIPAddress
:: Get the date in ISO format (YearMonthDay)
call :GetISODate
:: Save a log of each logon, user account x computer x location x room etc.
call :LogonLog
:: exit clause for servers with names starting with SERV (change to suit your environment)
if /i [%computername:~0,4%]==[SERV] (
goto :Eof
)
:: IE opens to our intranet page
start iexplore
Exit
:: End Main
::——————————————————————————————————————
::——————————————————————————————————————
:GetISODate
@echo.
@echo —————————————————————
@echo Set ISODate…
@echo.
:: Grab only the last 10 chars (DD/MM/YYYY or MM/DD/YYYY)…
Set ISODate=%date:~-10%
:: If the date format is MM/DD/YYYY then convert it to DD/MM/YYYY…
for /f «tokens=1-9 skip=1 delims=()-» %%i in (‘@echo. ^| date 2^>nul’) do (
if /i [%%j]==[mm] ( Set ISODate=%ISODate:~3,2%/%ISODate:~0,2%/%ISODate:~6,4% )
)
:: Now convert «DD/MM/YYYY» to YYYYMMDD…
Set ISODate=%ISODate:~6,4%%ISODate:~3,2%%ISODate:~0,2%
:: ——————————————————————-
goto :Eof
:: End GetISODate
:LogonLog
@echo —————————————————————
@echo Record Net Logon details…
@echo.
:: output to central log file — we set a «location» system environmental variable in each PC according to the site it is located at
Set OutString=%Username%,%computername%,%Location%,%LogonServer%,%IP%,%date%,%time:~0,5%,%ISODate%,%ScriptVer%,%sessionname%,logon
@echo %OutString% >> «\%FileSvr%NetworkData_NetLogonLogs%userdomain%.csv»
:: output to users H drive (useful for checking the last time they logged in before archiving)
@echo %OutString% >> «H:%Username%’s LastLogon.csv»
:: Clean up the temporary variables…
Set ISODate=
Set OutString=
goto :Eof
:: End LogonLog
:end
4sysops.com
функция-обработчик( array &arParams );
Событие «OnAfterUserLogin» вызывается в методе CUser::Login после попытки авторизовать пользователя, проверив имя входа arParams[‘LOGIN’] и пароль arParams[‘PASSWORD’].
Параметры
Параметр | Описание |
---|---|
arParams | Массив полей проверки имени входа и пароля:
|
Примечание
Все параметры данного обработчика являются ссылками на исходные переменные. Поэтому, если вы измените значение параметра внутри обработчика, это приведет к смене значения исходной переменной поступившей на вход функции-обработчика.
Это позволяет, например, изменить RESULT_MESSAGE, что приведет к смене сообщения возвращаемого функцией CUser::Login.
См. также
- Событие «OnBeforeUserLogin»
- CUser::Login
- События
- Внешняя авторизация
Пример функции-обработчика:
<? AddEventHandler("main", "OnAfterUserLogin", Array("MyClass", "OnAfterUserLoginHandler"));
class MyClass { // создаем обработчик события "OnAfterUserLogin" function OnAfterUserLoginHandler(&$fields) { // если логин не успешен то if($fields['USER_ID']<=0) { // счетчик неудавшихся попыток логина $_SESSION["AUTHORIZE_FAILURE_COUNTER"]++; // если количество неудачных попыток авторизации превышает 10, то if ($_SESSION["AUTHORIZE_FAILURE_COUNTER"]>10) { // ищем пользователя по логину $rsUser = CUser::GetByLogin($fields['LOGIN']); // и если нашли, то if ($arUser = $rsUser->Fetch()) { // блокируем бюджет пользователя $user = new CUser; $user->Update($arUser["ID"],array("ACTIVE" => "N")); // задаем сообщение $fields['RESULT_MESSAGE'] = array("TYPE" => "ERROR", "MESSAGE" => "Ваш бюджет блокирован."); } } } } } ?>
dev.1c-bitrix.ru
Conclusion
I hope this tutorial was helpful to you. I am glad you actually followed it through to the end. Feel free to examine the code, customize it to suit your needs and use it in your projects. If you have any issues or comments or any remarks at all about this tutorial, leave it in the comments below.
Best wishes!
codewithawa.com