setting up session variable using only javascript - javascript

I am working on setting up a session variable only using JavaScript.
The requirement goes this way, A user logs into my application using SFTP client with UN/key, if I store the UN in a ctx variable its getting cleared after login process. I need the user name value to transfer any file to the back-end using my application. for this I am planning on using a session variable in JavaScript so that the UN will be saved as long as the session is established. I don't see any example with just JavaScript being used. is this possible ? I am not a JavaScript developer.
My application only supports XLS, XML and JavaScript.
I am thinking something like
this is just sudo code.
function username(UNvalue) {
var sessionun;
session.setvalue(sessionun) = UNvalue;
return sessionun;
}
Thanks,
Aswin.

Related

Embeddable js interpreter for user's code?

Imagine website, where user can generate content via js.
For example.
User clicks button
It requests our api (not user's api)
Api returns object with specific fields.
We show select with user's defined options generated by user's code or some calculated result based on data we sent.
The idea is to give user an ability to edit visible content (using our structures, we know beforehand which fields in returned object do what things).
First solution "developed" in 5 minutes.
Users clicks button
It send all required data as context to our api.
We fetch from database user's defined code
// here is the code which we write (not user) and we know this code is safe
const APP_CONTEXT = parseInput(); // this can be parameters from command line
const ourLibrary = require('ourLibrary');
// APP_CONTEXT is variable which contains data from frontend. We control data inside APP_CONTEXT, user can not write to it
// here is user defined code
const someVar = APP_CONTEXT['fieldDescribedInOurDocumentation'];
const anotherVar = APP_CONTEXT['anotherFieldFromDocumentation'];
ourLibrary.sendToFrontend(someVar + anotherVar);
In this very simple example once user clicked on button, we sent api request to our api, user's code has been executed, we show result of execution. ourLibrary abstract the way the handling is completed.
The main problem as I think is the security. I think about using restricted nodejs process. No network access, no file system access.
Is it possible to deny any import/require in nodejs process? I want to let user only call all builtin js function (Math.min, Math.max, new Date(), +, -), declare functions and so on. So it will work like a sophisticated calculator. And also we should have an ability to send it back to frontend. For example, via rabbitmq + nodejs + websockets. We can use simple console.log if former is the problem.
Some possible solution (not secure, of course) using nodejs interpreter. We execute interpreter every time when action is required.
const APP_CONTEXT = parseInput();
const ourLibrary = require('ourLibrary');
const usersCode = getUsersCode();
eval(usersCode);
Inside usersCode they use ourLibrary.sendToFrontend to produce the result. But this solution allows user to use any builtin nodejs functions, like const fs = require('fs'). Of course access will be restricted using linux system (selinux or similar) but can I configure/setup nodejs to run as simple js interpreter? May be there is some other js interpreter exists which is safe to use? Safe means: only arithmetic, Date function, Math functions and so on. No filesystem access, no network access.

How to pass access token from php implemented js script to localStorage of extension

I am making a browser extension which uses the Facebook php and js SDK.
I need to get the user access token but I cannot use the js SDK locally (as facebook does not offer to connect from an extension directly) so I have to implement the js sdk into a php that is on my server (I cannot use the php sdk here as it does not allow automatic login via cookies but I need this).
So is there a safe way to transfer the access token from the js script part in my php to my localStorage? I could imagine using something like parent.postMessage(token, chrome://chrome_extension_id), is this safe? Or is there a direct way to safe something to the localStorage of the extension?
Another way would be to use the Facebook PHP sdk JavaScriptHelper developers.facebook.com
I already tried this code:
$fb = new Facebook\Facebook([/*...*/]);
$jsHelper = $fb->getJavaScriptHelper();
$access_token = $jsHelper->getAccessToken();
$_SESSION['fb_user_token'] = (string) $access_token;
/*...*/
$response = $fb->get("/?id=$url&fields=share{comment_count}", $_SESSION['_fb_user_token']);
But it does not work, as an object is passed to the get method at the end and not a string. So I think I made a mistake getting the string from the token object.
Ok, I got a solution by using the 2nd option in my original post (using the JavaScriptHelper function).
$access_token->getValue();
This was all I had to do with the access token object to get the access token string.
By the way, this was really helpful to get the available methods of the access token object:
array get_class_methods ( mixed $class_name )

HTML form connecting to local H2 database

I am wanting to create an HTML form for entering/viewing data on localhost.
The data is in a file based H2 database on localhost.
Ideally, I'd like to use only client-side javascript and HTML so that the user does not need to run a local web server.
I have found some information here on how to connect: http://blog.jooq.org/2014/06/06/java-8-friday-javascript-goes-sql-with-nashorn-and-jooq/
but am wondering about the next step of how to integrate the connection/SQL queries into the web form.
I am aware that the use of javascript to connect to a database is usually frowned upon for security reasons, but for this use-case, it will only be accessing data on localhost.
Also, are there any recommended javascript libraries that would make this easier?
var someDatabaseFun = function() {
var Properties = Java.type("java.util.Properties");
var Driver = Java.type("org.h2.Driver"); //JDBC interface for H2
var driver = new Driver();
var properties = new Properties();
properties.setProperty("user", ""); // database username
properties.setProperty("password", ""); // database password
try {
var conn = driver.connect(
"jdbc:h2:~/db", properties); // connect to database
// Database code here
}
finally {
try {
if (conn) conn.close();
} catch (e) {}
}
}
someDatabaseFun();
Connecting to a java based database like H2 is not easy with a pure javascript solution (despite the fact that H2 exposes itself via JDBC and HTML).
However, there are certainly ways of working with databases in pure-html. These essentially leverage indexeddb and websql storage mechanisms built into the browser.
an incomplete list of javascript libraries are discussed here http://nolanlawson.com/2015/09/29/indexeddb-websql-localstorage-what-blocks-the-dom/:
Lawnchair
PouchDB
LocalForage
Dexie
Lovefield
LokiJS
AlaSQL
MakeDrive
ForerunnerDB
YDN-DB
These are in addition to working with pure WebSQL. For my purposes, pure WebSQL was the best solution, for example: http://www.tutorialspoint.com/html5/html5_web_sql.htm
I am wiling to lose IE/Firefox compatibility.
But there are also options of shiming WebSQL to IndexedDB, for example:
http://nparashuram.com/IndexedDBShim/
So, in summary, you can work with SQL client side with pure javascript but H2 is not the best DB to do this with. WebSQL has the advantage that the database is actually stored by the browser as an SQLite file (file based storage is important to my application)
I'd like to use only client-side javascript and HTML
Where is your JVM going to run? H2 is a Java database. It runs inside a JVM.
Are you embedding it in a Java Applet?
Are you using Java Web Start?
They would be the only ways I know of to run Java on the client's machine.
Anything else has to connect to a server.
If I were tasked with implementing this, I would run H2 embedded in a Java Applet, then have my javascript talk to the Applet. It's very clunky though, and only keeps data in memory. Why not just keep all your data in javascript arrays?

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.

Using ActiveX to get username

I'm working with an old intranet site written in classic ASP. I'm trying to retrieve their username they logged into their machine with. Each user is logged into AD, but I can't retrieve it from the server since the intranet site does not use AD.
I was told I could use ActiveX in order to retrieve it. I did some research and I found the following code (javascript):
var wshshell = new ActiveXObject("WScript.shell");
var username = wshshell.ExpandEnvironmentalStrings("%username%");
Currently I'm using IE8 and I get an "Automation server can't create object" error on that first line.
1) Any ideas why I'm getting the error?
2) Is there a better way to be doing this given my limitations?
If this is done client-side, then you must have the user add the site to the Trusted Sites zone and set the security level to the lowest. Line 1 should work server-side, but I don't think line 2 is right.
Try this
var net = new ActiveXObject ( "WScript.NetWork" );
var username = net.UserName;
Basically, its impossible to retrieve client's Windows machine information using Javascript.
Because its scope is upto browser only.
For doing so you need to create COM object or say an Activex object, and using ASPX page you need to deploy it on Client's system at the very first time your page is accessed from a browser.
Now, ActiveX object has a featured to interact using javascript. You have to access the COM object or the class and function of the COM, which further interact with the system classes to get the system Information. i.e logged in client's windows user information.
var net = new ActiveXObject ( "WScript.NetWork" );
var username = net.UserName;
Above code is also initializing a COM object, if it is not deployed to your client system this script won't work.

Categories

Resources