Done get and post logic

Also added an initial input box for passphrase which is set to hidden
later
This commit is contained in:
Rohan Sircar 2019-11-06 19:42:43 +05:30
parent ed3853c5ea
commit fd6de29a89
2 changed files with 144 additions and 215 deletions

View File

@ -55,6 +55,7 @@ var userBoxes = document.getElementsByName('user-box');
for (let i = 0; i < userBoxes.length; i++) { for (let i = 0; i < userBoxes.length; i++) {
userBoxes[i].addEventListener('click', function() { userBoxes[i].addEventListener('click', function() {
let current = document.getElementsByClassName('user-box active'); let current = document.getElementsByClassName('user-box active');
let passphrase = passphraseInput.value;
if (current.length > 0) { if (current.length > 0) {
current[0].className = current[0].className.replace(" active", ""); current[0].className = current[0].className.replace(" active", "");
@ -63,202 +64,29 @@ for (let i = 0; i < userBoxes.length; i++) {
else if (current.length == 0) { else if (current.length == 0) {
document.getElementById('no-user-selected').hidden = true; document.getElementById('no-user-selected').hidden = true;
document.getElementById('chat-card').hidden = false; document.getElementById('chat-card').hidden = false;
let elem = document.getElementById('passphrase-initial');
passphrase = elem.value;
elem.hidden = true;
} }
let words = this.innerText.split("\n");
// console.log(words);
// let children = this.children;
// let userName = children[0].innerText;
let userName = this.querySelectorAll('span')[1].innerText; let userName = this.querySelectorAll('span')[1].innerText;
document.getElementById('user-name-span').innerText = userName; document.getElementById('user-name-span').innerText = userName;
populateMessages(userName); populateMessages(userName, passphrase);
sessionStorage.setItem('selectedUser', userName);
this.className += " active"; this.className += " active";
}) })
} }
function populateMessages(userName) function populateMessages(userName, passphrase) {
{ console.log('Selected user = ' + userName);
console.log(userName); if (passphrase == '') {
}
// var lastMessageTimeStamp;
// console.log(authToken);
// 'Basic ' + btoa("hmm" + ":" + "hmm")
Handlebars.registerHelper('avatar', function() {
return '<div class="img_cont_msg"> <img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img_msg"> </div>';
});
// var user;
function getSelectedUser() {
for (var i = 0; i < toUserRadios.length; i++) {
if (toUserRadios[i].checked) {
let user = toUserRadios[i].value;
console.log('sending to user = ' + user);
isCheckedUser = true;
return user;
}
}
}
// console.log('Credentials = ' + JSON.parse(sessionStorage.getItem('credentials')));
function handleChatForm() {
let chatInput = document.getElementById('chatInput');
let myForm = document.getElementById('chatMessageForm');
myForm.addEventListener(
'submit',
function(e) {
e.preventDefault();
let user = getSelectedUser();
if (!myForm.checkValidity()) {
console.log("error");
myForm.classList.add('was-validated');
return;
}
myForm.classList.add('was-validated');
if (!isCheckedUser) {
window.alert('please select a user');
return;
}
// console.log('second user = ' + user);
let messageContent = chatInput.value;
let localDate = new Date();
let messageLine = sprintf('%s %s %s: %s', localDate.toLocaleDateString(), localDate.toLocaleTimeString(), username, messageContent);
chatTextArea.append(messageLine + "\n");
chatTextArea.scrollTop = chatTextArea.scrollHeight;
// let messageCipher = sjcl.encrypt("password", messageContent);
let messageCipher = sjcl.encrypt(passphraseInput.value, messageContent, { mode: "gcm", ts: 128, adata: "", iter: iterations });
let messageCipherJson = JSON.parse(messageCipher);
// let messageCipherSpring = JSON.stringify(messageCipherJson);
// console.log('message cipher json ' + messageCipherJson);
// console.log('message cipher string ' + messageCipherSpring);
let chatMessageDTO = {
"toUser": user,
"messageCipher": messageCipherJson
}
// console.log(chatMessageDTO);
// console.log(JSON.stringify(chatMessageDTO));
messageSend(JSON.stringify(chatMessageDTO));
// sessionStorage.setItem('passphrase', passphraseInput.value);
// console.log(sessionStorage.getItem('passphrase'));
})
}
function messageSend(chatMessageDTO) {
let headers = new Headers();
// console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json')
headers.append('Content-Type', 'application/json');
headers.append('Authorization', authToken);
fetch(postNewMessageUrl, {
method: 'POST',
headers: headers,
body: chatMessageDTO
})
.then(response => console.log(response));
}
// function getMessages(toUser) {
// let headers = new Headers();
// let messageLog = [];
// // console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// // headers.append('Accept','application/json')
// // headers.append('Content-Type', 'application/json');
// headers.append('Authorization', 'Basic ' + btoa("hmm" + ":" + "hmm"));
// let myPromise = fetch(getUrl + toUser, {
// method: 'GET',
// headers: headers
// })
// .then(response => {
// console.log(response);
// return response.json();
// })
// .then(json => {
// console.log(json);
// let i = 0;
// json.forEach(function (obj) {
// // console.log(obj.toUser);
// messageCipher = JSON.stringify(obj.messageCipher);
// console.log(messageCipher);
// // let message = sjcl.decrypt("password", messageCipher);
// let message = sjcl.decrypt(passphraseInput.value, messageCipher);
// let messageLine = sprintf('%s %s: %s \n', obj.messageTime, obj.fromUser, message);
// console.log(messageLine);
// // chatTextArea.append(obj.fromUser + ": " + message + "\n");
// chatTextArea.append(messageLine);
// messageLog[i++] = messageLine;
// });
// console.log(messageLog);
// // return messageLog;
// });
// return messageLog;
// }
// async function getUserAsync(name)
// {
// let response = await fetch(`https://api.github.com/users/${name}`);
// let data = await response.json()
// return data;
// }
// getUserAsync('yourUsernameHere')
// .then(data => console.log(data));
async function getAllMessages(toUser) {
let headers = new Headers();
// headers.append('Accept','application/json')
// headers.append('Content-Type', 'application/json');
headers.append('Authorization', authToken);
let response = await fetch(getAllMessagesUrl + toUser, {
method: 'GET',
headers: headers
});
let data = await response.json();
return data;
}
async function getNewMessages(toUser, lastMessageTimeStamp) {
let headers = new Headers();
headers.append('Authorization', authToken);
let response = await fetch(`${getNewMessagesUrl}${toUser}/${lastMessageTimeStamp}`, {
method: 'GET',
headers: headers
});
let data = await response.json();
return data;
}
// getMessages('user2');
window.EventTarget.prototype.addDelegatedListener = function(type, delegateSelector, listener) {
this.addEventListener(type, function(event) {
if (event.target && event.target.matches(delegateSelector)) {
listener.call(event.target, event)
}
});
}
let parent = document.getElementById('chatMessageForm')
parent.addDelegatedListener("click", "input[type='radio']", function(event) {
// if (sessionStorage.getItem('status') != null) {
if (passphraseInput.value == '') {
alert('Please input passphrase') alert('Please input passphrase')
return; return;
} }
console.log(this.value); // console.log(userName);
if (sessionStorage.getItem(this.value) == null) { if (sessionStorage.getItem(userName) == null) {
chatTextArea.textContent = ''; chatTextArea.textContent = '';
chatAreaNew.innerHTML = ''; chatAreaNew.innerHTML = '';
getAllMessages(this.value) getAllMessages(userName)
.then(json => { .then(json => {
console.log(json); console.log(json);
let i = 0; let i = 0;
@ -272,7 +100,7 @@ parent.addDelegatedListener("click", "input[type='radio']", function(event) {
messageCipher = JSON.stringify(obj.messageCipher); messageCipher = JSON.stringify(obj.messageCipher);
console.log(messageCipher); console.log(messageCipher);
// let message = sjcl.decrypt("password", messageCipher); // let message = sjcl.decrypt("password", messageCipher);
let message = sjcl.decrypt(passphraseInput.value, messageCipher); let message = sjcl.decrypt(passphrase, messageCipher);
let utcDate = obj.messageTime; let utcDate = obj.messageTime;
lastMessageTimeStamp = utcDate; lastMessageTimeStamp = utcDate;
let localDate = new Date(utcDate); let localDate = new Date(utcDate);
@ -301,12 +129,12 @@ parent.addDelegatedListener("click", "input[type='radio']", function(event) {
}); });
sessionStorage.setItem(this.value, JSON.stringify(messageLog)); sessionStorage.setItem(userName, JSON.stringify(messageLog));
sessionStorage.setItem(this.value + 'new', JSON.stringify(messageLogNew)); sessionStorage.setItem(userName + username + 'new', JSON.stringify(messageLogNew));
// console.log() // console.log()
// sessionStorage.clear(); // sessionStorage.clear();
console.log('Last message time = ' + lastMessageTimeStamp); console.log('Last message time = ' + lastMessageTimeStamp);
sessionStorage.setItem(this.value + '-time', lastMessageTimeStamp); sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
} }
@ -314,19 +142,19 @@ parent.addDelegatedListener("click", "input[type='radio']", function(event) {
} else { } else {
console.log("Stored messages = " + sessionStorage.getItem(this.value)); console.log("Stored messages = " + sessionStorage.getItem(userName));
let storedMessages = JSON.parse(sessionStorage.getItem(this.value)); let storedMessages = JSON.parse(sessionStorage.getItem(userName));
let storedMessagesNew = JSON.parse(sessionStorage.getItem(this.value + 'new')); let storedMessagesNew = JSON.parse(sessionStorage.getItem(userName + username + 'new'));
let lastMessageTime = sessionStorage.getItem(this.value + '-time'); let lastMessageTime = sessionStorage.getItem(userName + '-time');
console.log("last message time stamp = " + lastMessageTime); console.log("last message time stamp = " + lastMessageTime);
if (lastMessageTime != null) { if (lastMessageTime != null) {
getNewMessages(this.value, lastMessageTime) getNewMessages(userName, lastMessageTime)
.then(json => { .then(json => {
console.log(json) console.log(json)
if (json.length > 0) { if (json.length > 0) {
json.forEach(function(obj) { json.forEach(function(obj) {
let messageCipher = JSON.stringify(obj.messageCipher); let messageCipher = JSON.stringify(obj.messageCipher);
let message = sjcl.decrypt(passphraseInput.value, messageCipher); let message = sjcl.decrypt(passphrase, messageCipher);
// console.log(message); // console.log(message);
// chatTextArea.append(message + "\n"); // chatTextArea.append(message + "\n");
let utcDate = obj.messageTime; let utcDate = obj.messageTime;
@ -354,12 +182,12 @@ parent.addDelegatedListener("click", "input[type='radio']", function(event) {
$(chatAreaNew).append(msgContainer); $(chatAreaNew).append(msgContainer);
}) })
sessionStorage.setItem(this.value + '-time', lastMessageTimeStamp); sessionStorage.setItem(userName + '-time', lastMessageTimeStamp);
sessionStorage.setItem(this.value, JSON.stringify(storedMessages)); sessionStorage.setItem(userName, JSON.stringify(storedMessages));
sessionStorage.setItem(this.value + 'new', JSON.stringify(storedMessagesNew)); sessionStorage.setItem(userName + username + 'new', JSON.stringify(storedMessagesNew));
console.log("this value stored" + sessionStorage.getItem(this.value)) console.log("this value stored" + sessionStorage.getItem(userName))
console.log("last message time stamp = " + lastMessageTimeStamp); console.log("last message time stamp = " + lastMessageTimeStamp);
console.log(sessionStorage.getItem(this.value + '-time')); console.log(sessionStorage.getItem(userName + '-time'));
} }
chatTextArea.textContent = ''; chatTextArea.textContent = '';
@ -404,17 +232,114 @@ parent.addDelegatedListener("click", "input[type='radio']", function(event) {
} }
// sessionStorage.setItem('status', 'ready'); // sessionStorage.setItem('status', 'ready');
// sessionStorage.setItem('this.value', messageLog); // sessionStorage.setItem('userName', messageLog);
// console.log('Message log = ' + messageLog); // console.log('Message log = ' + messageLog);
// } // }
// let passphraseKey = this.value + '-passphrase'; // let passphraseKey = userName + '-passphrase';
// sessionStorage.setItem(passphraseKey, passphraseInput.value); // sessionStorage.setItem(passphraseKey, passphrase);
// console.log(sessionStorage.getItem(passphraseKey)); // console.log(sessionStorage.getItem(passphraseKey));
}
// var lastMessageTimeStamp;
// console.log(authToken);
// 'Basic ' + btoa("hmm" + ":" + "hmm")
Handlebars.registerHelper('avatar', function() {
return '<div class="img_cont_msg"> <img src="https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg" class="rounded-circle user_img_msg"> </div>';
}); });
handleChatForm(); // var user;
function getSelectedUser() {
for (var i = 0; i < toUserRadios.length; i++) {
if (toUserRadios[i].checked) {
let user = toUserRadios[i].value;
console.log('sending to user = ' + user);
isCheckedUser = true;
return user;
}
}
}
function getSelectedUserNew() {
return sessionStorage.getItem('selectedUser');
}
document.getElementById('chatMessageForm').addEventListener('submit', function(e) {
let chatInput = document.getElementById('chatInput');
e.preventDefault();
let user = getSelectedUserNew();
if (!this.checkValidity()) {
console.log("error");
this.classList.add('was-validated');
return;
}
this.classList.add('was-validated');
if (user == null) {
window.alert('please select a user');
return;
}
let messageContent = chatInput.value;
let localDate = new Date();
let messageLine = sprintf('%s %s %s: %s', localDate.toLocaleDateString(), localDate.toLocaleTimeString(), username, messageContent);
chatTextArea.append(messageLine + "\n");
chatTextArea.scrollTop = chatTextArea.scrollHeight;
let messageCipher = sjcl.encrypt(passphraseInput.value, messageContent, { mode: "gcm", ts: 128, adata: "", iter: iterations });
let messageCipherJson = JSON.parse(messageCipher);
let chatMessageDTO = {
"toUser": user,
"messageCipher": messageCipherJson
}
messageSend(JSON.stringify(chatMessageDTO));
})
// console.log('Credentials = ' + JSON.parse(sessionStorage.getItem('credentials')));
function messageSend(chatMessageDTO) {
let headers = new Headers();
// console.log("Token = " + btoa("hmm" + ":" + "hmm"))
// headers.append('Accept','application/json')
headers.append('Content-Type', 'application/json');
headers.append('Authorization', authToken);
fetch(postNewMessageUrl, {
method: 'POST',
headers: headers,
body: chatMessageDTO
})
.then(response => console.log(response));
}
async function getAllMessages(toUser) {
let headers = new Headers();
// headers.append('Accept','application/json')
// headers.append('Content-Type', 'application/json');
headers.append('Authorization', authToken);
let response = await fetch(getAllMessagesUrl + toUser, {
method: 'GET',
headers: headers
});
let data = await response.json();
return data;
}
async function getNewMessages(toUser, lastMessageTimeStamp) {
let headers = new Headers();
headers.append('Authorization', authToken);
let response = await fetch(`${getNewMessagesUrl}${toUser}/${lastMessageTimeStamp}`, {
method: 'GET',
headers: headers
});
let data = await response.json();
return data;
}
$(document).ready(function() { $(document).ready(function() {
$('#action_menu_btn').click(function() { $('#action_menu_btn').click(function() {

View File

@ -101,6 +101,7 @@
<div class="d-flex justify-content-center"> <div class="d-flex justify-content-center">
<div class="align-self-center"> <div class="align-self-center">
<h2 class="display-4 no-user-selected-h2">Please select a user</h2> <h2 class="display-4 no-user-selected-h2">Please select a user</h2>
<input class="form-control type_msg" size="10" type="password" id="passphrase-initial" placeholder="Passphrase " required>
</div> </div>
</div> </div>
</div> </div>
@ -152,21 +153,24 @@
</div> </div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<form action="#" th:object="${chatMessageDTO}" method="post" id="chatMessageForm" class="needs-validation" novalidate>
<div class="input-group"> <div class="input-group">
<div class="input-group-append"> <div class="input-group-append">
<span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span> <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span>
</div> </div>
<textarea name="" class="form-control type_msg" placeholder="Type your message..."></textarea> <input class="form-control type_msg" size="10" type="password" id="passphrase" placeholder="Passphrase " required>
<textarea name="" id="chatInput" class="form-control type_msg" placeholder="Type your message..." required></textarea>
<div class="input-group-append"> <div class="input-group-append">
<span class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></span> <button class="input-group-text send_btn"><i class="fas fa-location-arrow"></i></button>
</div>
</div>
</form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> <section hidden>
</div>
<section>
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-sm"> <div class="col-sm">
@ -184,7 +188,7 @@
<div class="card-text"> <div class="card-text">
</div> </div>
<form action="#" th:object="${chatMessageDTO}" method="post" id="chatMessageForm" class="needs-validation" novalidate> <form action="#" th:object="${chatMessageDTO}" method="post" class="needs-validation" novalidate>
<div class="row"> <div class="row">
<div class="col-3"> <div class="col-3">
<div class="form-group"> <div class="form-group">
@ -201,7 +205,7 @@
<div class="my-form-inputs container"> <div class="my-form-inputs container">
<div class="form-group"> <div class="form-group">
<label for="chatInput">Your message: </label> <label for="chatInput">Your message: </label>
<textarea class="form-control" type="text" id="chatInput" required></textarea> <textarea class="form-control" type="text" required></textarea>
<div class="invalid-feedback"> <div class="invalid-feedback">
Cannot be empty Cannot be empty
</div> </div>
@ -209,7 +213,7 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="passphrase">Passphrase: </label> <label for="passphrase">Passphrase: </label>
<input class="form-control" type="password" id="passphrase" required> <input class="form-control" type="password" required>
</div> </div>
<div class="form-group text-center"> <div class="form-group text-center">
<button class="btn btn-secondary mx-auto">Submit</button> <button class="btn btn-secondary mx-auto">Submit</button>