moved js into seperate files inside js/ directory
This commit is contained in:
parent
38ad788a45
commit
ca1b8fb324
@ -1,4 +1,4 @@
|
||||
#posts > div > p {
|
||||
#posts > div > p > span:first-child {
|
||||
color: green;
|
||||
}
|
||||
|
||||
@ -42,5 +42,5 @@ button {
|
||||
}
|
||||
|
||||
* {
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-family: 'system-ui';
|
||||
}
|
||||
|
22
js/changePW.js
Normal file
22
js/changePW.js
Normal file
@ -0,0 +1,22 @@
|
||||
async function setUser() {
|
||||
let user = await (await fetch("/api/getuser")).json()
|
||||
//user["username"],user["error"]
|
||||
if(user["username"])document.getElementById("username").innerText = `Current User: ${user["username"]}`
|
||||
if(user["error"])document.getElementById("username").innerText = `Error: ${user["error"]}`
|
||||
|
||||
}
|
||||
|
||||
setUser()
|
||||
|
||||
document.getElementById("submit").addEventListener("click",async function(){
|
||||
if(window.confirm("Are you sure that you want to change your Password?")){
|
||||
let re = await (await post("/api/changePW",{"currentPW":document.getElementById("currentPW").value,"newPW":document.getElementById("newPW").value})).json()
|
||||
document.getElementById("response").innerText = re["error"] || re["success"]
|
||||
document.getElementById("response").style="color:green"
|
||||
if(re["error"]) {
|
||||
document.getElementById("response").style="color:red"
|
||||
}
|
||||
document.getElementById("currentPW").value = ""
|
||||
document.getElementById("newPW").value = ""
|
||||
}
|
||||
})
|
31
js/htmlescape.js
Normal file
31
js/htmlescape.js
Normal file
@ -0,0 +1,31 @@
|
||||
const {replace} = '';
|
||||
|
||||
const es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
|
||||
const ca = /[&<>'"]/g;
|
||||
|
||||
const esca = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
"'": ''',
|
||||
'"': '"'
|
||||
};
|
||||
const pe = m => esca[m];
|
||||
|
||||
const escape = es => replace.call(es, ca, pe);
|
||||
|
||||
const unes = {
|
||||
'&': '&',
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'>': '>',
|
||||
''': "'",
|
||||
''': "'",
|
||||
'"': '"',
|
||||
'"': '"'
|
||||
};
|
||||
const cape = m => unes[m];
|
||||
|
||||
const unescape = un => replace.call(un, es, cape);
|
1
js/httppost.js
Normal file
1
js/httppost.js
Normal file
@ -0,0 +1 @@
|
||||
window.post = function(url, data) {return fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});}
|
121
js/posts.js
Normal file
121
js/posts.js
Normal file
@ -0,0 +1,121 @@
|
||||
socket = new WebSocket("wss://ws.zerotwohub.tk:25566");
|
||||
socket.addEventListener("message", function (event) {
|
||||
let data = event.data;
|
||||
let ds = data.split(" ")
|
||||
let message = ds[0]
|
||||
console.log(data,ds);
|
||||
if(message == "new_post") {
|
||||
main()
|
||||
mainNoti(ds[1])
|
||||
}
|
||||
})
|
||||
function urlify(text) {
|
||||
let urlRegex = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal|tk|ga))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi
|
||||
return text.replace(urlRegex,'<a href="$1">$1</a> ')
|
||||
}
|
||||
function filterMentions(text) {
|
||||
let mentionRegex = /(@[^\s]*)/gi
|
||||
return text.replace(mentionRegex,'<span class="mention">$1</span> ')
|
||||
}
|
||||
document.getElementById("post-btn").addEventListener("click",async function() {
|
||||
if(document.getElementById("post-text").value.length >= 1001) {
|
||||
alert("Error, your message cant contain more than 1000 characters!")
|
||||
return
|
||||
}
|
||||
let r = await post("/api/post",{"message":document.getElementById("post-text").value})
|
||||
document.getElementById("post-text").value = ""
|
||||
})
|
||||
function filterPost(text) {
|
||||
text = escape(text)
|
||||
text = urlify(text)
|
||||
text = filterMentions(text)
|
||||
return text
|
||||
}
|
||||
function createPost(username,text,time) {
|
||||
const newDiv = document.createElement("div");
|
||||
const newP = document.createElement("p");
|
||||
const newSpan = document.createElement("span");
|
||||
const newSpan2 = document.createElement("span");
|
||||
|
||||
|
||||
//const newText = document.createTextNode(text);
|
||||
const newUsername = document.createTextNode(username);
|
||||
let timedate = new Date(time)
|
||||
time = timedate
|
||||
time = time.toString()
|
||||
time = time.split(" ")
|
||||
time = time[0] + " " + time[1] + " " + time[2] + " " + time[3] + " " + time[4]
|
||||
if(timedate=="Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)")time="unknown time"
|
||||
const newTime = document.createTextNode(` | ${time}`)
|
||||
newDiv.classList.add("post");
|
||||
newSpan.appendChild(newUsername)
|
||||
newSpan2.appendChild(newTime)
|
||||
|
||||
newP.appendChild(newSpan)
|
||||
newP.appendChild(newSpan2)
|
||||
|
||||
|
||||
newDiv.appendChild(newP)
|
||||
newDiv.innerHTML += filterPost(text)
|
||||
//newDiv.appendChild(newText)
|
||||
|
||||
document.getElementById("posts").appendChild(newDiv)
|
||||
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let user = await (await fetch("/api/getuser")).json()
|
||||
let username = user.username
|
||||
if(!username)username = user.error
|
||||
document.getElementById("username-self").innerText = username
|
||||
|
||||
let index = 0
|
||||
let last_10_posts = await (await fetch(`/api/getPosts/${index}`)).json()
|
||||
if(!last_10_posts)return;
|
||||
document.getElementById("posts").innerHTML = ""
|
||||
last_10_posts.forEach((item, i) => {
|
||||
console.log(item,i);
|
||||
createPost(item.post_user_name,item.post_text,item.post_time)
|
||||
});
|
||||
let mentions = document.getElementsByClassName("mention")
|
||||
for (let i = 0; i < mentions.length; i++) {
|
||||
if(mentions[i]!=undefined && mentions[i].innerText == "@"+username) {
|
||||
mentions[i].classList.add("user-mention");
|
||||
mentions[i].classList.remove("mention");
|
||||
i--;
|
||||
}
|
||||
if(mentions[i]!=undefined && (mentions[i].innerText == "@everyone" || mentions[i].innerText == "@here")) {
|
||||
mentions[i].classList.add("everyone-mention");
|
||||
mentions[i].classList.remove("mention");
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
var cansendNoti = false
|
||||
|
||||
async function askNotiPerms() {
|
||||
return Notification.requestPermission()
|
||||
}
|
||||
|
||||
async function mainNoti(user) {
|
||||
if(Notification.permission === 'denied' || Notification.permission === 'default') {
|
||||
await askNotiPerms()
|
||||
console.log("asked for perms");
|
||||
} else {
|
||||
if(cansendNoti) {
|
||||
let notification = new Notification('ZTH Board', { body: "new message posted from " + user });
|
||||
notification = await notification
|
||||
console.log(notification);
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener("visibilitychange", function() {
|
||||
if (document.visibilityState === 'visible') {
|
||||
cansendNoti = false
|
||||
} else {
|
||||
cansendNoti = true
|
||||
}
|
||||
});
|
37
server.js
37
server.js
@ -251,8 +251,8 @@ router.post("/api/post", async function(req,res) {
|
||||
res.send("error")
|
||||
return
|
||||
}
|
||||
let sql = `insert into zerotwohub.posts (post_user_name,post_text) values (?,?);`
|
||||
let values = [res.locals.username,req.body.message]
|
||||
let sql = `insert into zerotwohub.posts (post_user_name,post_text,post_time) values (?,?,?);`
|
||||
let values = [res.locals.username,req.body.message,Date.now()]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err) throw err;
|
||||
console.log(result);
|
||||
@ -265,7 +265,7 @@ router.post("/api/post", async function(req,res) {
|
||||
|
||||
router.get("/api/getPosts/*", async function(req,res) {
|
||||
|
||||
let sql = `select post_user_name,post_text from zerotwohub.posts where post_id >= ? and post_id <= ? order by post_id desc;`
|
||||
let sql = `select post_user_name,post_text,post_time from zerotwohub.posts where post_id >= ? and post_id <= ? order by post_id desc;`
|
||||
let id = parseInt(req.originalUrl.replace("/api/getPosts/"))
|
||||
if(isNaN(id))id=0
|
||||
let values = [id,id+100]
|
||||
@ -320,6 +320,16 @@ router.get("/css/*", (request, response) => {
|
||||
return;
|
||||
});
|
||||
|
||||
router.get("/js/*", (request, response) => {
|
||||
if(!increaseUSERCall(request,response))return
|
||||
if(fs.existsSync(__dirname + request.originalUrl)){
|
||||
response.sendFile(__dirname + request.originalUrl);
|
||||
} else {
|
||||
response.status(404).send("no file with that name found")
|
||||
}
|
||||
return;
|
||||
});
|
||||
|
||||
router.get("/*", (request, response, next) => {
|
||||
if(!increaseUSERCall(request,response))return
|
||||
let originalUrl = request.originalUrl.split("?").shift()
|
||||
@ -344,13 +354,18 @@ router.post("/register",async function(req,res) {
|
||||
if(!increaseAPICall(req,res))return;
|
||||
res.status(200)
|
||||
let username = req.body.user.toString()
|
||||
username = username.replace(" ","")
|
||||
username = username.replace(/\s/gi,"")
|
||||
let password = req.body.pass.toString()
|
||||
if(!username) {
|
||||
res.status(400)
|
||||
res.redirect("/register?success=false&reason=username")
|
||||
return
|
||||
}
|
||||
if(username=="") {
|
||||
res.status(400)
|
||||
res.redirect("/register?success=false&reason=username")
|
||||
return
|
||||
}
|
||||
if(username.length > 100) {
|
||||
res.status(400)
|
||||
res.send("username is too long")
|
||||
@ -369,11 +384,11 @@ router.post("/register",async function(req,res) {
|
||||
return
|
||||
}
|
||||
let hashed_pw = SHA256(password,username,HASHES_DB)
|
||||
let values = [username,hashed_pw]
|
||||
let sql = `INSERT INTO zerotwohub.users (User_Name, User_PW) VALUES (?, ?);`
|
||||
let ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
|
||||
let values = [username,hashed_pw, Date.now(), ip, ip]
|
||||
let sql = `INSERT INTO zerotwohub.users (User_Name, User_PW, User_CreationStamp, User_CreationIP, User_LastIP) VALUES (?, ?, ?, ? ,?);`
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err) throw err;
|
||||
let ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
|
||||
let setTo = username + " " + SHA256(password,username,HASHES_COOKIE)
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret+ip);
|
||||
res.cookie('AUTH_COOKIE',cookiesigned, { maxAge: Math.pow(10,10), httpOnly: true, secure: DID_I_FINALLY_ADD_HTTPS });
|
||||
@ -407,7 +422,7 @@ router.post("/login",async function(req,res) {
|
||||
|
||||
let hashed_pw = SHA256(password,username,HASHES_DB)
|
||||
|
||||
let userexistssql = `SELECT * from zerotwohub.users where User_Name = ? and User_PW = ?`
|
||||
let userexistssql = `SELECT User_Name,User_PW,Last_IP from zerotwohub.users where User_Name = ? and User_PW = ?`
|
||||
con.query(userexistssql,[username,hashed_pw],function(error,result) {
|
||||
if(result && result[0] && result[0].User_Name && result[0].User_Name==username && result[0].User_PW && result[0].User_PW == hashed_pw) {
|
||||
let ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
|
||||
@ -415,6 +430,12 @@ router.post("/login",async function(req,res) {
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret+ip);
|
||||
res.cookie('AUTH_COOKIE',cookiesigned, { maxAge: Math.pow(10,10), httpOnly: true, secure: DID_I_FINALLY_ADD_HTTPS });
|
||||
res.redirect("/user?success=true")
|
||||
if(result[0].Last_IP != ip) {
|
||||
let sql = `update zerotwohub.users set Last_IP=? where User_Name=?;`
|
||||
con.query(sql,[ip,username],function(error,result) {
|
||||
if(error)throw error
|
||||
})
|
||||
}
|
||||
} else {
|
||||
res.redirect("/login?success=false")
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Change Password</title>
|
||||
<link rel="stylesheet" href="/css/changePW.css">
|
||||
<script type="text/javascript">window.post = function(url, data) {return fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});}</script>
|
||||
<script type="text/javascript" src="/js/httppost.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div>
|
||||
@ -24,29 +24,6 @@
|
||||
<br>
|
||||
<span id="response"></span>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
async function setUser() {
|
||||
let user = await (await fetch("/api/getuser")).json()
|
||||
//user["username"],user["error"]
|
||||
if(user["username"])document.getElementById("username").innerText = `Current User: ${user["username"]}`
|
||||
if(user["error"])document.getElementById("username").innerText = `Error: ${user["error"]}`
|
||||
|
||||
}
|
||||
|
||||
setUser()
|
||||
|
||||
document.getElementById("submit").addEventListener("click",async function(){
|
||||
if(window.confirm("Are you sure that you want to change your Password?")){
|
||||
let re = await (await post("/api/changePW",{"currentPW":document.getElementById("currentPW").value,"newPW":document.getElementById("newPW").value})).json()
|
||||
document.getElementById("response").innerText = re["error"] || re["success"]
|
||||
document.getElementById("response").style="color:green"
|
||||
if(re["error"]) {
|
||||
document.getElementById("response").style="color:red"
|
||||
}
|
||||
document.getElementById("currentPW").value = ""
|
||||
document.getElementById("newPW").value = ""
|
||||
}
|
||||
})
|
||||
</script>
|
||||
<script type="text/javascript" src="/js/changePW.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
150
views/posts.html
150
views/posts.html
@ -4,40 +4,8 @@
|
||||
<meta charset="utf-8">
|
||||
<title></title>
|
||||
<link rel="stylesheet" href="/css/posts.css">
|
||||
<script type="text/javascript">window.post = function(url, data) {return fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});}</script>
|
||||
<script type="text/javascript">
|
||||
const {replace} = '';
|
||||
|
||||
const es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
|
||||
const ca = /[&<>'"]/g;
|
||||
|
||||
const esca = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
"'": ''',
|
||||
'"': '"'
|
||||
};
|
||||
const pe = m => esca[m];
|
||||
|
||||
const escape = es => replace.call(es, ca, pe);
|
||||
|
||||
const unes = {
|
||||
'&': '&',
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'>': '>',
|
||||
''': "'",
|
||||
''': "'",
|
||||
'"': '"',
|
||||
'"': '"'
|
||||
};
|
||||
const cape = m => unes[m];
|
||||
|
||||
const unescape = un => replace.call(un, es, cape);
|
||||
</script>
|
||||
<script type="text/javascript" src="/js/httppost.js"></script>
|
||||
<script type="text/javascript" src="/js/htmlescape.js"></script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
@ -46,117 +14,7 @@ const unescape = un => replace.call(un, es, cape);
|
||||
<textarea name="name" id="post-text" rows="8" cols="80"></textarea> <br>
|
||||
<button type="button" name="button" id="post-btn">Post</button>
|
||||
</div>
|
||||
<div class="posts" id="posts">
|
||||
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
socket = new WebSocket("wss://ws.zerotwohub.tk:25566");
|
||||
socket.addEventListener("message", function (event) {
|
||||
let data = event.data;
|
||||
let ds = data.split(" ")
|
||||
let message = ds[0]
|
||||
console.log(data,ds);
|
||||
if(message == "new_post") {
|
||||
main()
|
||||
mainNoti(ds[1])
|
||||
}
|
||||
})
|
||||
function urlify(text) {
|
||||
let urlRegex = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal|tk|ga))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\s+|$)/gi
|
||||
return text.replace(urlRegex,'<a href="$1">$1</a> ')
|
||||
}
|
||||
function filterMentions(text) {
|
||||
let mentionRegex = /(@[^\s]*)/gi
|
||||
return text.replace(mentionRegex,'<span class="mention">$1</span> ')
|
||||
}
|
||||
document.getElementById("post-btn").addEventListener("click",async function() {
|
||||
if(document.getElementById("post-text").value.length >= 1001) {
|
||||
alert("Error, your message cant contain more than 1000 characters!")
|
||||
return
|
||||
}
|
||||
let r = await post("/api/post",{"message":document.getElementById("post-text").value})
|
||||
document.getElementById("post-text").value = ""
|
||||
})
|
||||
function filterPost(text) {
|
||||
text = escape(text)
|
||||
text = urlify(text)
|
||||
text = filterMentions(text)
|
||||
return text
|
||||
}
|
||||
function createPost(username,text) {
|
||||
const newDiv = document.createElement("div");
|
||||
const newP = document.createElement("p");
|
||||
//const newText = document.createTextNode(text);
|
||||
const newUsername = document.createTextNode(username);
|
||||
|
||||
newDiv.classList.add("post");
|
||||
|
||||
newP.appendChild(newUsername)
|
||||
|
||||
newDiv.appendChild(newP)
|
||||
newDiv.innerHTML += filterPost(text)
|
||||
//newDiv.appendChild(newText)
|
||||
|
||||
document.getElementById("posts").appendChild(newDiv)
|
||||
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let user = await (await fetch("/api/getuser")).json()
|
||||
let username = user.username
|
||||
if(!username)username = user.error
|
||||
document.getElementById("username-self").innerText = username
|
||||
|
||||
let index = 0
|
||||
let last_10_posts = await (await fetch(`/api/getPosts/${index}`)).json()
|
||||
if(!last_10_posts)return;
|
||||
document.getElementById("posts").innerHTML = ""
|
||||
last_10_posts.forEach((item, i) => {
|
||||
console.log(item,i);
|
||||
createPost(item.post_user_name,item.post_text)
|
||||
});
|
||||
let mentions = document.getElementsByClassName("mention")
|
||||
for (let i = 0; i < mentions.length; i++) {
|
||||
if(mentions[i]!=undefined && mentions[i].innerText == "@"+username) {
|
||||
mentions[i].classList.add("user-mention");
|
||||
mentions[i].classList.remove("mention");
|
||||
i--;
|
||||
}
|
||||
if(mentions[i]!=undefined && (mentions[i].innerText == "@everyone" || mentions[i].innerText == "@here")) {
|
||||
mentions[i].classList.add("everyone-mention");
|
||||
mentions[i].classList.remove("mention");
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
var cansendNoti = false
|
||||
|
||||
async function askNotiPerms() {
|
||||
return Notification.requestPermission()
|
||||
}
|
||||
|
||||
async function mainNoti(user) {
|
||||
if(Notification.permission === 'denied' || Notification.permission === 'default') {
|
||||
await askNotiPerms()
|
||||
console.log("asked for perms");
|
||||
} else {
|
||||
if(cansendNoti) {
|
||||
let notification = new Notification('ZTH Board', { body: "new message posted from " + user });
|
||||
notification = await notification
|
||||
console.log(notification);
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener("visibilitychange", function() {
|
||||
if (document.visibilityState === 'visible') {
|
||||
cansendNoti = false
|
||||
} else {
|
||||
cansendNoti = true
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<div class="posts" id="posts"></div>
|
||||
<script type="text/javascript" src="/js/posts.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
Loading…
x
Reference in New Issue
Block a user