I am building a blog website, from scratch, so I am not using any frameworks, only plain html, css, javascript and php.
What is the "good habit" and secure way to check in Javascript if an admin or any user is logged in? For example, if a normal member is logged in, I don't want to show buttons / pages like "New post", or "Delete post". Now I do it with ajax, I call my router.php (all get and post request are handled there), and send the client's cookie to the server, where router.php checks if the cookie["token"] is equal to session["token"], and only then it sends back information (username and member-status into ajax's success function) to Javascript, and there I do something like if(username == "admin") then show "Delete button". Code:
if(document.cookie.indexOf("token") != -1){ // check if cookie["token"] exists
$.ajax({ //create an ajax request to router.php
type: "POST",
url: "../php/router.php", //cookie_check data only
data: {"cookie_check" : document.cookie.split(';')[1].split("=")[1]},
dataType: "json",
success: function(response){
// sign in button transform to username
var username = response[0]["username"];
var status = response[0]["status"];
$("#signInMenu").empty();
var usernameList = document.createElement("li");
usernameList.innerHTML = username;
usernameList.className = "usernameCss";
document.getElementById("menuNavId").appendChild(usernameList);
// check which page is loaded
var sPath = window.location.pathname;
var currentPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(currentPage == "posts.html" && username === "admin"){
//PLACE BUTTONS
}
}
});
}
It works but I don't think this is the right way to do it. All my views are in .html files, the controllers are JavaScript which are included in the .html files and in them I call ajax, and there is only 1 php file which serves all the requests from ajax. Can you somehow explain the concept/good habit?