How to clear data after logout - javascript

I do use hawtio 1.5.5 for my website. I have an issue with user's credentials. User's name and password are stored in browser. When user performs logout, I would like to be this data wiped. I did some investigation, and there is called method doLogout() in index.html file (hawtio-web). I know these credentials are stored in localStorage but I don't know, which is the right spot to wipe them. Thanks.

Due to username and password being stored in browser instead of the localStorage cache for security reason, you need to use the browser feature to clean up the browser cache. You should be able to clear the cache by restarting the browser or use private browsing like Incognito.

I have found solution. You have to inject service into your plugin
module.run(..., preLogoutTasks) {
// your code
preLogoutTasks.addTask("clearCredentials", () => {
localStorage.removeItem('userName');
localStorage.removeItem('password');
});
}

Related

Google oauth session lost after page reload (javascript)

I recently moved from the deprecated gapi.auth2 to the new Google Identity Services, using the javascript client library, and noticed a big difference: if someone signs in, and then reloads the page, the session is lost, and has to sign in again, every time the page is loaded. This was not the case with the deprecated library.
The problem can be easily reproduced with the Calendar API example.
Is there any configuration option to keep the session persistent? Or do I need to store the access tokens somehow? I could not find anything relevant in the official docs.
UPDATE:
The migration guide states the following:
Previously, Google Sign-In helped you to manage user signed-in status using:
Callback handlers for Monitoring the user's session state.
Listeners for events and changes to signed-in status for a user's Google Account.
You are responsible for managing sign-in state and user sessions to your web app.
However there's absolutely no information on what needs to be done.
UPDATE 2
To be more specific, the actual issue is not making the session persistent. Managing the sign in state and user session is something I can solve.
The real problem is the access token used to call the Google APIs.
As mentioned in the comments, the access tokens are 1) short lived 2) are not stored anywhere, so even if not expired, they do not persist between page reloads.
Google provides the requestAccessToken method for this, however even if I specify prompt: '', it opens the sign-in popup. If I also specify the hint option with the signed in user's email address, than the popup opens, displays a loading animation briefly, and closes without user interaction. I could live with this, however this only works if triggered by a user interaction, otherwise the browser blocks the popup window, meaning that I cannot renew the token without user interaction, e.g. on page load. Any tips to solve this?
I faced all the same issues you described in your question.
In order to help:
Google 3P Authorization JavaScript Library: in this link we can check all the methods the new library has (it does not refresh token, etc..)
This doc says the library won't control the cookies to keep the state anymore.
Solution
Firstly I need to thanks #Sam O'Riil answer.
As Sam described: "you can somehow save access token and use it to speed-up things after page reload."
Given the the Google's exampe, we should call initTokenClient in order to configure the Google Auth and the requestAccessToken to popup the auth:
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: 'YOUR_CLIENT_ID',
scope: 'https://www.googleapis.com/auth/calendar.readonly',
prompt: 'consent',
callback: tokenCallback
});
tokenClient.requestAccessToken({prompt: ''})
In your tokenCallback you can save the credentials you get somehow, e.g.:
const tokenCallback(credentials) => {
// save here the credentials using localStorage or cookies or whatever you want to.
}
Finally, when you restart/reload your application and you initialize the gapi.server again, you only need to get the credentials again and set token to gapi, like:
gapi.load('client', function() {
gapi.client.init({}).then(function() {
let credentials = // get your credentials from where you saved it
credentials = JSON.parse(credentials); // parse it if you got it as string
gapi.client.setToken(credentials);
... continue you app ...
}).catch(function(err) {
// do catch...
});
});
Doing it, your application will work after the reload. I know it could not be the best solution, but seeing what you have and the library offers, I think that's you can do.
p.s.: the token expires after 1 hour and there is no refresh token (using the implicit flow) so, you will have to ask the user to sign-in again.

Msal v2 library, handle logout for SSO (Node.js and Vue.js)

The problem:
Using msal v2, when user log in to the app via Microsoft account, it saves params to the sessionStorage and it all works great, problem happens when user logs out in the Office.com or any other site using Microsoft SSO. Since the data is still saved in sessionStorage (tried same with localStorage) the AcquireSilentToken(...) resolves with the cached data, even though the user has been logged out.
Tried How to know if a given user is already logged in with MSAL?
It suggest using AcquireSilentToken(...) but it resolves promise without error since it checks sessionStorage.
My case:
In the middleware I would like to do:
const promise = msalInstance.acquireTokenSilent(graphScopes);
promise.then(resp=>{
//User is logged continue next();
}).catch(error=>{
//User is not logged in clear sessionStorage/localStorage and next('/login')
});
So if anyone can help me with the way of asking the thru msal if user has logged out. I would really appreciate it.
This behavior is by design. AAD services uses cookies to remember who you are and to automatically sign you in.
The sign-out process for services forces the session cookies to expire. These session cookies are used to maintain your sign-in state when you use these services. However, because the web browser is still running and may not be updated to handle cookies correctly, you may have a cookie that is not updated to expire and finish the sign-out process. By default, these cookies are valid for eight hours or are set to expire when you close all web browsers.
const promise = msalInstance.acquireTokenSilent(graphScopes);
promise.then(resp=>{
const logoutRequest = {
account: instance.getAccountByHomeId(homeAccountId),
postLogoutRedirectUri: "your_app_logout_redirect_uri"
}
instance.logoutRedirect(logoutRequest);
}).catch(error=>{
//User is not logged in clear sessionStorage/localStorage and next('/login')
});
Also this is a known issue.

Angularjs: Why page refresh destroy the values of $rootScope?

In my local route http://localhost:9000/#/deviceDetail/ I have a controller that manage that view. Before going to that view I set some variables to the $rootScope (for example $rootScope.dashboards).
Once on that view I have acces to dashboards property, but when I refresh the page with F5 key for example the property dashboards is lost.
I tried to save the $rootScope on the localStorage variable but I got circular reference problems with the JSON.stringify method.
Any tip to manage that?
AngularJS is a JavaScript framework, everything is stored in memory heap and the heap is starts when you open a page and it's destroyed after you close it. In this context, browser refresh is like closing and re-opening the page.
To keep the value after refresh, you should store it in a cookie, for this you use for example $cookies or sessionStorage / localStorage as recommended by M K.
I tried to store auth token using cookies following the article at Getting started with AngularJS and ASP.NET MVC - The long awaited Part Three. But the cookies is destroyed whenever I hit F5 or refresh the Chrome browser.
That article says ngCookies helps to deal with page refresh to maintain token for page refresh. And I had thought it did and I did not know ngCookies killed me. It was destroyed if page is refresh! after hours to research online I see this article helps me.
According to M K, I used localStorage (or sessionStorage) helped me to get rid of the headache of cookies. Using cookies to store authentication token or something else is a bad idea. I ran into that problem and I got lost (did not know the bug coming from "using cookies") as the above article mentioned/confirmed. So, it was a bug in that article.
Thank you million times, M K.
Use localStorage and $stateChangerStart check if you using ui.route
something like this
$rootScope.$on('$stateChangeStart', function(event, toState) {
// Grab the user from local storage and parse it to an object
var user = JSON.parse(localStorage.getItem('user'));
if(user) {
$rootScope.currentUser = user;
}
});

Unable to retrieve current Parse user

I'm logging into my Parse app through the JavaScript SDK, it appears to be storing cookies however once it progresses to the next page it always displays the current user as being null despite having logged in successfully. I've cleared the cookies and it appears to be storing the cookies after login fine. This is the code I'm using however no matter what I seem to do it just won't collect the current user. Does anyone know if there's an issue with this or if there's something extra I have to do for it to be able to recall the cookie? If it's relevant the two site are on subdomains, could this be the problem?
Parse.initialize(JSDK, API);
var currentUser = Parse.User.current();
var currentUsername = currentUser.get('username');
alert(currentUsername);
You should use the getUsername() method instead of get('username').

how to backup html 5 local storage data

am developing an offline application using html 5 and java script libraries.
my system is for offline data collection. data is stored in the local machine in text format before being synced to the server later on.
before i had developed the same application but using silver light which was easy to back up data for security reasons using
any idea on how i can backup the text files and zip them to my hard disk will be highly appreciated.
i have not found a solid answer through my research so far
thanks in advance.
One "solution" I can think of is, before the user closes the app using the close button, you could detect the window.onbeforeunload event and send the data to your server to save. But this is not reliable because there might be cases when the browser may crash or the user might forcefully close the browser application. Or worst of all if you are constantly using localStorage and by chance the user clears the browsing data (which includes localStorage) it will be gone.
But assuming you have the data at hand, you can send it to the server using POST and make a script to save it in the disk. Obviously, you might want to impose limitation on file size and enforce other security restrictions.
WARNING: PHP
Lets say you have a folder created for each unique user and all files in each user's folder are guaranteed to be named uniquely. In PHP you can use functions like file_put_contents() to save a text file, you can also easily ZIP it using the ZipArchive class.
It's not recommended to store this kind of data directly to the drive. I would highly recommend you to put the localStorage data in some kind of database and do a database backup instead of backing up individual user's data.
As other users have pointed it out you could also look at the HTML5 File API. Examples here.
I found a solution on how to backup local storage files and zip them to my local drive without any server code. Below is a code snippet that works fine for me at least for now. Any modifications and enhancements will be highly appreciated.
if (localStorageKeys.length > 0) {
for (var i = 0; i < localStorageKeys.length; i++) {
var key = localStorageKeys[i];
if (key.search(_instrumentId) != -1) {
keysToBackup.push(key);
var data = localStorage.getItem(localStorageKeys[i]);
zip.file(localStorageKeys[i].slice(0, -19) + ".txt", data);
}
else {
keysNotToBackup.push(key);
}
var datafile = document.getElementById('backupData');
datafile.download = formName + "_Data.zip";
datafile.href = window.URL.createObjectURL(zip.generate({ type: "blob" }));
}
}
I found a solution for backup and restoring the local storage of websites.
You can use this repository:
https://github.com/todvora/localstorage-backup
This is the live app:
https://www.tomas-dvorak.cz/localstorage-backup/
Usage:
In the live app, Drag the buttons and drop them into your bookmarks. They are so-called bookmarklets.
Open the site you want to backup/restore and click on this bookmarked button.

Categories

Resources