Reputation: 13
This is more about code organization and a slicker approach, that can be generalized. Specifically its in a Jeopardy Quiz that I'm building out to improve my skills in AJAX/JSON. I would like to keep the answers apart from the question. One can simply find and open the JSON in DevTools and find the correct answer. I'd like to make it a little harder, but not too hard to code or add any more layers past one or two JSON files. (And not overkill like hashing a DB query since its just a pet project).
Not sure how to do this... Here's my JSON.. { "question": "Town where Jefferson built Monticello", "choices": [ "Richmond", "Raliegh", "Charlottesville" ] }
I had the correct answer with the question in the JSON, but I'm not sure that is the best way to do this... I think an anwser key might be better.
Upvotes: 0
Views: 1948
Reputation: 2258
One way you could do this (and keep it simple) is to do a base64 encoding of your JSON object.
First, once you have all of your questions, encode them to base64. You can use the btoa
function in JavaScript to do this. Don't put this line of code in your client though.
btoa( JSON.stringify({ "question": "Town where Jefferson built Monticello", "choices": [ "Richmond", "Raliegh", "Charlottesville" ] }))
Then, take that base64 encoded string and place it in your code.
const data = "eyJxdWVzdGlvbiI6IlRvd24gd2hlcmUgSmVmZmVyc29uIGJ1aWx0IE1vbnRpY2VsbG8iLCJjaG9pY2VzIjpbIlJpY2htb25kIiwiUmFsaWVnaCIsIkNoYXJsb3R0ZXN2aWxsZSJdfQ=="
From there, you can decode and turn it back into a JSON object in your code.
let questions = JSON.parse( atob(data) )
Like you mentioned in your question, this can still be "hacked". It's not proper security by any means. People can inspect it and run the code to get the questions and answers. However, the answers wouldn't be obvious at first glance.
To make it a little better, you can run your JavaScript through an obfuscation tool. The variables for data
and questions
would get mangled and it would be a bit harder to identify what is being decoded.
Upvotes: 1
Reputation: 425
I'd make an endpoint that gets the question id and the selected answer, returning whether or not it's correct and the correct answer, in case it's wrong, marking the question as answered for that user/session in the process.
That way, even if the user hits your API using DevTools or something like that, the effect would be the same as answering through the UI.
Upvotes: 0