What's missing in my Sign In request? - javascript

I'm trying to access the endpoints of a website (lighterpack.com, github: https://github.com/galenmaly/lighterpack). To test my ability to do this, I'm trying to make a POST call to the 'signin' function in edit.js (bottom).
I'm using Postman to send the POST request, sending it the object {username: myusername, password: myhashedpasswordandusername}
I'm hashing the object manually right now on my local machine, and copying that out to Postman. I created a JS file with the "crypto-js" dependency, and ran the command that the edit.js file uses, after setting var CryptoJS = require('crypto-js').
This might be the part I messed up, but I can't see where. I
My hashing file code:
var crypto = require('crypto-js')
var pass = "mypassword"
var name = "username"
var hash = crypto.SHA3(pass+name)
var hash= hash.toString(crypto.enc.Base64)
console.log(hash)
I take what the console logs out, and put that in my Postman object as my password. The thing I don't get is that in the edit.js file, CryptoJS doesn't appear defined anywhere, not that I could see anyway. Can someone point me in the right direction?
Original edit.js function:
$(".signin").on("submit", function(evt) {
evt.preventDefault();
var form = this;
var error = "";
var username = $(".username", this).val();
var password = $(".password", this).val();
if (!password) error = "Please enter a password.";
if (!username) error = "Please enter a username.";
if (error) {
$(".lpError", this).text(error).show();
return;
}
$(".lpError", this).text("").hide();
username = username.toLowerCase();
var hash = CryptoJS.SHA3(password+username);
hash = hash.toString(CryptoJS.enc.Base64);
$.ajax({
url: "/signin",
data: {username: username, password: hash, },
method: "POST",
error: function(data, textStatus, jqXHR) {
var error = "An error occurred.";
if (data.responseText) error = data.responseText;
$(".password", form).val("").focus();
$(".lpError", form).text(error).show();
},
success: function(data) {
$("#signin, #lpModalOverlay").fadeOut("slow", removeBlackout);
$(".password, .username", form).val("");
signedIn(data.username);
library.load(JSON.parse(data.library));
initWithLibrary();
}
});
});

So someone got me the answer. In github, there is a file public/sha3.js that has the CryptoJS variable, and the app.js file declares that file's info (CryptoJS) as a global variable.
I copied sha3.js, and was able to correctly hash my data and then login. Success!

Related

App not redirecting to proper page upon receiving server response

First, I am sorry for the odd name of this thread but I was not sure how to name it.
I am working on a NodeJS app and I seem to have stumble upon a bug I really don't understand.
This is an eLearning app so, at some point, an admin will create quizzes and questions for other users to answer.
The one creating a quiz also has the possibility to duplicate a quiz and edit the title and description of the quiz.
For this I created a route, /duplicatetest.js, that has a GET and a POST method.
The GET method brings the quiz data from the server and sends it to front end for display:
app.get('/duplicatetest/:idTest', isLoggedIn, hasPermision, function(req, res) {
console.log(currentDateTime.getCurrentDate() + " - GET > duplicatetest");
customLogging.customLogging("GET > duplicatetest");
var idTest = req.params.idTest;
getTestToDuplicate.getTestToDuplicate(idTest)
.then(function(result) {
res.render('duplicatetest', {
'test': result
});
});
});
The POST method saves the changes to DB:
app.post('/duplicatetest', isLoggedIn, hasPermision, function(req, res) {
console.log(currentDateTime.getCurrentDate() + " - POST > duplicatetest");
customLogging.customLogging("POST > duplicatetest");
var newTest = req.body.newTest;
saveNewTest.saveNewTest(newTest)
.then(function(result) {
console.log("Sending response now...");
res.send({
"status": 201,
"message": "",
"value": ""
});
});
});
Both seem to be working just fine.
On front-end I have the following JavaScript:
$(document).ready(function()
{
$("#testName").val(test.title);
$("#testDetails").val(test.testDescription);
var url = window.location.pathname;
var idTest = url.split("/");
$("#nextStepTest").click(function()
{
const token = getCookie("u.tkn");
test.token = token;
var title = $("#testName").val();
var details = $("#testDetails").val();
var modifiedTest = {idTest: idTest[2], title: title, description: details, author: token};
var newTest = {newTest: modifiedTest}
$.ajax({
traditional: true,
url: '/duplicatetest',
type: "POST",
contentType: 'application/json',
data: JSON.stringify(newTest),
dataType: 'json',
success: function (response) {
if (response.status == 201) {
window.location = "/tests";
}
},
failure: function (response) {
console.log(response.message[1]);
}
});
});
function getCookie(name)
{
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
});
However, I encounter the following behavior:
I visit /duplicatetest/idTest and make the changes.
Say I have a test with title Test 1 and description Test Description 1.
I change them to Test 1 Duplicate and Test description 1 Duplicate.
On saving, the data is saved in the DB without problems but instead of receiving a response and being redirected to /tests,
the page refreshes, displays the original data (Test 1 and Test Description 1) and the url changes from /duplicatetest/idTest to /duplicatetest/idTest?testName=Test+1+Duplicate (or whatever new name you pick for the new quiz).
On rare occasions however, the redirect works. I am using similar ajax calls for other pages and situations, without any problem.
What I noticed so far is that mostly there is no response from the server in front-end but so far I could not explain why.
What exactly am I doing wrong here and where is that "?testName=Test+1+Duplicate" coming from? I would really appreciate any suggestions since I've been trying to find an explanation for this for some time now...

MailChimp GAS - invalid resource: blank email

I'm writing a script that takes google sheet data and uploads my mailchimp subscriber data, where the edited cell values are sent over as updated merge tags. The original code came from here. I've got the script running successfully, accept for this one error:
"Invalid Resource","status":400,"detail":"Blank email address"
I understand the error according to the documentation in the mailchimp api documentation, but I'm not sure why it's not recognizing the subscriber data from the script:
var emHash = md5(em.toLowerCase()); //this is pulled from my md5 function
var payload = JSON.stringify({
"status_if_new": "subscribed",
"email_address": em,
"merge_fields": {
"LEAD": lead,
//rest of vars following same syntax
}
});
var options = {
"headers" : headers,
"payload": payload,
"method" : "put",
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch('https://us15.api.mailchimp.com/3.0' + '/lists/' + 'xxxxxxx' + '/members/' + emHash,options);
Logger.log(response);
}
Last is the function triggered by editing so that changed values get sent over via the function above
function onEdit(e) {
var activeSheet = e.source.getActiveSheet();
var range = e.range;
var rowedited = range.getRowIndex();
if (activeSheet.getName() !== "ATTENDANCE"){
return;
Logger.log("Oops :(");
}
else {
var values = sheet.getRange(rowedited, 1, 1, 13).getValues()[0];
var em = values[2];
var lead = values[1];
//remaining vars omitted for brevity
sendToMailChimp_(em,lead...[etc.]);
}
Any thoughts?
I figured it out - I pulled an amateur move and had the columns attributed to the wrong array element.... So yes, I started at 1 and not 0
facepalm
It is now working!

Connecting to Bitfinex API from Google Sheets

I'm trying to connect my google sheet to Bitfinex through the 'authenticated' section of the API so I can access my account information. Here is the API link.
I haven't been able to get the 'request' or 'crypto' libraries to work so I've been trying to use other available functions in google sheets, but am having trouble.
Following is the code snippet I'm using:
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL,
'nonce' : nonce
};
var payload = JSON.stringify(body).toString('base64');
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384,
payload,
secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
}
Logger.log(completeURL);
Logger.log(params);
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
I get the following error from the API:
Request failed for https://api.bitfinex.com/v1/account_infos returned code 400. Truncated server response: {"message":"Invalid json."} (use muteHttpExceptions option to examine full response). (line 209, file "Code")
And the following are the values from the Logger.log calls:
[17-09-24 16:22:28:170 AEST] https://api.bitfinex.com/v1/account_infos
[17-09-24 16:22:28:171 AEST] {headers={X-BFX-PAYLOAD={"request":"https://api.bitfinex.com/v1/account_infos","nonce":1506234148}, X-BFX-SIGNATURE=06d88a85098aefbf2b56af53721506863978f9350b1b18386c23f446254789dbbfc1eeb520bdfc7761b30f98ea0c21a2, X-BFX-APIKEY=ak6UoPiwaLjwt2UqDzZzZGjpb9P2opvdPCAIqLy0eVq}}
I'm stuck and not sure what else to try?
Can anyone spot what I'm doing wrong?
How about this modification? Since I have no secret, I couldn't debug this sample. So I don't know whether this modified sample works. I'm sorry.
Modification points :
secret is not defined.
When POST method is used, it requires to include method: "post" to UrlFetchApp.fetch().
When it reads Javascript sample of the document, signature has to be modified.
When it reads Javascript sample of the document, body: JSON.stringify(body) is included in the request parameters.
There is an error message of {"message":"Invalid json."}.
The script which was reflected above modifications is as follows.
Modified script :
var secret = "#####"; // Please input this.
var completeURL = "https://api.bitfinex.com/v1/account_infos";
var nonce = Math.floor(new Date().getTime()/1000);
var body = {
'request' : completeURL, // I don't know whether this is the correct value.
'nonce' : nonce
};
var payload = Utilities.base64Encode(Utilities.newBlob(JSON.stringify(body)).getDataAsString());
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, payload, secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
var params = {
method: "post",
headers: {
'X-BFX-APIKEY': key,
'X-BFX-PAYLOAD': payload,
'X-BFX-SIGNATURE': signature
},
payload: JSON.stringify(body),
contentType: "application/json",
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(completeURL, params);
var json = JSON.parse(response.getContentText());
If this was not useful for you, I'm sorry.
I am not sure if I am understanding your code, but if I do, there is at least one oddity at first sight:
In computeHmacSignature(...), you are using the variable secret which has not been initialized or even declared anywhere.
That's how it works
var body = {
'request' : "/v1/balances",
'nonce' : nonce,
'options':{}
};

Unable to receive POST body from Ajax request using Play Framework

I am trying to send a POST request to my backend with some JSON data. The call from the frontend looks like this:
function register() {
var user = $("#form_reg_username").val();
var pass = $("#form_reg_password").val();
var referal = $("#form_reg_referal").val();
var postbody = {};
var url = "http://" + location.host + "/api/admin/register";
postbody.username = user;
postbody.password = pass;
postbody.referal = referal;
var jsonbody = JSON.stringify(postbody);
console.log(jsonbody);
$.ajax({
type: "POST",
url: url,
data: jsonbody,
dataType: "json",
success: registerHandler()
});
}
The generated log looks like this:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Which is fine.
Here is the start of how I handle the request on the backend (I am using play 2.4)
public Result adminRegister() {
// Generate JSON from postbody
ObjectNode json = Json.newObject();
Logger.info("Body: " + request().body().asText());
JsonNode body = request().body().asJson();
String username = body.get("username").asText();
String password = body.get("password").asText();
String referal = body.get("referal").asText();
...
}
Looking at my application log the Info log looks like this:
[info] application - Body: null
I am then getting a Nullpointer Exception in first line of trying to get the json values.
So for some reason the POST body seems not to be received correctly.
Thanks for any help in advance.
Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null.
I fixed my issue with this little workaround:
Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();
String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];

how to redirect page in html?

i am writing page in html and i have server/database on parse.com .
parse provides login function which checks if username and password is matched in a database. i have done this part but when i get success it is not redirecting into other page. here is the code :
$("#login").click(function(event)
var name = $(#name).val();
var pass = $(#password).val();
Parse.User.logIn(name, pass, {
debugger
success: function(user){
window.location="login/login.html";
console.log("everything OK")
}, error: function(user, error){
console.log("Log in Error:"+error.message);
}
});
});
i have searched for redirecting the page and found out the window.location but it is not working. what is the error please help me.
By the way i got error message at this line var name = $(#name).val(); with error message :
Uncaught SyntaxError: Unexpected token ILLEGAL
You have a couple of problems in your code which is stopping it from running. Unexpected token ILLEGAL is the browser's way of telling you that it doesn't understand your code.
1) You're missing the opening brace in the first function
2) In the jQuery selectors, you need to wrap the selectors in quotes - $("#name").val() and $("#password").val()
3) Your debuger statement is misplaced. You've put it inside an object definition, and it doesn't make sense there. Move it to inside the function below. (It's also spelt debugger with 2 g's :) )
$("#login").click(function(event) { // 1) include brace
var name = $("#name").val(); // 2) include quotes
var pass = $("#password").val();
Parse.User.logIn(name, pass, {
success: function(user){
debugger; // 3) move debugger statement to a valid location
window.location="login/login.html";
console.log("everything OK")
},
error: function(user, error) {
console.log("Log in Error:"+error.message);
}
});
});
You need to pass both of your selectors in quotes
var name = $("#name").val();
var pass = $("#password").val();
That will stop the error and should work.
This is riddled with errors and missing semicolons and parantheses. Try this
$("#login").click(function(event) {
var name = $("#name").val();
var pass = $("#password").val();
Parse.User.logIn(name, pass, debuger);
success: function(user){
window.location="login/login.html";
console.log("everything OK")
}, error: function(user, error){
console.log("Log in Error:"+error.message);
}
});
});

Categories

Resources