Classic ASP + Javascript - trying to avoid sessions - javascript

please be patient with my poor english...
I started working on a classic ASP application developed by others. Lots and lots of pages, not well organized : the typical situation you have to face when you come to an existing website.
We now have a big problem : lots of log outs due to losts of session variables.
So I am trying to write a script to avoid sessions.
Luckily, there is a common page which is included in every page of the application.
My first step will be the transition from now to the future : the application is already in production so first I will leave the session variables as is and add my script at the top of the included page.
The ASP script defines the names of the session variables which are critical, retrieves their values on the request.form collection and add the values in the session.contents collection.
Then the Javascript script create hidden inputs containing the values on the page load, in order to post them to the next page (it will fill existing forms and create new form when the user clicks on a link). To be sure there are no conflicts, a specific word is used for every name : name="specific_myName"
Please can somebody tell me if this is a good approach ? If so the script will have to be improved...
Thank you
Below the script :
<%
Class ConnexionState
' #### Connexion
Private m_dict
Private m_keys
Private m_Javascript
Private m_specific
Private m_deconnection
Public Property Get GetDict()
Set GetDict = m_dict
End Property
Public Sub Class_Initialize()
' Test if connexion is allowed
TestConnexion
' Initilize datas + retrieve "session" variables
m_specific = "Connexion_"
Init
End Sub
Public Sub Class_Terminate()
Set m_dict = Nothing
End Sub
Private Sub TestConnexion()
' One test may be : do we come from a page of the same application ?
If Instr(1,Request.ServerVariables("HTTP_REFERER"),Request.ServerVariables("HTTP_HOST"),1) = 0 And Request.ServerVariables("HTTP_REFERER") <> "" Then
EndConnexion
End If
End Sub
Private Sub Validate(key_)
' Test if variables are well formatted : for example check if we get an integer if we expect an integer
m_deconnection = false
On Error Resume Next
Select Case key_
' Expecting an integer
'Case "key_integer_1","key_integer_2"...
' m_dict(key_) = CStr(CInt(m_dict(key_)))
' Expecting a string which lenght is 6
Case "key_string_1"
If m_dict(key_) <> "" And Len(m_dict(key_)) <> 6 Then m_deconnection = True
Case Else
' Avoid values which length is too high
If Len(m_dict(key_)) > 25 Then m_deconnection = True
End Select
' Avoid ' character
If InStr(m_dict(key_),"'") > 0 Then m_deconnection = True
' If we got an error or one variable is not well formatted
If Err.Number > 0 Or m_deconnection = True Then
EndConnexion
End If
On Error Goto 0
End Sub
Private Sub EndConnexion()
response.end
End Sub
Private Sub Init()
Dim i
Set m_dict = Server.CreateObject("Scripting.Dictionary")
' Names of the "session" variables
' m_keys = Array( names_ )
' We do some stuff on each key
For Each i In m_keys
SetValue(i)
Next
End Sub
Public Function ToString()
' Pass a string (will be used in the javascript below)
Dim i
ToString = ""
For Each i In m_dict.keys
If InStr(m_dict(i),"=") = 0 then
ToString = ToString & i & "=" & m_dict(i) & "&"
End if
Next
ToString = ToString & "specific=" & m_specific & "&"
If ToString <> "" then
ToString = Left(ToString,Len(ToString)-1)
End If
End Function
Private Sub SetValue(key_)
' Retrieve values from request.form collection
m_dict(key_) = request.form(m_specific & key_)
' If not in request.form, we try in session.contents
If m_dict(key_) = "" Then
m_dict(key_) = Session(key_)
End If
' Test if value is well formatted
Validate(key_)
' Update session
session(key_) = m_dict(key_)
End Sub
End Class
Dim Connexion
Set Connexion = New ConnexionState
%>
<script type="text/javascript">
(function() {
var Connexion = (function() {
function init(args_) {
// Translate "session" variables from a string passed in argument to object properties
var params_ = args_[0],
p;
for (var i in params_.split("&")) {
try {
this[params_.split("&")[i].split("=")[0]] = params_.split("&")[i].split("=")[1];
}
catch (e) {
// do something
}
}
// Load click event listener
load.call(this);
return;
}
function load() {
// What happens on page load
var that = this;
window.onload = function() {
document.onclick = function(event) {
event = event || window.event;
var t = event.target || event.srcElement,
p,
input;
// Click on a link -> we create a form and post values to the next page
if (t.tagName && t.tagName.toLowerCase() === "a" && (typeof t.onclick).toLowerCase() !== "function") {
send.call(that,t.href,t.target);
return false;
}
// Click on an input button -> we get the form containing th input and add hidden inputs containing connexion parameters inside it
if (t.tagName && t.tagName.toLowerCase() === "input") {
p = t;
while (p != null) {
if (p.tagName && p.tagName.toLowerCase() === "form") {
appendInputs.call(that,p,true);
return;
}
p = p.parentNode;
}
return;
}
return;
}
// If there is any form inside th page we add hidden inputs containing connexion parameters inside it
var formsInDocument = document.getElementsByTagName("form");
for (var i=0;i<formsInDocument.length ;i++ ) {
appendInputs.call(that,formsInDocument[i],true);
}
}
}
function send(action_,target_) {
// Create a form and post connexion parameters to the next page
var form = document.createElement("form"),
body;
form.name = "Connexion";
if (action_) { form.action = action_; }
if (target_) { form.target = target_; }
form.method = "post";
// Add hidden inputs containing connexion parameters
appendInputs.call(this,form);
// If body tag does not exist we create it
if (!document.getElementsByTagName("body")[0]) {
body = document.createElement("body");
document.documentElement.appendChild(body);
body.appendChild(form);
} else {
document.getElementsByTagName("body")[0].appendChild(form);
}
form.submit();
return false;
}
function appendInputs(form_,testExists_) {
// Add hidden inputs containing connexion parameters inside a form
var input;
for (var p in this) {
if (this.hasOwnProperty(p) && (typeof this[p]).toLowerCase() != "function" && p.toLowerCase() != "specific") {
if ((testExists_ && !document.getElementsByName(p)[0]) || !testExists_) {
input = document.createElement("input");
input.type = "hidden";
input.name = this["specific"] + p;
input.value = this[p];
form_.appendChild(input);
console.log(" " + input.name + " - " + input.value);
}
}
}
return;
}
return {
init: init
}
})();
Connexion.init(arguments);
})("<%=Connexion.ToString()%>");
</script>

Related

How to use external JavaScript script in Angular that is not available as a node module

I am trying to integrate a payment system into my Ionic/Angular android app and I cannot figure out how to use the JavaScript script they sent me that is supposed to be used to create the payment frame.
I have linked the js file in the angular.json file. But what I cannot figure out is how to actually use the script in my component.
I have already tried adding a typings.d.ts to the src folder. In which I added:
declare let ozow: any;
ozow being the function that is being exported, I then proceeded to add:
import * as variable from ozow
but this also did not work.
I also tried adding the following to my component:
declare let ozow:any
but that also did not work.
Here is the javascript file I am trying to make use of in my angular project:
var ozow = (function(e, t, a) {
var n = e.addEventListener ? "addEventListener" : "attachEvent",
r = "/payment/iframeredirect?redirecturl=",
o = "Payment could not be completed, please contact the site administrator";
function l(e) {
return (
e.CancelUrl &&
e.CancelUrl.length > 0 &&
(e.CancelUrl = r + encodeURI(e.CancelUrl)),
e.ErrorUrl &&
e.ErrorUrl.length > 0 &&
(e.ErrorUrl = r + encodeURI(e.ErrorUrl)),
e.SuccessUrl &&
e.SuccessUrl.length > 0 &&
(e.SuccessUrl = r + encodeURI(e.SuccessUrl)),
e
);
}
return (
(0, e[n])(
"attachEvent" == n ? "onmessage" : "message",
function(a) {
if (
a.data &&
a.data.event &&
("ozowMessage" == a.data.event || "ozowResize" == a.data.event)
)
if ("ozowMessage" == a.data.event) {
var n = Object.keys(a.data.postData)
.map(function(e) {
return (
encodeURIComponent(e) +
"=" +
encodeURIComponent(a.data.postData[e])
);
})
.join("&");
e.location =
a.data.url +
(-1 == a.data.url.indexOf("?") ? "?" : "&") +
(n || {});
} else
"ozowResize" == a.data.event &&
(t.getElementById("paymentFrame").style.height =
a.data.height + "px");
},
!1
),
function() {
var e = this;
(e.createPaymentFrame = function(e, a, n) {
if (!e || "" == e || 0 == e.length)
return (
console.log(
"The createPaymentFrame method parameter elementSelector cannot be empty or null."
),
void alert(o)
);
if (!a || "" == a || 0 == a.length)
return (
console.log(
"The createPaymentFrame method parameter paymentUrl cannot be empty or null."
),
void alert(o)
);
if (t.getElementById("paymentFrame")) {
var r = t.getElementById("paymentFrame");
r.parentNode.removeChild(r);
}
if ("object" == typeof n) {
l(n),
(a =
a +
"?viewName=JsInjection&" +
Object.keys(n)
.map(function(e) {
return encodeURIComponent(e) + "=" + encodeURIComponent(n[e]);
})
.join("&"));
var i = t.createElement("iframe");
i.setAttribute("id", "paymentFrame"),
i.setAttribute("src", a),
i.setAttribute("frameborder", "0"),
i.setAttribute("scrolling", "no"),
i.setAttribute("height", "100%"),
i.setAttribute("width", "100%"),
(i.style.overflow = "hidden"),
(i.style.height = "100%"),
(i.style.width = "100%"),
t.getElementById(e).appendChild(i);
} else
console.log(
"The createPaymentFrame method expects a JSON object for the postData parameter."
),
alert(o);
}),
(e.createPaymentModal = function(e, a) {
if (!e || "" == e || 0 == e.length)
return (
console.log(
"The createPaymentModal method parameter paymentUrl cannot be empty or null."
),
void alert(o)
);
if (t.getElementById("paymentFrame")) {
var n = t.getElementById("paymentFrame");
n.parentNode.removeChild(n);
}
if ("object" == typeof a) {
l(a),
(e =
e +
"?viewName=JsPopup&" +
Object.keys(a)
.map(function(e) {
return (
encodeURIComponent(e) + "=" + encodeURIComponent(a[e])
);
})
.join("&"));
var r = t.createElement("iframe");
r.setAttribute("id", "paymentFrame"),
r.setAttribute("src", e),
r.setAttribute("frameborder", "0"),
r.setAttribute("scrolling", "no"),
(r.style.position = "fixed"),
(r.style.left = "0"),
(r.style.right = "0"),
(r.style.bottom = "0"),
(r.style.top = "0"),
(r.style.width = "100%"),
(r.style.height = "175%"),
t.body.appendChild(r);
} else
console.log(
"The createPaymentModal method expects a JSON object for the postData parameter."
),
alert(o);
}),
(e.cancelFramePayment = function() {
t.getElementById("paymentFrame").contentWindow.postMessage({
event: "ozowCancelPayment"
},
"*"
);
});
}
);
})(window, document);
Please note this is a file that was sent to me by them directly. The function that the instructions said to call is ozow.createPaymentFrame but I cannot get to the point where I can successfully call this function.
Below are the instructions found in the README.md
1. Add a container element onto your page and assign it a unique id value, i.e. a div etc., this element will be the container for the Ozow payment iframe.
Eg. <div id="paymentContainer"></div>
2. Add a trigger element onto your page and assign it a unique id value, i.e. a radio button, button etc., the element will be a option that displays pay using Ozow and will also trigger the Ozow payment frame.
Eg. <input type="radio" id="payUsingOzow" value="Ozow"> Ozow
3. Add cancel element onto your your page and assign it a unique id value, i.e. button etc., this element will be used to cancel payment using the Ozow payment frame.
Eg. <input type="button" id="cancelOzowPayment" name="cancelOzowPayment" value="Cancel Payment">
4. Inside an existing or new JavaScript script block on your page instantiate the ozow jsintegration module and assign it to a variable.
Eg. <script>
var ozow = new Ozow();
</script>
5. Create an event listener for the trigger element and add code inside the event listener to load the Ozow payment frame, i.e. onclick, onchange etc.
Eg. JavaScript: trigger_element_id.onclick = function(){
var containerElement = document.getElementById('container_element_id'); //The container element where Ozow payment frame will be loaded
var paymentUrl = 'https://pay.ozow.com/'; //The URL to process Ozow payments
var postData = {}; //The form data, which should contain all the required Ozow post variables, serialized as JSON object
ozow.createPaymentFrame(containerElement, paymentUrl, postData); //The method that initiate loading the Ozow payment frame
}; or
jQuery: $('trigger_element_id').click(function(){
var containerElement = $('container_element_id'); //The container element where Ozow payment frame will be loaded
var paymentUrl = 'https://pay.ozow.com/'; //The URL to process Ozow payments
var postData = {}; //The form data, which should contain all the required Ozow post variables, serialized as JSON object
ozow.createPaymentFrame(containerElement, paymentUrl, postData); //The method that initiate loading the Ozow payment frame
});
6. Create event listener for the cancel element and add code inside the event listener to cancel the Ozow payment, i.e. onclick, onchange etc.
Eg. JavaScript: cancel_element_id.onclick = function(){
ozow.cancelFramePayment(); //The method that will call and instruct Ozow to cancel the payment
}; or
jQuery: $('cancel_element_id').click(function(){
ozow.cancelFramePayment(); //The method that will call and instruct Ozow to cancel the payment
});
Thank you in adavnce for your support.
Additonal Notes:
It is a javascript runtime error and not a typescript compilation error
The error I am getting is that ozow.createPaymentFrame is not a function
I added the js script to the angular.json file. Below is the entire script section from the angular.json file
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"./src/assets/js/ipay-noredirect-1.0.min.js"
],
Please note I also tried :
"src/assets/js/ipay-noredirect-1.0.min.js"

Passing values to HTML File STORED in Asset Folder in Android

I was trying to pass the parameters to HTML file stored in android Asset Folder. I was passing the parameters to the function written in java script on my HTML file. But at certain times, I'm getting Exception, which I find difficult to sort out the issue.
Exception::
`I/chromium: [INFO:CONSOLE(1)] "Uncaught SyntaxError: missing ) after argument list", source: file:///android_asset/templateOffer.html (1)`.
Java script Code in HTML file:
function setWineDetails(tempOffer,wineBrnd,wineName,
wineCurrency,winePrice,placeLineOne,PlaceLineTwo,userName,wineMtchVal){
document.getElementById("usrname").innerHTML = userName;
document.getElementById("wineTpe").innerHTML = tempOffer;
document.getElementById("wine_brnd_id").innerHTML = wineBrnd;
document.getElementById("wine_name_id").innerHTML = wineName;
document.getElementById("wine_currcy_id").innerHTML = wineCurrency;
document.getElementById("wine_price_id").innerHTML = winePrice;
if (placeLineOne != = "" || placeLineOne != = null) {
document.getElementById("place_line_one_id").innerHTML = placeLineOne;
document.getElementById("place_line_second_id").innerHTML = PlaceLineTwo;
}
if (wineMtchVal == "" || wineMtchVal == null) {
document.getElementById("wine-percentages").style.visibility = 'hidden';
} else {
document.getElementById("wine-percentages").style.visibility = 'visible';
document.getElementById("wineMtch_id").innerHTML = wineMtchVal;
}
}
function setImage(wineImage){
document.getElementById("wineImage_id").src = wineImage;
}
function setValuesToOfferView(offerPercentage,offerExpiry){
document.getElementById("offer_per_id").innerHTML = offerPercentage;
document.getElementById("offer_expiry_id").innerHTML = offerExpiry;
}
passing parameteres::
private void loadWebViewContent(){
offerWebView.getSettings().setJavaScriptEnabled(true);
offerWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
//Here you want to use .loadUrl again
//on the webview object and pass in
//"javascript:<your javaScript function"
offerWebView.loadUrl("javascript:setWineDetails('"+offerTemp+"','"+wineBrand+"','"+wineName+"','"+wineCurrency+"','"+winePrice+"','"+placeLineOne+"','"+PlaceLineTwo+"','"+userName+"','"+wineMatch+"')");
offerWebView.loadUrl("javascript:setValuesToOfferView('"+offerPercentage+"','"+offerExpiry+"')"); //if passing in an object. Mapping may need to take place
offerWebView.loadUrl("javascript:setImage('"+wineImage+"')"); //if passing in an object. Mapping may need to take place
}
});
offerWebView.loadUrl("file:///android_asset/templateOffer.html");
}

Cross Site Scripting cannot be cleared

In order to prevent malicious html/scripts from being entered in input fields and saved in our application, we are inspecting the user input for html and if found, we don't submit.
We do this using the following function
/**
* Parse for HTML elements to avoid cross-site scripting
* #param str
*/
function isHTML() {
var str = $("#AttributeInstance").val();
var htmltempElement = document.createElement('div');
htmltempElement.innerHTML = str;
for (var c = htmltempElement.childNodes, i = c.length; i--;) {
if (c[i].nodeType == 1) {
htmltempElement = null;
str = null;
return true;
}
}
return false;
}
The function is working great. For instance, if on our form, the user enters the following
<img src=a onerror=alert(1)>
The function returns true and we don't save the value.
Here is how we call this function
if (isHTML()) {
alert("Found HTML! Stop!");
instance = "";
$("#AttributeInstance").val(""); //clear the input field
}
else {
alert("No HTML! Continue");
alert(instance);
addKpi(group, name, instance, instanceSelection);
}
alert("Finished");
Now here is the issue. This code results in an alert of "Found HTML! Stop!" and then "Finished" being displayed.
But then we also get an alert of "1" which is from the original input value that contains the script. By this point, that field has been cleared and we are not storing the malicious script value anywhere, however, it pops it up as a message even though it was clearly detected and we stop processing.
Any ideas? Or any suggestion how to better detect cross site scripting values in an input field?
If we remove the following from the function
htmltempElement.innerHTML = str;
for (var c = htmltempElement.childNodes, i = c.length; i--;) {
if (c[i].nodeType == 1) {
htmltempElement = null;
str = null;
return true;
}
}
Then the script does not pop up the "1" There's something about checking for a script this way that ends up processing the script it seems.

how to catch the event and distinguish close and refresh event

In my project I need to use close event in browser through web, server and database deal with the information when user log out.
I do not know how to catch the event and distinguish close and refresh event.
I tried these code:
window.onbeforeunload = function() {
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey) {
alert("close event");
}else{
alert("refresh event");
}
}
But it only catches the refresh event.
Is there a better way to solve the problem?
Besides,I have read the How to differentiate browser close and refresh events in Chrome?,but it doesn't give me the answer.
An idea: Judge by cookie to get the information if it is log in.
And the browser usually doesn't disable cookies.
If the cookie is disable, you may ask user to enable it.
Here is an example for cookie:
function setCookie(name, value) //cookies setting
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires!=null)
{
var LargeExpDate = new Date ();
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
}
document.cookie = name +value }
//In Js
setCookie("a","34234523542");
//read cookie:
function WM_readCookie(name)
{
//if there is no cookie,return false;or get value and return value
if(document.cookie == '')
return false;
else
return
unescape(WM_getCookieValue(name));
}
function WM_getCookieValue(name)
{
// Declare variables.
var firstChar,lastChar;
// Get the entire cookie string.
// (This may have other
name=value pairs in it.)
var theBigCookie = document.cookie;
// Grab
just this cookie from theBigCookie string.
// Find the start of
'name'.
firstChar = theBigCookie.indexOf(name);
// If you found it,
if(firstChar != -1)
{
// skip 'name' and '='.
firstChar +=
name.length + 1;
// Find the end of the value string (i.e. the next
';').
lastChar = theBigCookie.indexOf(';', firstChar);
if(lastChar == -1) lastChar = theBigCookie.length;
// Return the
value.
return theBigCookie.substring(firstChar, lastChar);
} else
{
// If there was no cookie, return false.
return false;
}
}

Reference controls within web service?

I have an onBlur() function in a textbox which calls a web service.
The web service checks the email entered in the textbox against a SQL table to see if it's in there and if it is, I need it to deactivate an ASP Button. (Plus a bit more fiddly stuff, but once I crack the button all should be well). However, whenever I try to reference the button control (or any other ASP control) inside the web service I am treated to an error "Cannot refer to an instance member of a class from with a shared method..."
How can I disable a button & change a panel's visibility from the web service?
onBlur()
In VB.net
txtEmail.Attributes.Add("onblur", CStr(IIf(c.AccountNo > 0, "", "CallMe(this.id,this.id);")))
In Jscript.js file
//AJAX Call to server side code
function CallMe(src, dest) {
aForgotPwd.style.display = 'none';
var ctrl = document.getElementById(src);
var cont = document.getElementById(btn);
var panel = document.getElementById(pnl);
// call server side method
return PageMethods.ValidateEmail(ctrl.value, CallSuccess, CallFailed, dest);
}
// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl) {
var dest = document.getElementById(destCtrl);
if (res == "") {
if(aForgotPwd.style.display != 'none')
{ aForgotPwd.style.display = 'none'; }
return true;
} else {
setTimeout("aForgotPwd.style.display='block';", 1);
setTimeout("dest.focus();", 1);
setTimeout("dest.select();", 1);
alert("We have your email address already in our database. Please visit forgot your password page");
return false;
}
//alert(res.get_message());
// var dest = document.getElementById(destCtrl);
}
// alert message on some failure
function CallFailed(res, destCtrl) {
var dest = document.getElementById(destCtrl);
return true;
}
Web Service called by CallMe() function
'Email Validation
<System.Web.Services.WebMethod()> _
Public Shared Function ValidateEmail(email As String) As String
Dim wbClient As WebClient = New WebClient()
Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
Dim reqHTML As Byte()
reqHTML = wbClient.DownloadData(strUrl)
Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
Dim output As String = objUTF8.GetString(reqHTML)
If String.IsNullOrEmpty(output) Then
exists = False
Else
exists = True
btnContinue.enabled = False
End If
If String.IsNullOrEmpty(output) Then Return String.Empty
Dim c As GPCUser
If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
c = CType(HttpContext.Current.Session("Customer"), GPCUser)
If c.AccountNo > 0 Then Return ""
End If
Return output
End Function
You cannot acces page objects in the web service method, rather you can disable the button and the visibility of the panel post the execution of the webservice in your call back function. Just return a message from your method which says email already present or new. Let me know if I am unclear.
EDIT
You can find further details of the webmethod implementation in this link https://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.90).aspx
<System.Web.Services.WebMethod(EnableSession:=True)> _
Public Shared Function ValidateEmail(email As String) As String
Dim wbClient As WebClient = New WebClient()
Dim strUrl As String = ConfigurationManager.AppSettings("WebsiteURLFull") + "/ajax/check_email_address.aspx?Email=" + email
Dim reqHTML As Byte()
reqHTML = wbClient.DownloadData(strUrl)
Dim objUTF8 As UTF8Encoding = New UTF8Encoding()
Dim output As String = objUTF8.GetString(reqHTML)
If String.IsNullOrEmpty(output) Then
exists = False
Else
exists = True
'btnContinue.enabled = False
'Commenting the Button enabling
output="disable"
'Assinging the output as disable so that in JS you can disable btn
End If
If String.IsNullOrEmpty(output) Then Return String.Empty
Dim c As GPCUser
If TypeOf HttpContext.Current.Session("Customer") Is GPCUser Then
c = CType(HttpContext.Current.Session("Customer"), GPCUser)
If c.AccountNo > 0 Then Return ""
End If
Return output
End Function
Also now in the CallSuccess before you continue with your functionality check whether the res is disable then you can disable button and display the already existing message.

Categories