Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add data validation to the node server request handler #22

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

MartyO256
Copy link

This pull request aims at adding data validation to the request handlers used in the node server for adding entries to the MongoDB.
Since req.body's shape is based on user-controlled input, it should not always be trusted.

I introduce a Joi schema matching the following record type:

type mongo_solution =
{ student_id : string;
timestamp : string;
collection : string;
student_solution : string
}

The following code snippet is responsible for making POST requests from the LearnOCaml server to the node server.
It seems like the mongo_solution is marshalled into an object with the proper keys.

let student_json = Json.output {student_id = stId; timestamp = current_time; collection = collection_name; student_solution = solution} in
let nodeRequest = XmlHttpRequest.create () in
nodeRequest ## _open (Js.string "POST") (url) (Js.bool true);
nodeRequest ## setRequestHeader (Js.string "Content-Type") (Js.string "application/json; charset=UTF-8");
nodeRequest ## send (Js.some student_json);

I was surprised to find in the node request handler that the mongo_solution gets unmarshalled as an array.
Is this a limitation of js_of_ocaml?

learn-ocaml/node/app.js

Lines 32 to 43 in 82ae88e

const split_array = req.body;
const collection = split_array[3];
let parsedSolStr = split_array[4];
const obj = new Object();
obj.studentId = split_array[1];
obj.timestamp = new Date().toString();
obj.solution = parsedSolStr;
const jsonString = JSON.stringify(obj);
const solution = JSON.parse( jsonString ); // parse req.body as an object
db.collection(collection).insertOne(solution);
console.log(solution);
res.sendStatus(200); // success status

Testing would be required to ensure that this PR does not break unmarshalling of the request's body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant