Check if user Logged in - javascript

hey There I completely new to this kind of work! Actually I want to check if user is successfully logged in!
suppose that i have a menu item:
<li>Java</li>
when user clicks on it:
function CheckSignIn() {
//here i want to check login
if (!login) {
alert('please login');
} else {
window.open('new page url here');
}
}
I know how can i do it with php i.e.
<?php
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo (welcome user);//sort of
} else {
echo "please login!";
}
?>
In simple I want to check if user logs in using javascript and i know i cant use php inside java script can somebody help me please! Its not an assignment but i am learning it to my own

You cannot check session variable using JavaScript since a session variable is stored on server. To do this you'll have to call your server side code asynchronously using js. jQuery ajax can help you make the async call.

Very similar to access-php-variable-in-javascript
Even $_SESSION is a PHP variable so I am sure you should be able to get it in javascript variable.

One way is to send a xhr to the server which returns true or false if a user is signed in (aka a session value is set eventually making a database call), parse the response and return true or false.
Another way is to send an encrypted token (jwt is what I use currently) upon login that is stored in the browser's sessionStorage
So either you have everything on the server side
or you have the clientside UI which makes requests to the server side api.
Both have advantages and disadvantages.
If you have a client side UI that makes requests to an api, like in your example I suggest you send a JWT upon login, store it in the browser's sessionStorage.
Now you'd like to check on the client side if a user is logged in for display purposes. So check if a token in the sessionStorage exists, that means a user is logged in. Now when making a request to the server you send that token in a header field. The server checks the token for validity and if valid performs the operation. If not status 403.
This has downsides, the user needs to log in for every browser window it opens. Storing it in localStorage adds new security considerations, which are out of scope of the question (CSP, X-Frame-Options, and so on). JWT by default uses RSA and SHA256 (RS256).
The flow is:
User fills out login form and hits submit
Server receives the login information and if valid sends a token
If reponse status != 403|401 store the token in sessionStorage
When making a request to a protected resource the client sends the token in a header field.
Server checks token for validity
If valid send protected resource (or content that was requested)
Client renders received content

Related

How to extend firebase authentication login session from the client side?

The question is in the title. I have done some research but it seems like I can't find a solution to extending the life of the login session when using firebase authentication.
Currently, I have a file that logs the user in from the front-end. After logging in with Firebase Authentication, I pass the firebase id token to the server:
//[index.php]
auth.onAuthStateChanged(function(user) {
if (user) {
//Retrieve the firebase id token
user.getIdToken().then((idToken) => {
//Send the idToken to the server
sendIdTokenToServer();
});
} else {
//The user is logged out, redirect to login page
}
});
From the server side, I verify the firebase id token, and assign it to $_SESSION['firsebase_id_token'] if the token is valid.
//[server.php]
//Pseudo verifying the token, if the token is valid, record it
if (verifyToken($token)) $_SESSION['firebase_id_token'] = $token;
Now, from this point on, I am trying to verify the token before processing anything from the server side. For example:
//[test.php]
//Before processing anything, validate the token
if (verifyToken($_SESSION['firebase_id_token'])) {
//Perform an action because the user is still logged in
} else {
//Redirect the user to login page because they are logged out/the token cannot be verified
}
I am not certain this is the right approach to the problem (so please suggest the correct approach), they are just what I think is right when reading the documentation. All I want to do is to verify the user (that logged in from the client side) from the server side before performing any administrative tasks. The problem is after a very short period of time, the $token isn't valid any more, so the request cannot be made.
How do I extend the firebase id token session from the client side?
Instead of using onAuthStateChanged, which is only triggered when the user signs in or out, you should be using onIdTokenChanged, which is triggered whenever the user's auth token is refreshed (every hour automatically, or on demand when you call getIdToken(true)).

How to check if username and password are correct in web2py?

I want to check if the username and password which is in a database are correct.
For this i made a javascript function.
function checkLogin() {
username = (document.getElementById('login').value
password = document.getElementById('password').value)
if (username == db.Membership.select(username)){
alert("it exists")
So this function gets called everytime when someone clicks on Log in after they have entered their details. Is it possible to check if username and password are correct?
In web2py, db.Membership.select(username) is Python code and must be run on the server in a model or controller (or module) -- it is not Javascript and cannot be run in the browser.
Furthermore, it doesn't make sense to simply check in the browser whether a user's login credentials are valid because (a) you need to know on the server whether a user is logged in (in order to control access to functions and resources on the server) and (b) an attacker could simply run some Javascript in the browser console to fake a valid login.
In web2py, a user's logged in status is stored in the session, which is either stored on the server (in a file or in the database) or in an encrypted and signed cookie (which cannot be altered from the client side). The authentication itself must happen on the server (so it cannot be faked).
If you want to log a user in, you should use the standard login mechanism. If you want the login submission to be handled via Ajax, you can post the credentials to a web2py controller function, and in the controller, you can call auth.login_bare(username, password), which will either log in the user (i.e., update the session to indicate login) or return False if the login fails.

server request security with tokens

I have built a browser game and now I'm working on making it a bit more secure. Since all server requests are initiated from javascript even kids could tamper data on the server. I've been reading through questions on stackoverflow and implemented sending/receiving a token in my requests however I am regenerating this token on every request to the server and send the new one back to the client for the next call. Requests are made through https and are of type POST.
Here's the token flow on client side:
var token = 'abcd1234';
$.ajax({
url: "index.php",
type: "post",
data: {
method: "score",
value: 50
}
});
$(document).ajaxSend(function(e, xhr, o){
o.data += '&token=' + token;
});
$(document).ajaxComplete(function(e, xhr, o){
var data = JSON.parse(xhr.responseText);
token = data.token;
});
And on server side:
if (!isset($_POST['token']) || ($_POST['token'] != $_SESSION['token']))
{
die();
}
else
{
// generate new token and send it back along with the response
}
So my question would be if this token increases the security of my server requests or not and what can be done to further increase the security?
EDIT This is a facebook game, all code is javascript and the server side simply handles updating the database.
I dont really think tokens do alot when using Ajax.
You should just validate all your forms and data server sided with the users session because the login itself is the most realiable way to identify a user.
A token an merely help to make session stealing/riding harder but if you code your session handle to logout the user on changed IP adress this should be fair secure enough.
I have an online game aswell and I dont do more but validate all forms and values against injection, valid data and check the login/session every time correctly and never had any bad experience with that.
One more thing I do is security issue is that you should flag your admin accounts with a special attribute that it requires a special IP range to login, then I fetch the ip range with a whois lookup on ripe.net and enter it into the database and look if the users actual IP is inside the min and max ip, this way maybe 1 of 1000 attackers would have the correct IP adress to login with the admin account even if they achive the login data.
Remember that the generated token will be received and send with every normal ajax request and someone who want to harm you and your page will analyse your form and request data and then simply copy that process.
It will make it harder for script kiddies, but not for professional intruders.
Its all just a matter about how paranoid you are about security issues and how skilled your possible attackers are.
As Steini already stated the ONLY reliable login system is done with session. The client side solution has got infinity security issues.
You can for example make the system using session and than use Javascript to ask php if the user is logged, and which privilege it has.
This said you can use PDO to increment the security, you can also fetch all the data from all the form and all variables that are passed through browser alone to exclude some issues.
Without a secure login system your game will be a security bomb and will create you trouble soon or later.

Persisting a security token between calls

We are creating a prototype application as follows:
We have a html web site using knockoutjs
Using qQuery/Ajax it communicates with Web Api services
We only want the services to be accessed by authorised users. So we have written in security that can validate the user based on username/password
So next I guess we need to pass back some type of token to the client which it uses in further communications with the API services.
What I would like to know is how this is stored on the client so it can be passed back to the server again for the next call?
I assume the client makes an initial call passing in the user name and password over HTTPS and gets back a token. You question is to how to store the token? I assume your application is an SPA. If so, why not just store it in a JavaScript variable? If you do not use a cookie, you avoid XSRF. Of course, you must ensure the user name and password are never stored in the client side and that the life time token of your token is finite and preferably as small as possible.
EDIT:
If you can regenerate the token with every page (since it is not SPA), it is even better and you make the life time of token very small. You can use code like this. I use Authorization header and bearer scheme but you can use your own scheme as well, if no standardization is needed.
var accessToken = ''; // Write out the token into this variable in the server side (view)
$.ajax({
type: 'GET',
url: 'http://whatever',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: { 'Authorization=': ='Bearer ' + accessToken },
success: function (data) {
}
});
So we have written in security that can validate the user based on username/password
This sentence basically means that you need to store the username and password in your javascript file in order to be able to call the service, unless of course you want to ask the user to enter his credentials on every single action he performs. I hope this is not something you are wiling to do at the moment. If it is then you can stop reading my answer and store the username and password in your javascript file.
At this stage it is more than clear that your security should be handled differently. Your Web API should not be protected by a username and password but by a token. Here's how this could work in practice. You will have an action that will take the username and password, validate them and if successful it will return a token. This token could contain the encrypted username. So your javascript will ask the user for his username and password, call the Login method and it could store the token. Then it will use this token on subsequent calls. The API will in turn decrypt it in order to extract the username.
What I would like to know is how this is stored on the client so it can be passed back to the server again for the next call?
Cookies. You will send token as a cookie, and it will be sent automatically when user requests your page.
create a server side session, for the once authorised md5(username) md5(password).
generate an uuid per request, and return it in the response.
basic model is called token exchange and it is reliable (no m.i.t.m) even w/o SSL.

Security in a Javascript based app -refreshing a users hash

I'm developing an hybrid mobile app using HTML/CSS/JS, I'm going over security with login information, the system I have set up creates an hash after a user logs in, this hash has a time limit and is set via localStorage
Essentially, I would have something like this is localstorage:
hash
5f4a09cfec2a6d8f306eecb3844e33e9
hash_expiration
1373012945
password
*encryted user password*
This hash is sent to my server for validation in the header of all my AJAX requests (accompanied by the user id for database matching)
I'm mostly opening this topic to discuss best practices on how to deal with recreating hash keys, I need to figure out a way to refresh a users hash key.
Considering my experience with AJAX and JS is still rather limited, I thought about using the AJAX setup to check for a new hash, like so:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
var time = new Date().getTime(); //unix time
var hash_time = localStorage.getItem("hash_expiration");
if(time>hash_time){
//ajax request to fetch new hash, async: false to make sure this completes before continuing with other AJAX calls
}
}
});
I would send the user id and his encrypted password to verify him and return a new hash.
Should I be sending AJAX requests in the ajaxSetup's beforeSend? How would this conflict with other beforeSends across my application?
Basicallly on the clients side you shouldnt have anything except hash. On the server side this hash must be associated with user it belongs to, expire time and anything else you need.
Send this hash with each request, and on server side validate it. When it expires you have to send (server) appropriate headers like 401 - Unauthorized. Client have to understand that response and try to exchange hash to new one. And finally when client gets new valid hash it can resume sending requests.
... and you shouldnt check expire time at client, this job for server.
thanks.

Categories

Resources