Access to different databases, prevent user errors PHP - javascript

I'm developing a tool that allows user to change database connection.
So user has a select box where he selects the desire database. I have a total of 4 different databases, but structure is the same in all, only data change.
If user works only with 1 open tab, I don't have any kind of problem. But if user works with few tabs , a lot of security problems can happen.
For example:
Tab 1 - User wants edit a row from database 1
In the same time, user change Tab2 to database 3.
So when he is going to save tab 1, probably it would save to database 3, as it was the last change.
I'm saving the selected database on $_SESSION var.
My code right now, I have a form where user selects the database. And on _init.php I have a simple switch case that require a different config.php depending of selected database.
Some ideas how i can prevent errors like this happen?

If you store the active connection in $_SESSION, there can be only one active connection regardless the number of tabs you open in your browser as the session is shared across tabs.
Instead, you can give a counter or a numeric identifier for each connection:
Example:
1 = connection 1
2 = connection 2
...
If the user changes the connection from your select box, use a redirect a send a GET parameter with the connection number.
Example:
if I choose connection 1 the browser redirects to index.php?cn=1
If in another tab I use connection 2, the browser redirects me to index.php?cn=2
You will need always to send your connection id by GET or POST, and receive it instead of looking it in your $_SESSION var.
Hope it helps

If each concurrent tab is permitted to use a separate database connection, then each concurrent tab will need to specify that information when posting requests to the server.
This could be as simple as including the identifier for the database in a hidden field in each form. When the user selects a different database on that page, update that hidden field. (Mostly guessing on the "hidden field" structure here, since we don't know how your forms are laid out. But the point is that the form should contain this value.)
This becomes an overall more RESTful approach, moving away from session state and toward a state transfer driven by the page itself. Which in general is a good thing.
Basically, since the request for the action being performed (saving a record) needs to know where to save it, include that piece of information in the request itself rather than trying to juggle that information server-side.

Quite honestly I would take a different approach to your issue.
Set up sub-domains on your server which point to the same exact web folder and have hard-coded DB connection settings.
db1.example.com
db2.example.com
db3.example.com
db4.example.com
Now the user will have to log into the correct sub-domain in order to perform operations on the desired DB so session_start() will actually create a unique session per sub-domain.
The user will be able to have 4 tabs open without the fear of using the wrong DB.
So your db_config.php file can look like this:
switch($sub_domain)
{
case 'db1.example.com':
// Code for connecting to DB1
break;
case 'db2.example.com':
// Code for connecting to DB2
break;
case 'db3.example.com':
// Code for connecting to DB3
break;
case 'db4.example.com':
// Code for connecting to DB4
break;
}
As for the idea with creating a <select> box for choosing your DB, you can just implement some JS to open a new tab pointing to the correct sub-domain.

Related

how to pop up a Notice Span when user just log in (but not just refresh to the home page)?

I do not know how to detect it is the first time that user login the web.
I thought i should write a pop-up span on the jsp that user firstly saw when he login.but the issue is then he refresh the page,the notic will show again,that is ridiculous.
I need detect if it is first login means to detect if the user JUST LOGIN or NOT REFRESH the page
how and where shall I detect if it is the first time user login ? and then i can make mind if the notice span pop up.
and I think it should use cookies or session,but which one should i use?
Maintain a field in database table that check if it is first login than show a popup and after that change the value of that field so that Popup do not appear next time.
Ex:
if($data['first_login'] == 1)
{
// show popup
}
If you want to show it only to the new user (the time user registers) you can use a table column in database where you can use it to check if the user if logging in for the first time (e.g firtsLogin the column name = 1 ). If he is logging in for the first time you show the pop-up and change the value of the field to 0.
Otherwise if you want to show to users that are logged in to a specific device for the first time you should use cookies.
I suppose that you want to detect the user logging in to your web-site the first time. There are multiple ways that you can do it depending on your desire to spend additional time writing the code, the location of your logging-in logic (client or server side), security that you want to have while proving your users with login functionality. In all cases - you would have to store the data whether the user has logged in for the first time. I think you are seeking a fast solution that will work without a big care for privacy or security as working with client-side cookies isn't the safest way to store data. The alternatives to cookies are web tokens, url query string, server-side sessions and data-base (RDBMS) storage.
Storing and retrieving the data on the client-side using COOKIES. They are the pieces stored in the user's web browser. Cookies were created to help servers remember the data about the user next time he enters the web-site. The most common usages are: to store location (if accepted by user), web-site locale (language in which the user was browsing the site), products added to cart, etc. Following that approach you can create cookie after the user has logged in to your web-site as follows:
This should be run by your JavaScript.
document.cookie = "firstLogin=true";
After having done that, you would have to add JavaScript logic that will hook-up to user's/client's COOKIE data and read up whether he has logged in the first time before.
This would probably look like a simple JavaScript cookie look-up.
var cookieData = document.cookie;
This will return all of your user's cookies that has been previously stored when he visited your web-site. It will return it as a string concatenated with "; ". If we had previously stored only one cookie, we would get firstLogin=true;
In case if you have multiple cookies set before, you would have to parse the cookie string and extract the data either imperatively by plain procedural JavaScript code or by writing the function which will be able to do that repeatedly. Detailed examples of writing such functions could be found here.

Two different templates for user and guest? Or dynamically change the view using a client side variable?

Scenario 1
I have a control panel interface (html/css), which is available to both a registered user and non-registered user. I'll use a client-side ajax just to check if there's a valid user session. If that returns a 200 (ok), I'll then have Angular hide the guest part of the interface, and show the user part. (Basically hides the login form and shows the user options section). If it returns a 400, vice versa.
Scenario 2
I have one control panel interface for guest, and one for a registered user. Upon requesting the control panel partial interface, I would use a server-side router/controller logic that checks for a valid user session. If it is true, response send the controlPanel-user.html. If it is false, response send the controlPanel-guest.html.
I have tried looking for proper theories for this scenario but couldn't find one specific to this situation, maybe someone here is a better Googler than I am.
Note: client side interface updates wouldn't really compromise my system, regardless whether or not the person is able to access the user-version of the html views, they would still be declined access to any API without proper server side authentication.
For my own requirements, I decided on scenario 1. For a light-data front end application, this shouldn't be an issue. Multiple templates would just increase the amount of requests and increase server usage.

Meteor.userId from the client - changing shows user email, correct behavior?

I was looking at another question's answer regarding changing the userId from the client side and following along but not getting expected results;
Meteor.userId is changeable
I followed steps 1 through 5 just fine with no issues but then set the userId() to the user I'd just logged out in a separate browser using Meteor.default_connection.setUserId('usersfjhjdskfh');
Rather than display a spinny in place of the email address since the server shouldn't be returning data, it displayed the actual user's email address I'd used there. (It did not however, bring back the party information and show it on the map).
Is this intended behavior and I missed the point of the last answer given back in December or has something changed? (I'm running Meteor 0.6.2 and both insecure and autopublish were removed from my example)
Im assuming you want to change the user's _id and not change the logged in user via an id. To change the user id you could probably do something like
Meteor.users.update(Meteor.userId(), {$set:{_id:<new Id>}});
Assuming you have the correct permissions in place with Meteor.users.allow. This should change the _id of the current logged in user.
The previous question demonstrated the security when changing local client side Meteor functions and how it would affect the server. The Meteor server doesn't trust anything from the client and double checks it with the allow/deny rules before changing it whatever the data may be for that current logged in user. So the user does need to be logged in to change any data about them on the mongodb database on the server for the allow/deny rules to comitted.

ajax and local/session storage pattern

I'm building a web app that uses ajax to communicate with the server. Basically, the user requests a record, it comes back in json, it's added to the DOM and the user makes changes to it. When the user requests the next record, the current record is stringified and sent back to the server and the following record comes back.
All this works really well.... as long as the user keeps requesting records. However, I am wondering how to handle the situation where the user stops his work: how do I get the last record updated?
I thought of adding the working record to the local storage while he's editing it and at each edit, updating the local storage and if he logs on next time and there's still a record in there, ajax it when he logs on. The problem with his approach is that if another user logs on to the same computer, then when that new user logs on, he's updating the data of another user.
I thought of using the window.unload event also; but that doesn't solve the problem of the user closing his browser before the final update.
What are some good ways to handle this issue. Thanks for your suggestions.
I would consider a 'draft-like' feature. Where you could upload changes after a certain amount of time of no input, for instance, after 15 seconds of no input, push those changes.
If your app requires login, you could key the localStorage using their ids like so:
localStorage.getItem( "user13434" )
would retrieve data for user13434
localStorage.getItem( "user12345" )
would retrieve data for user12345
If the information is sensitive but not too sensitive you could add encryption, but it can be decrypted by experienced users which is why it must not be too sensitive.

Disallow login to website in multiple browsers/tabs at the same time

I have an ajax heavy website that breaks (or shows incorrect data) when users have it open in multiple browser windows at the same time. So I would like to enforce only allowing the user to be logged in to the website in one tab at a time, whether it is on the same computer or even multiple computers.
I am looking for ideas on how to do this.
Is there any JavaScript method to tell if a certain page is already open in another tab?
Perhaps there is another solution that could involve the server side..
For instance, the client could message the server every say, 1 minute. If the server gets messages from a certain users at a frequency higher than one message per minute, it knows that it is open in more than one window or tab. It can then let one of the clients know that it needs to shout an error to the user.
The idea of messaging the server every one minute does not sit that well with me though.
Any other ideas out there?
EDIT: some people are wondering why I have this problem in the first place. Here it goes:
This is a time tracking application that is fully ajax. You can browse/create/delete/modify timers, projects and clients with ajax, without ever leaving the page. If the website is open in multiple tabs, things will get inconsistent very quickly. Errors usually even occur. For instance, user creates a project and then starts a timer in tab1, tab2 will not show these changes. And since it is all ajax, it will not simply sync when the user clicks some button in the second tab.
Having read the update in your question, what I would really suggest is using WebSocket where available, falling back to Flash socket, long polling and forever iframe for older browsers (actually I'd use Socket.IO to make it all easy - you can use a similar abstraction for whatever environment you are using). That way you can make all of your windows and tabs consistent in real time - problem solved.
That having been said if you don't want to do it for some reason (though what you are trying to do would be a perfect application for WebSockets so think about it) you might use sessionStorage and localStorage to distinguish sessions between tabs or windows for the same logged in user, but it is not widely available yet - see the compatibility table so it would be probably easier to go real-time with a socket.io-like solution where there are a lot of fallbacks available than to restrict visitors to one tab - not to mention the user experience.
There's no way to get information about other tabs/windows in javascript (and for good reason).
The best way I can think to do it would be to print a unique identifier (a timestamp should work reasonably well) in the javascript code for each page, and then it periodically ping the server with that unique ID, and associate it on the server with the user. This way if you have more than one ID belonging to a single user being pinged within a given interval, you can send back a response to the page to warn the user that having multiple tabs open will result in unexpected behavior.
(Like Caspar said above though, you should really figure out why the unexpected behavior is happening and fix that rather than force the user to act a certain way)
This is pretty lo-fi, but I think the simplicity may make it work: you could try having the login open the session in a named window (or change the name of the current window). Then, on load inside the application, check to see if the browser window name is the one you've allowed them to use; if not, pop up an alert, close the window, focus on the named window, if still there. (If not there--i.e., they've already closed the other window--you could let this one stay open, and change the name to the correct name.)
So you're essentially using window.name and window.opener. Rough idea, but an idea.
I have a similar situation and the solution I use is:
on server: at every login you create an unique ID, save it (ex. database) and return it to client.
on client: on every transaction you send this ID to server as a parameter.
on server: if saved and received ID match then allow the request to execute if not refuse it with an error code.
on client: if transaction failed with specific code then you know that "ID" verification failed and you logout user.
So in this way if the same credentials will be used again in any other tab, browser, PC, country,... the old tab will logout user on next transaction request. Or in other words limiting only one opened page per user on the whole world.
Edit:
As I have stopped using html requests for any data communication and use websockets, I register user on server and if same user wants to login from some other location I close the previously used socket (the page automatically logs out).
In this way I also have a way to trigger full page reloads from server in case admin does something that influences users.
Simply use cookies.
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}

Categories

Resources