I am using cryptojs to encrypt and decrypt a file. I also have a web service to upload the encrypted files to a server. I can upload and save the ecnrypted object as a file on the server, but when I decrypt it, the file does not open correctly. My concern is if I am saving the ecnrypted object correctly or not.
Tutorial that I followed initially: http://tutorialzine.com/2013/11/javascript-file-encrypter/
encryt method:
function encrypt() {
var folderPath = "C:\\User\\test\\javascript-file-encrypter\\";
selectedFiles = document.getElementById("MainContent_file1");
var sfile = selectedFiles.files[0];
var read = new FileReader();
read.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(read.result, '123456');
var ct2 = encrypted.toString();
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': ct2, 'fileName': sfile.name + '.encrypted' },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
}
read.readAsDataURL(sfile);
}
decrypt method:
function decrypt() {
var sfiles = document.getElementById("MainContent_file1");
var sfile = sfiles.files[0];
var freader = new FileReader();
freader.onload = function (e) {
var decrypted = CryptoJS.AES.decrypt(freader.result, '123456');
var dct = decrypted.toString(CryptoJS.enc.Latin1);
//var dct2 = decrypted.toString();
//console.log(dct);
//console.log(dct2);
debugger;
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': dct, 'fileName': sfile.name.replace('.encrypted', '') },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
};
freader.readAsText(sfile);
}
webservice method:
[WebMethod]
public bool FileUpload(string folderPath, string uploadData, string fileName)
{
bool returnValue = false;
try
{
File.WriteAllText(folderPath + fileName, uploadData);
returnValue = true;
}
catch (Exception ex)
{
returnValue = false;
}
return returnValue;
}
Related
Working on a requirement to upload images to AWS instance. UI and service is separated and connects via REST. Service is in nodejs. from UI we are making a ajax call to backend service to upload the images to AWS.
The problem:
When I upload the images via POSTMAN request, I can see that response as uploaded with files properly uploaded in AWS.
Whereas when I upload images via AJAX call, I get no response in browser, and also the images are not uploaded in aws.
Below is the piece of code in ajax:
var formData = new FormData();
formData.append('image', $('#tx_file_programa')[0]);
$.ajax({
method: 'POST',
type: "POST",
url: 'http://10.0.0.95:9999/photo/1',
contentType: false,
processData: false,
async: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token );
},
data: formData,
success: function (data) {
console.log('response from server is : ', data);
}
//dataType: 'json'
});
This is the backend service.
server.post('/photo/:count', function (req, res) {
if (req.getContentType() == 'multipart/form-data') {
var form = new formidable.IncomingForm(),
files = [], fields = [];
var result = [];
var noOfFiles = req.params.count;
var count = 0;
console.log('noOfFiles', noOfFiles);
form.on('field', function(field, value) {
fields.push([field, value]);
console.log(fields);
})
form.on('progress', function(bytesReceived, bytesExpected) {
console.log('err');
});
form.on('error', function(err) {
console.log('err',err);
});
form.on('aborted', function() {
console.log('aborted', arguments);
});
new Promise(function(resolve, reject) {
var result = [];
form.onPart = function (part) {
var data = null;
const params = {
Bucket: 'xxxxx',
Key: uuidv4() + part.filename,
ACL: 'public-read'
};
var upload = s3Stream.upload(params);
upload.on('error', function (error) {
console.log('errr', error);
});
upload.on('part', function (details) {
console.log('part', details);
});
upload.on('uploaded', function (details) {
let extension = details.Location.split('.');
if(['JPG', 'PNG'].indexOf(extension[extension.length - 1].toUpperCase()) > -1) {
var ext = extension[extension.length - 1];
count++;
result.push(details.Location);
if(count == noOfFiles) {
resolve(result);
}
}
});
part.pipe(upload);
}
}).then(function(result){
console.log('end', result);
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received files:\n\n ' + util.inspect(result));
})
form.parse(req, function (err, fields, files) {
})
return;
} else {
BadRequestResponse(res, "Invalid request type!");
}
})
#user3336194, Can you check with this, this is working thins
var appIconFormData = null
$(":file").change(function () {
var file = this.files[0], name = file.name, size = file.size, type = file.type;
var imageType = new Array("image/png", "image/jpeg", "image/gif", "image/bmp");
if (jQuery.inArray(type, imageType) == -1) {
return false;
} else {
appIconFormData = new FormData();
appIconFormData.append('appimage', $('input[type=file]')[0].files[0]);
}
});
$.ajax({
url: 'your/api/destination/url',
type: 'POST',
data: appIconFormData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data)
},
error: function (e) {
}
});
I think the way you are sending formdata is not correct.
Try these 2 ways:
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
I am trying to pass json string from angularjs to my websrvice and used below code.Can someone please let me where i went wrong with the below code?
Controller method:
[httpget]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "GET",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
You need [HttpPost] method, and make post request
Controller method:
[HttpPost]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "POST",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
Can anyone point me to an article that explains clientside token auth implementation using Javascript?
I found many articles on Angular but that is not what I'm looking for. That brings me to the question if it is possible to be done with Javascript.
Also how to handle scenarios when the auth server throws a 401. Is there a built in exception to detect that response? Or is a custom exception required to be implemented?
I have personally used JSON web tokens in one of my projects.
http://blog.slatepeak.com/creating-a-simple-node-express-api-authentication-system-with-passport-and-jwt is a tutorial on how to set up JSON web tokens on the server side.
Once you get the token as a response to the client side, you can store the token on window.localStorage.
var credentials = {
username : document.getElementById("username").value,
password : document.getElementById("password").value
};
var url = window.localStorage.getItem('appUrl');
$.ajax({
url: url + '/register',
type: 'POST',
data: { username: credentials.username, password: credentials.password },
success: function(Data) {
window.localStorage.setItem('token', Data.token);
},
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', window.localStorage.getItem('token'));},
error: function() {
alert('Error occured');
}
});
});
Then you can attach it in an AJAX call as a header while navigating to other pages.
$.ajax
({
type: "GET",
url: "index1.php",
data: '{}',
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization',window.localStorage.getItem('token'));
},
success: function (){
alert('Thanks for your comment!');
}
});
This worked for me..
var token = gettoken();
function getDatatypes() {
if (isEmpty(token)) {
token = gettoken();
}
var request = getDatatypesFromApi();
request.success(function (data) {
alert('success!');
});
request.error(function (httpObj, textStatus) {
if (httpObj.status == 401)
gettoken();
});
}
function getDatatypesFromApi() {
var request = $.ajax
({
type: "GET",
url: "http://yoururl.com/",
data: '',
headers:{
'Authorization': 'Basic ' + token
},
dataType: "json",
timeout: 5000,
});
return request;
}
function gettoken() {
var credentials = {
username: "userid",
password: "PASS",
domain: "",
extensionsAppId:"{extAppId}"
};
var url = "http://thelinktoresource/"
$.ajax({
url: url,
type: 'GET',
data: { userId: credentials.username, password: credentials.password, domain: credentials.domain, extensionsAppId: credentials.extensionsAppId },
dataType: "json",
contentType: 'application/json; charset=UTF-8',
success: function (Data) {
console.log(Data);
token = Data.replace(/"/ig, '');
return token;
},
error: function () {
alert('Error occured');
return "undefined";
}
});
}
function isEmpty(strIn) {
if (strIn === undefined) {
return true;
}
else if (strIn == null) {
return true;
}
else if (strIn == "") {
return true;
}
else {
return false;
}
}
Here is the function to process my form
$scope.processForm = function () {
var url = 'http://localhost:8080/tickets/'
$http({
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
url: url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
console.log("purchase failed");
});
What I would like to do is append the requestID onto the end of the url if there is an error.
If there is an error then the url should change the the below once they submit again:
var url = 'http://localhost:8080/tickets/'+ requestID
You are looking to append the requestID on the end of the url that you are submitting data to, correct?
One option would be to store either the URL or the requestID on $scope.
$scope.url = 'http://localhost:8080/tickets/';
$scope.processForm = function () {
$http({
method: 'POST',
headers: {'Content-Type': 'application/json; charset=UTF-8'},
url: $scope.url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
$scope.url = 'http://localhost:8080/tickets/' + requestID;
console.log("purchase failed");
});
I figured out how to achieve what I wanted in the end. I saved the url and the requestID on $scope.
if ($scope.requestID == null) {
$scope.url = 'http://localhost:8080/tickets/';
}
else if ($scope.requestID !== null && $scope.firstTransaction == null) {
$scope.firstRequest = $scope.requestID;
console.log("first transaction id = " + $scope.requestID)
$scope.url = 'http://localhost:8080/tickets/' + $scope.firstRequest;
}
$scope.processForm = function() {
$http({
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
url: $scope.url,
data: JSON.stringify($scope.formData)
}).then(function successCallback(response) {
//log
console.log("ticket purchased");
}, function errorCallback(response) {
var requestID = JSON.stringify(response.data.requestID);
$scope.url = 'http://localhost:8080/tickets/' + requestID;
console.log("purchase failed");
});
I am using Google authorization into my app. It works perfectly,
but the problem is cache not clear when someone logout from app.
I have tried adding clearcache=yes and clearsessioncache=yes, but they do not seem to do anything. Without clearing the cache when someone tries to log back in it validates the token with the previously signed in account.
Is there a way I can delete everything associated to the InAppBrowser ?
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
var authWindow = window.open(authUrl,'_blank','location=no,toolbar=no,clearsessioncache=yes');
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function (response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
googleapi.authorize({
client_id: 'client_id',
client_secret: 'client_secret-key',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
getDataProfile();
});
}
function getDataProfile() {
var term = null;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {
},
success: function (data) {
var item;
var OAuthToken = accessToken;
var OAuthAccessToken = data.id;
var username = data.email;
var firstname = data.given_name;
var lastname = data.family_name;
var ExternalIdentifier = data.id;
var Email = data.email;
var ProviderSystemName = "ExternalAuth.Google";
ExternalResponseInsert(apiSecretKey, storeId, languageId, username, firstname, lastname, Email, ExternalIdentifier, OAuthToken, OAuthAccessToken, ProviderSystemName);
}
});
//disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
}
});
}