Sessions in JavaScript or Global variables - javascript

What do you recommend to use as "website sessions settings": I have few notifications (about using my web site functions) and I show them to user when he open the page first time. However, I do not want to show him everytime that he navigates the page.
My idea is to use some variable that is valid through session on my web site and terminates when user leaves it.
I am thinking of using php server settings and then use AJAX to set them, but it looks a little complicated. What do you think? Client session settings (if such exist) or global variables, or something else?

There are many ways to do so.
You can achieve that using HTML and Javascript using a cookie. (Take a look at [jQuery Cookie])1.
Check for the cookie when the user opens the page; if not found, show him the message and create the cookie.

Related

How can I 'lock' a page behind a log-in screen in jQuery/Bootstrap/JS?

I've been building a web app using Google's Firebase as a backend (for those who don't know, it's a Realtime database; any changes in data are reflected instantly and updated), there's other people working on the Android app with it so there's no other option (plus it's kinda cool). I was surprised that I have yet to write a single line of php or any server-side code. Anyway, jQuery is working perfectly fine for login and stuff.
Now I'm going to be making an admin page (with a separate login from the main users login). It'll be accessed in a completely separate way (by opening something like /admin.html). So the login can't be put on a separate page so people don't 'accidentally' access the admin panel by writing /admin.html in the address bar.
So I want to stop the admin page from completely loading until I've received confirmation from Firebase that the credentials are correct. So how can I achieve this knowing that both the login and the whole admin page needs to be in the same file. I'm positive this can be achieved with simple jQuery + Bootstrap but I'm not really sure how. Can anyone please point me in the right direction. Thanks in advance!
I have googled it of course but maybe my wording is off? :P
If I'm understanding your question correctly, your problem is that you need to create two separate views in a single file, and redirect to one or to another depending on your user "session", however, as all your code is in client, you don't have a "session" system operative.
Ok, there are several options you can take. I like the idea of using LocalStorage to store the user session.
When /admin.html is requested, your code checks for a valid session object (keep in mind that you'll need to define that session object) in the LocalStorage. If there is a valid object, you render the admin area, if there isn't any, you render the login area.
When someone sends username/pass to the database and you receive a valid response, you create a session object, store it in the LocalStorage and reload the page.
Keep in mind that you'll need to create a mechanism to make sessions die and a log off view.
For the dying sessions, as an idea, you can store the creation time and a expiration time in the session object. Each time a "session protected" page is served, when you check that the session object exist, you update it's expiration date a fixed amount (20 minutes plus current time, for example).
So, when you check if exists a valid session, you also check that it's expiration date has not due, and if it's, you delete the object.

How to manage server user session within client side single page app

I've been fumbling around with different client side technologies, like AngularJS, EmberJS, even trying to use straight JQuery and figure out how to use ReactJS with it. That aside, my goal is to build a single page app using json in between the client and a Java Jersey 2 jax-rs back end api.
I have two stumbling blocks right now. Some info though..I am deploying my app as a WAR file in Jetty. My back end is java based. I am using only jquery in the client side as of now.
My main stumbling block is how to handle login, logout and session management. With an rest API and using ajax, I have login working, including it setting a cookie. My concern however is with a single page app, there is just the one index page, and if the user closes the browser, then reopens it to the index page while the cookie/session is still good, the user should be logged in, not see the outside (not logged in) page. I am unsure how to handle this, whether it be a jsp page, index.html with some templating library, etc. With JSP I can insert some scriplet code (against my better judgment). In the old days I'd include a header that would check for request.getSession().getAttribute("user") and if it was there..the user was logged in and using scriplet if() code I'd display a logged in header, instead of the non-logged in header. But I am in the belief there has got to be a better way to do this with todays client side JS frameworks.
The other stumbling block is the navigation and dynamic aspects. For example, when I was messing around with angular js, it was easy enough to use Welcome {{name}} and within the scope replace name with a json response value for the logged in user. In my current situation, I am not exactly sure how to best go about displaying dynamic bits like this with pure jquery other than using some sort of $("#elem-id").innerHtml="..." code within the response success method of an ajax call. As well, I am not quite sure how to handle navigation to different pages. My logged in site will have some drop down menus or links that will replace the content area with different varying amounts of content.
So first, what are some ways in a SPA to handle user sessions, in the case of a page reload, or close/crash browser restart.. to ensure the user is still logged in and direct them to the right page? Second, what sort of templating and routing/navigation options exist that don't require me to put a huge ton of code in my one index.jsp page?
Thank you.
If you're having a REST API as the back end, then you must have implemented oAuth as an authentication mechanism. That is, when your user logs in, using a username and a password, you exchange that data with an authentication token. This authentication token is sent your server with each and every API call and your backend validates this token before servicing the request. Clear so far?
What you could do is, when you obtain the access token, you can also obtain the access token expiration time from the server and store that data in your client side app. In localStorage maybe? And when your user closes the browser and reopens again, you can first check whether such access token is available (and not expired) before asking the user to log in. This should solve your first problem.
Secondly, if you're looking for a lightweight routing option, I recommend director.
I am building a similar application. OAuth is not mandatory. You can have normal sessions etc by hitting the jersey login endpoint and setting a session and a cookie "keepme" with the session if user wants to be persistently logged in. You can then have a jersey AuthFilter for example check if either there is a cookie with a valid session or an active session and keep the user logged in.
Your frontend application should have no say over this, just communicate with the server and if it doesn't get unauthorized access (from the AuthFilter) then continues otherwise it displays the login page.

is it possible to run javascript one time only?

Hello I'm looking for one time clicking solution , i want javascript to load only one time in life for every member of my website
when member of my website will interact with javascript for example by clicking yes or no in browser i want this script not to load again in his browser
This is something that's best to do on the server side. For example, if you have a database field for users that is something like "Last Login" and you only load the script if that value is null.
It depends on the info you have on your users. This is not advisable to solve in js.
I would use cookies, however clunky that may seem. Create a cookie when he presses the button in the form and just test for that cookie when he visits each page. Do remember that people with cookies turned off will keep receiving it though.
You can use cookies or local/session Storage for this...something along these lines
if(!localStorage.getItem('isNewUser')) {
localStorage.setItem('isNewUser', false);
alert('new user');
//insert whatever you want to do the first time a user visits your page
}
There is no reliable way to do what you are asking. How are you going to uniquely identify your users? What's gonna happen if your users access the page from within another browser, another IP etc.?
The only somewhat reliable way of doing it is through a registration system which would require your users to log in before using your one-time functionality. Once they log in the functionality (button) should only be available through a server-side request or an asynchronous (ajax) request through JavaScript.
Even then its usually a lost battle to prevent people from creating multiple accounts etc.

How to show welcome message only onetime when visit the home page?

I am working with rails applications since some couple of months. Now I am supposed to add a feature to show the welcome message for the first time when user visits the site home page, and not for second time even the user reloads the same page.
How can I achieve this by using jQuery or Javascript?
Simply set a cookie and check for it. If you use one of the usual jQuery cookie plug-ins, then put this script at the bottom of the page:
(function($) {
if (!$.cookie("yourcookiename")) {
$("selector for the message").show();
$.cookie("yourcookiename", "x");
}
})(jQuery);
That looks for the cookie and, if not found, shows content that you've defaulted to being hidden.
It's not perfect, because the user can clear cookies, but it's usually good enough.
Not sure how you define first time, if you just mean registered user then you can record something on your server side.
If you mean anyone, you need firstly define who is this guy, writing a cookie to client browser might work but if they change a browser your message will show up again, record IP on server side might work but if some people sharing internet connection then only one person can really see it in that sub net.
Most of the case using cookie should be fine, or to with HTML5 local storage

Session null after window.open in minimal SharePoint page

I'm storing a token in a session variable. I launch a report that needs this token in a new ASPX page by using the javascript windows.open function. When this new page loads the HttpContext.Current.Session is null.
I have gotten around this by passing the token in the query string but activity in this window needs to keep the session of the parent window active and I'm not sure what the session object being null means for this scenario.
Any idea why the HttpContext.Current.Session object would be null by using window.open from javascript?
EDIT: I will add that this is a basic System.Web.UI.Page stored in a SharePoint library and the window.open function is called from a webpart. I'm thinking that this page may need to inherit from a base class to share the right context.
UPDATE: I've narrowed down that this is related to SharePoint. I moved the code that accesses the Session object into a web part. The web part works fine if put in a standard web part page but I have it added to a minimal page that only contains a ScriptManager, SPWebPartManager and a WebPartZone. The code runs but the session object is again null. My minimal page is missing something that makes the Session object available.
SOLVED: My minimal ASPX page needed to implement the IRequiresSessionState interface. After that the Session object is there.
I'm going to give the cred to Andrey since he offered the most useful information.
Technically, it's a different connection to the web site, that's why it's a different session. It's probably better to use Application cache instead of session if you want different windows to utilize the same session storage.
UPDATE:
What you can do if you want to stick to using session state, is to write the session ID to a persistent cookie, this way the child window's call to the server will carry it along and you can retrieve SessionID from that cookie. IMPORTANT: Make sure you encrypt session ID ebfore putting into teh cookie to avoid session hijacking.
window.open() should keep the same session id
window.open() clears session
make sure that the url you pass to the open() method is relative or the same domain name
I assume you are using IIS 6 or later.
Lets say you have 2 different websites:
http://site1.yourdomain.com
http://site2.yourdomain.com
2 things can happen
Both sites run under the same Application Pool: Session should be the same for both sites.
note: Internet Explorer prior to version 8 gets assigned different session if the newest window is not originated from the currently open window. Starting on version 8 all windows accessing the same Application Pool share the same version regardless the origin of the window.
Sites run under different Application Pools in IIS: Not even dreaming you can share the same session for both windows
If the website is the same for both windows you shouldn't have any problem sharing session between two windows, even with any version of Internet Explorer since the second window is originating from the first one by calling window.open() method.

Categories

Resources