I have been using PHP and JavaScript for building my dad's website. He wants to incorporate a login system into his website, and I have the design for the system using PHP. My problem is how do I show buttons if the person is logged in?
For Example - You have Home, Products, About Us, and Contact. I want to have buttons for Dealer, Distributor, and maybe other information if the user is logged in. So I will have Home, Products, About Us, Contacts, Dealer (if dealer login), Distributor (if distributor login), and so forth.
Would JavaScript be a good way to do this or would PHP, or maybe even both? Using JavaScript to show and hide buttons, and PHP to check to see which buttons to show.
Regarding security, you cannot trust what comes from the client:
The visitor can see all your code (HTML and Javascript, not PHP) and try stuff
The visitor may not even use a browser; it's trivially easy to send a request with a script
This means hiding the buttons is good User Interface design (because you can't use them if you are not logged in). But it's not a security feature. The security feature is checking, on the server, that the visitor is logged in before each action that requires it.
If you don't intend to show the buttons, it's not useful to send the HTML and images to the browser and then hide them with Javascript. I would check with PHP.
In your menu file or w/e you put:
<? require 'auth.php' ?>
<ul>
<li>Home</li>
<li>Products</li>
<? if( loggedin() ): ?><li>Secret area</li><? endif; ?>
</ul>
Then in pages that require auth just do this:
<?php
require 'auth.php';
require_login();
?>
Where auth.php may contain:
<?php
function loggedin(){
return isset( $_SESSION['loggedin'] );
}
function require_login(){
if( !loggedin() ){
header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );
exit;
}
}
?>
If you use javascript to hide the buttons, you open a security hole in the application. A malicious user could either disable javascript or apply some of their own to get around your security.
I suggest using PHP to chose to either render the buttons or not. I do this in .NET quite often.
You should be able to check the user's access on the server-side whenever they try to use a restricted button as well.
What we have done at my work is have a library the provides functions such as checking if the user is logged in. For example:
<?php
require_once 'Auth.php';
// output some html
if (isLoggedIn()) {
echo 'html for logged in user';
}
// rest of html
For pages that only authenicated users should see, the controller checks if they are logged in and if not it redirects them to the login page.
<?php
public function viewCustomer($customerId) {
if (!isLoggedIn())
redirectToLoginPage();
}
Everything that Christian Lescuyer wrote is correct. Notice, however, that he said "I would" and not "you should". The choice is not that easy.
First of all, security is not an issue in the choice. You should have security check on server when you execute an action. Which code decides to show/hide the button that leads to the action is irrelevant.
That leaves us with only one drawback of doing show/hide logic in Javascript - the HTML sent to user is bigger than necessary. This may not be a big deal.
Having show/hide logic in PHP does have a minus, though. The PHP code required is usually a tag soup. Akira's code provides a good example of how it is usually done.
Corresponding Javascript code would probably look something like this:
if (logged())
{
elementSecretArea.style.display = "list-item";
}
(assuming that elements that could be hidden have display:none by default).
This style also allows nice "Ajax" scenario: user sees a page w/o secret area, inputs password, sees the secret area all without refreshing the page.
So, if you already have a script that runs when your document load for other reasons, I would seriously consider having show/hide logic there.
Basically where you have your menu in html, say as a list <ul> <li>Home</li> </ul> you add php after </li> of the last item:
<?php
if($session-logged_in) {
?>
<li>My Account</li>
<?php
}
?>
Related
I created an "embed code" within my site, which is simply an iframe
I would give this code to embed only certain users but do not know how to do. a user could get inspecting the html code from the authorized sites and get the code without permission.
how do I make my site that only authorized users?
I thought about taking $ _SERVER ['HTTP_REFERER'] but as soon as you click a link to the internal frame the referrer is lost.
You can't really avoid authorized person inspecting the URL of the inline frame and revealing it to an unauthorized person. The right course of action is to serve an empty/error page to an unauthorized user.
You could achieve that by creating a session upon user login and verifying that session in the source code the of page displayed in the inline frame.
Do not rely on referrer, it is easily spoofable and some browsers won't even set it. Session cookie is not spoofable unless the user knows the credentials used to create it, which makes them authorized, whether or not they are authenticated.
Verify the user with js.
<iframe src="verify.php">...
Verify.php contains:
<?php
session_start();
$id= generate sth random;
$_SESSION["id"]=$id;
?>
<script>
window.location="http:yourdomain/site.php?id=<?php echo $id;?>&referrer="+document.referrer;
</script>
Loading...
Now you can check the referrer, to verify if the site is correct and the id to check if nobody tried to trick you...
<?php
session_start();
if($_SESSION["id"]!=$_GET["id"] or $$_GET["referrer"]!="allowedsite.com"){
echo "not valid";
die();
}
?>
As Thomas Hübelbauer noted, people could still copy your code. The only thing you can do against it is obfuscation and the use of relative links. That makes it hard to copy.
I am creating a user authentication system using PHP, JQuery, and AJAX. On submit, a request will be sent to 'authenticate.php' with data: username & password using AJAX. The PHP code checks a database for the record and returns 0 on success, 1 on failure. Then if the returned value is 0, the page will be redirected to the 'user private page' using 'window.location="user.php"'.
Now, the question is, is it safe and proper way to authenticate like this? Are there any security problems to use jQuery/JavaScript to redirect page?
Now, the question is, is it safe and proper way to authenticate like this?
Only if inside your user.php you check again if the user has successfully authenticated already. (This is usually where sessions come into play.)
Otherwise, of course everyone who knows the URL of user.php can access it directly.
Are there any security problems to use jquery/js to redirect page?
The only difference between window.location="user.php" (which is wrong, btw. – correct would be window.location.href="user.php") and, say, a normal link to that page, foo, is that the first one happens automatically, and the second one would require the user to click the link first.
So, it is as “secure” as if you had used a simple link. What that actually means here in this case, depends what I said above.
Depends on how secure and compliant you want you application to be. According to RFCs its not recommended to login like that, but keep the form on server side and integrate the login form on frontend (via iframe), then just redirect with redirect url and token, scopes etc to a local html which then eg. sends a window postmessage to your frontend application.
https://www.rfc-editor.org/rfc/rfc6749#page-19
If you just want to be quick and dirty you can go for window.location.href or document.location.href.
Or a bit more secure, send the user to the server and let this be redirected back, but can end up in redirection hell, as its not easy to get back to the state where the user was (including settings and stuff).
Anyways, you will always have to check for the current users's session state whatever you do afterwards with serverside (Sessions).
Since you are working with PHP already i don't recommend using JS to redirect the user. You can use PHP for that:
if($user == $db['user'] && $password == $db['password']){
$_SESSION['logged_in'] = true;
header('location:user.php');
}else{
echo 'username of password is wrong';
}
Then on your user.php file:
if(isset($_SESSION['logged_in'] && $_SESSION['logged_in'] == true){
echo 'welcome to the user page';
}else{
header('location:index.php');//Go back to login page
}
If people go directly to the user.php page, they will be redirected to the index.php page.
So.
In a LAMP stack (PHP), I've got this situation where I'm showing an intermediate page based on some variable from the first page --more simply, I have one page called, say, ListOfProjects, from which I can select a project to view.
When I go to that project, there are other page-navigation elements (like looking at individual jobs in the project, say) the user can click. Once I click them, and am navigated away from the intermediate page between ListOfProjects and IndividualJob, I have to resubmit the data that got me there.
That's fine, and if I could do it automatically, I would. However, I haven't found a way to force this behavior and eliminate the extra click and the ugly "Confirm Form Resubmission" screen.
Does anyone know a way I could A) silently force form-resubmission when the user hits the back button or B) avoid the situation where there's a form that needs resubmitting?
I've thought about trying to just pass that project ID to the session variable, but it's well within scope to have more than one individual project open in the same browser, which would make that unwieldy.
Thoughts? Suggestions?
Thanks!
Don't use POST.
When you are getting data from the server, use GET and put the data in the query string.
POST is designed for sending data to the server that will make a change (e.g. updating data in the database), it isn't appropriate for just deciding what data to look at.
Some solution is bypass using jQuery to resubmit a form when click on back:
<?php if (isset($_POST['ListOfProject'])): ?>
<form method="POST" id="backToProject"></form>
<script>$("#backToProject").submit()</script>
<?php endif ?>
Another solution is to use header("Location: ...") to force users to redirect a page, BUT you should remove all previous $_POST request using unset($_POST) such as:
unset($_POST);
header("Location: your_uri://your_path");
Try reload a page and reload a page using javascript into <script> tag such as:
if ($_POST['ListOfProject'])
{
echo '<script type="text/javascript">location.reload();</script>';
}
Try to understand GET/POST method: https://en.wikipedia.org/wiki/Post/Redirect/Get
And I don't recommended using link of sites using $_POST method such as say Quentin user.
I am trying to separate an tangled mess of PHP and JS. I'm not looking for perfection in the first draft but anything is better than the current state.
Current (all in one file):
<?php if( checkSecureUserStuff ): ?>
//bunch of js like including admin features
//not fun stuff
<?php endif; ?>
Proposed:
PHP file
if( checkSecureUserStuff ){
$userAccess = 'admin';
}
...
//Later in file, I know this still not ideal
<script>
var useraccess = <?= json_encode($userAccess) ?>;
</script>
JS file
if( useraccess == 'admin' ){
// do the admin related JS stuff here
}
Obviously in the final HTML var useraccess = 'admin'; will be visible. Is it open to manipulation at that point? I know this design isn't great, but is it terribly insecure?
Oh yea, I should mention. Actions are still checked on the server. This is more about securing the UI and keeping certain stuff disabled. The server would still verify actions.
I guess the question is more about can a user manipulate the UI if the variables are set and checked on document load. Already partially answered by millerbr's mention of setting break points
. Didn't think of that
Yes. The user will be able to open their browser console, view the code, pause it at a breakpoint they have set, and then write code in the console to edit the variable.
You should never trust your frontend for security type things - yes, write code to limit access, but always double-check on your backend and assume any requests are insecure.
There are things you can do to obscure your code and make it more difficult to manipulate, such as minifying the code, but nothing is 100% effective and so you should always assume the frontend is compromised and place the necessary precautions on any incoming data or requests.
i've to create a "like" button as Facebook.
So this button will be on many web sites, that calls a javascript file hosted by me, which handle hover/click/etc.. action of button.
Now, how can I check if the user is logged or not in my website (Php with sessions) with js?
So if the user is logged the like button would change text and shows that user liked it, otherwise the user will be redirected(maybe a popup) on registration page.
How can I handle this type of cross-domain(js/ajax) request?
To enable cross-domain requests, add
header("Access-Control-Allow-Origin : *")
to the top of your PHP file.
Then do something like this :
<?php
if(isset($_SESSION['user_logged_in']){
echo "TRUE";
}
else{
echo "FALSE";
}
and take action on your page based on the value returned.