Good day to all. The task is to implement the service to which the user will get having a login (usually generated by the admin), and the administrator will log in with a login and password. Accordingly, after authorization, the admin should have his own page, and the user has his own. With this, in principle, everything is clear, but the first part is not very ... The essence of the question: please tell me in what ways can the authorization described above be implemented? Stack: Mongo DB or Redis (for now being defined), Express, React JS. As I see it: the admin will have a panel in which he will add user logins that will be saved to the database, then if there is a username in the database, then the user can log in, if not - no. Thanks in advance
1 answer
I think it is worth creating a users table, which will contain login and uid (if needed) and other user info (except admin). The administrator on the page has a form for adding a user (the contents, depending on what needs to be entered into the + login database).
When authorizing users there is a request to the database
SELECT COUNT(*) FROM users WHERE login='...' and if it returns not 0 or an error, then the authorization is successful, ip is recorded in the database (at discretion) and login is written in the cookie. When checking the user for authorization, this cookie is viewed and the corresponding page or login page is displayed.
I decided to write an example
login.php
<?php //Подключаем скрипт с проверкой логина include_once 'login_lib.php'; //Проверяем, была ли отправлена форма if(isset($_POST['login']){ //Обрабатываем переменную, для защиты $login = trim(striptags($_POST['login'])); //Проверяем if(isLogin($login)){ //Пишем куки cookie("login", $login, 3600 * 24 * 30, "/"); //Меняем заголовок для перехода на предыдущую страницу header("Location: ".$_SERVER['HTTP_REFERER']); //Выходим из скрипта exit(); } } //Если форма не была введена или логина нет в базе //будет загружена страница входа include_once 'login.html'; ?> login_lib.php
<?php //Подключаемся к MySQL $db = mysqli("localhost", "user", "pass"); //Выбираем базу $db->select_db("site"); //Функция проверки существования аргумента в таблице пользователей function isLogin($login){ //В результате запроса получаем кол-во записей с логином //соответствующем аргументу $result = $db->query("SELECT COUNT(*) FROM users WHERE login='$login'"); //Возвращаем итог сравнения этого кол-ва с нулём //(если кол-во больше 0, то вернёт истину) return $result.fetch_row()[0] > 0; } ?> Code at the top of each page requiring login
<?php //Подключаем скрипт с проверкой логина include_once 'login_lib.php'; //Проверяем, существует ли нужная куки //и существует ли она в базе //Так же значение проходит через защиту if(!isset($_COOKIE['login']) || !isLogin(striptags($_COOKIE['login']))){ //Если нет, то меняем заголовок на страницу входа header("Location: {$_SERVER['SERVER_NAME']}/login.php"); //И выходим из скрипта exit(); } //Иначе подключаем саму страницу include 'index.html'; ?> With the rest you can figure it out yourself.
- I am certainly grateful to you, but the stack of technologies was written .. but I will study, thanks - Vladyslav Tereshyn
- @VladyslavTereshyn I apologize) Just instead of pseudocode, I wrote on php) At least I would think so) - goodmice
- The part that should be on every page can be written in js with ajax get request at the very beginning, and you can set cookies at the entrance with ajax requests - goodmice
- Thanks, I basically understood the point; I wanted to hear ready-made solutions (jp) in the answers more. but thank you so much - Vladyslav Tereshyn pm
- @VladyslavTereshyn if you want, I can write about ajax - goodmice