fix error + format
This commit is contained in:
+107
-81
@@ -1,122 +1,148 @@
|
||||
import fs from "fs";
|
||||
import { SHA256 } from "../../extra_modules/SHA.js";
|
||||
import { unsign } from "../../extra_modules/unsign.js";
|
||||
const config = JSON.parse(fs.readFileSync("server_config.json"));
|
||||
const HASHES_DB = config.cookies.server_hashes;
|
||||
const HASHES_COOKIE = config.cookies.client_hashes;
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE;
|
||||
import fs from 'fs'
|
||||
import { SHA256 } from '../../extra_modules/SHA.js'
|
||||
import { unsign } from '../../extra_modules/unsign.js'
|
||||
const config = JSON.parse(fs.readFileSync('server_config.json'))
|
||||
const HASHES_DB = config.cookies.server_hashes
|
||||
const HASHES_COOKIE = config.cookies.client_hashes
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
router.use("/*path", (req, res, next) => {
|
||||
res.set("Access-Control-Allow-Origin", "*"); //we'll allow it for now
|
||||
let unsigned;
|
||||
router.use('/*path', (req, res, next) => {
|
||||
res.set('Access-Control-Allow-Origin', '*') //we'll allow it for now
|
||||
let unsigned
|
||||
|
||||
req.body = req.body || {};
|
||||
req.body = req.body || {}
|
||||
|
||||
if (typeof req.get("ipost-auth-token") === "string") {
|
||||
if (typeof req.get('ipost-auth-token') === 'string') {
|
||||
try {
|
||||
req.body.auth = JSON.parse(req.get("ipost-auth-token"))
|
||||
req.body.auth = JSON.parse(req.get('ipost-auth-token'))
|
||||
} catch (err) {
|
||||
console.log("error parsing header", err)
|
||||
console.log('error parsing header', err)
|
||||
}
|
||||
}
|
||||
if (req.body.auth !== undefined && req.originalUrl !== "/redeemauthcode") {
|
||||
if (typeof req.body.auth === "string") {
|
||||
if (
|
||||
req.body.auth !== undefined &&
|
||||
req.originalUrl !== '/redeemauthcode'
|
||||
) {
|
||||
if (typeof req.body.auth === 'string') {
|
||||
try {
|
||||
req.body.auth = JSON.parse(req.body.auth)
|
||||
} catch (err) {
|
||||
console.log("error parsing", err)
|
||||
console.log('error parsing', err)
|
||||
}
|
||||
} else
|
||||
if (
|
||||
typeof req.body.auth !== "object" ||
|
||||
typeof req.body.auth.secret !== "string" ||
|
||||
typeof req.body.auth.appid !== "number" ||
|
||||
typeof req.body.auth.auth_token !== "string" ||
|
||||
req.body.auth.secret.length !== 200 ||
|
||||
req.body.auth.auth_token.length !== 200 ||
|
||||
Buffer.from(req.body.auth.secret, "base64").length !== 150
|
||||
) {
|
||||
res.status(420).send("invalid authentication object")
|
||||
return;
|
||||
} else {
|
||||
//secret : string(200 chars)
|
||||
//appid : number
|
||||
//auth_token: string(200 chars)
|
||||
let sql = "select User_ID,User_Name,User_Bio,User_Avatar,User_Settings from ipost.auth_tokens inner join ipost.application on auth_token_isfrom_application_id=application_id inner join ipost.users on auth_token_u_id=User_ID where auth_token=? and application_secret=? and application_id=?"
|
||||
con.query(sql, [SHA256(req.body.auth.auth_token, req.body.auth.appid, HASHES_DB), SHA256(req.body.auth.secret, req.body.auth.appid, HASHES_DB), req.body.auth.appid], (err, result) => {
|
||||
if (err) throw err;
|
||||
} else if (
|
||||
typeof req.body.auth !== 'object' ||
|
||||
typeof req.body.auth.secret !== 'string' ||
|
||||
typeof req.body.auth.appid !== 'number' ||
|
||||
typeof req.body.auth.auth_token !== 'string' ||
|
||||
req.body.auth.secret.length !== 200 ||
|
||||
req.body.auth.auth_token.length !== 200 ||
|
||||
Buffer.from(req.body.auth.secret, 'base64').length !== 150
|
||||
) {
|
||||
res.status(420).send('invalid authentication object')
|
||||
return
|
||||
} else {
|
||||
//secret : string(200 chars)
|
||||
//appid : number
|
||||
//auth_token: string(200 chars)
|
||||
let sql =
|
||||
'select User_ID,User_Name,User_Bio,User_Avatar,User_Settings from ipost.auth_tokens inner join ipost.application on auth_token_isfrom_application_id=application_id inner join ipost.users on auth_token_u_id=User_ID where auth_token=? and application_secret=? and application_id=?'
|
||||
con.query(
|
||||
sql,
|
||||
[
|
||||
SHA256(
|
||||
req.body.auth.auth_token,
|
||||
req.body.auth.appid,
|
||||
HASHES_DB
|
||||
),
|
||||
SHA256(
|
||||
req.body.auth.secret,
|
||||
req.body.auth.appid,
|
||||
HASHES_DB
|
||||
),
|
||||
req.body.auth.appid,
|
||||
],
|
||||
(err, result) => {
|
||||
if (err) throw err
|
||||
|
||||
if (result.length !== 1) {
|
||||
res.status(420).send("invalid authentication object (or server error?)")
|
||||
return;
|
||||
res.status(420).send(
|
||||
'invalid authentication object (or server error?)'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
res.locals.userid = result[0].User_ID;
|
||||
res.locals.username = result[0].User_Name;
|
||||
res.locals.bio = result[0].User_Bio || "";
|
||||
res.locals.avatar = result[0].User_Avatar || "";
|
||||
res.locals.settings = result[0].User_Settings || {};
|
||||
res.locals.userid = result[0].User_ID
|
||||
res.locals.username = result[0].User_Name
|
||||
res.locals.bio = result[0].User_Bio || ''
|
||||
res.locals.avatar = result[0].User_Avatar || ''
|
||||
res.locals.settings = result[0].User_Settings || {}
|
||||
|
||||
res.locals.isbot = true; //only apps/bots use auth tokens
|
||||
res.locals.isbot = true //only apps/bots use auth tokens
|
||||
|
||||
next()
|
||||
})
|
||||
return;
|
||||
}
|
||||
}
|
||||
)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if (!req.cookies.AUTH_COOKIE) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
unsigned = unsign(req.cookies.AUTH_COOKIE, req, res);
|
||||
unsigned = unsign(req.cookies.AUTH_COOKIE, req, res)
|
||||
if (!unsigned) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
}
|
||||
let sql = `select User_ID,User_Name,User_Bio,User_Avatar,User_Settings from ipost.users where User_Name=? and User_PW=?;`;
|
||||
let values = unsigned.split(" ");
|
||||
values[1] = SHA256(values[1], values[0], HASHES_DIFF);
|
||||
res.locals.bio = "";
|
||||
res.locals.avatar = "";
|
||||
res.locals.settings = {};
|
||||
let sql = `select User_ID,User_Name,User_Bio,User_Avatar,User_Settings from ipost.users where User_Name=? and User_PW=?;`
|
||||
let values = unsigned.split(' ')
|
||||
values[1] = SHA256(values[1], values[0], HASHES_DIFF)
|
||||
res.locals.bio = ''
|
||||
res.locals.avatar = ''
|
||||
res.locals.settings = {}
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (result[0] && result[0].User_Name && result[0].User_Name === values[0]) {
|
||||
|
||||
res.locals.userid = result[0].User_ID;
|
||||
res.locals.username = result[0].User_Name;
|
||||
res.locals.bio = result[0].User_Bio || "";
|
||||
res.locals.avatar = result[0].User_Avatar || "";
|
||||
res.locals.settings = result[0].User_Settings || {};
|
||||
|
||||
if (err) throw err
|
||||
if (
|
||||
result[0] &&
|
||||
result[0].User_Name &&
|
||||
result[0].User_Name === values[0]
|
||||
) {
|
||||
res.locals.userid = result[0].User_ID
|
||||
res.locals.username = result[0].User_Name
|
||||
res.locals.bio = result[0].User_Bio || ''
|
||||
res.locals.avatar = result[0].User_Avatar || ''
|
||||
res.locals.settings = result[0].User_Settings || {}
|
||||
}
|
||||
next()
|
||||
});
|
||||
});
|
||||
})
|
||||
})
|
||||
|
||||
router.use("/api/*path", (req, res, next) => {
|
||||
res.set("Access-Control-Allow-Origin", "*"); //we'll allow it for now
|
||||
if (config["allow_getotheruser_without_cookie"] && req.originalUrl.split("\?")[0] === "/api/getotheruser") {
|
||||
next();
|
||||
return;
|
||||
router.use('/api/*path', (req, res, next) => {
|
||||
res.set('Access-Control-Allow-Origin', '*') //we'll allow it for now
|
||||
if (
|
||||
config['allow_getotheruser_without_cookie'] &&
|
||||
req.originalUrl.split('\?')[0] === '/api/getotheruser'
|
||||
) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
if (!server.increaseAPICall(req, res)) return;
|
||||
if (!server.increaseAPICall(req, res)) return
|
||||
|
||||
if (res.locals.username !== undefined) {
|
||||
next();
|
||||
}
|
||||
else {
|
||||
res.status(402);
|
||||
res.json({ "error": "you cannot access the api without being logged in" });
|
||||
next()
|
||||
} else {
|
||||
res.status(402)
|
||||
res.json({
|
||||
error: 'you cannot access the api without being logged in',
|
||||
})
|
||||
}
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
export default {
|
||||
setup
|
||||
};
|
||||
setup,
|
||||
}
|
||||
|
||||
@@ -1,71 +1,94 @@
|
||||
//const web_version = require("unsafe_encrypt").web_version
|
||||
import { web_version } from "unsafe_encrypt";
|
||||
import { web_version } from 'unsafe_encrypt'
|
||||
export const setup = function (router, con, server) {
|
||||
router.get("/api/getPersonalPosts", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
let otherperson = encodeURIComponent(req.query.otherperson || "");
|
||||
if (typeof otherperson !== "string" || otherperson.length > 100 || otherperson === "") {
|
||||
res.status(410).json({ "error": "invalid otherperson given" });
|
||||
return;
|
||||
router.get('/api/getPersonalPosts', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
let otherperson = encodeURIComponent(req.query.otherperson || '')
|
||||
if (
|
||||
typeof otherperson !== 'string' ||
|
||||
otherperson.length > 100 ||
|
||||
otherperson === ''
|
||||
) {
|
||||
res.status(410).json({ error: 'invalid otherperson given' })
|
||||
return
|
||||
}
|
||||
const columns = [
|
||||
"dms_user_name", "dms_text", "dms_time", "dms_special_text", "dms_id", "dms_from_bot", "dms_reply_id"
|
||||
];
|
||||
'dms_user_name',
|
||||
'dms_text',
|
||||
'dms_time',
|
||||
'dms_special_text',
|
||||
'dms_id',
|
||||
'dms_from_bot',
|
||||
'dms_reply_id',
|
||||
]
|
||||
//dms_user_name = sender
|
||||
//dms_receiver = receiver
|
||||
//if (sender == current and receiver == other) or (receiver == current and sender == other)
|
||||
let sql = `select ${columns.join(",")} from ipost.dms where ((dms_receiver = ? and dms_user_name = ?) or (dms_receiver = ? and dms_user_name = ?)) order by dms_id desc limit 50;`;
|
||||
con.query(sql, [otherperson, encodeURIComponent(res.locals.username), encodeURIComponent(res.locals.username), otherperson], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
let sql = `select ${columns.join(',')} from ipost.dms where ((dms_receiver = ? and dms_user_name = ?) or (dms_receiver = ? and dms_user_name = ?)) order by dms_id desc limit 50;`
|
||||
con.query(
|
||||
sql,
|
||||
[
|
||||
otherperson,
|
||||
encodeURIComponent(res.locals.username),
|
||||
encodeURIComponent(res.locals.username),
|
||||
otherperson,
|
||||
],
|
||||
function (err, result) {
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
}
|
||||
)
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/dms/conversations", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
let uriencusername = encodeURIComponent(res.locals.username);
|
||||
let sql = `select dms_user_name, dms_receiver from ipost.dms where ((dms_receiver = ?) or (dms_user_name = ?)) group by dms_receiver,dms_user_name;`;
|
||||
con.query(sql, [uriencusername, uriencusername], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
})
|
||||
router.get('/api/dms/conversations', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
let uriencusername = encodeURIComponent(res.locals.username)
|
||||
let sql = `select dms_user_name, dms_receiver from ipost.dms where ((dms_receiver = ?) or (dms_user_name = ?)) group by dms_receiver,dms_user_name;`
|
||||
con.query(
|
||||
sql,
|
||||
[uriencusername, uriencusername],
|
||||
function (err, result) {
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
}
|
||||
)
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/dms/encrypt.js", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
res.send(web_version());
|
||||
})
|
||||
router.get('/api/dms/encrypt.js', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
res.send(web_version())
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
})
|
||||
//
|
||||
router.get("/api/dms/getDM", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
let arg = req.query.id;
|
||||
let uriencusername = encodeURIComponent(res.locals.username);
|
||||
let sql = `select dms_user_name,dms_text,dms_time,dms_special_text,dms_id,dms_from_bot,dms_reply_id,dms_receiver from ipost.dms where dms_id=? and (dms_user_name=? or dms_receiver=?);`;
|
||||
con.query(sql, [arg, uriencusername, uriencusername], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (result[0]) {
|
||||
res.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
res.json(result[0]);
|
||||
router.get('/api/dms/getDM', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
let arg = req.query.id
|
||||
let uriencusername = encodeURIComponent(res.locals.username)
|
||||
let sql = `select dms_user_name,dms_text,dms_time,dms_special_text,dms_id,dms_from_bot,dms_reply_id,dms_receiver from ipost.dms where dms_id=? and (dms_user_name=? or dms_receiver=?);`
|
||||
con.query(
|
||||
sql,
|
||||
[arg, uriencusername, uriencusername],
|
||||
function (err, result) {
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
res.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
res.json(result[0])
|
||||
} else {
|
||||
res.json({ error: 'there is no such dm!' })
|
||||
}
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "there is no such dm!" });
|
||||
}
|
||||
});
|
||||
)
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
export default {
|
||||
setup
|
||||
};
|
||||
setup,
|
||||
}
|
||||
|
||||
+70
-58
@@ -1,104 +1,116 @@
|
||||
import xor from "../../../extra_modules/xor.js";
|
||||
import xor from '../../../extra_modules/xor.js'
|
||||
export const setup = function (router, con, server) {
|
||||
const PIDS = {}; //[pid]: true/"already_used"
|
||||
const PIDS = {} //[pid]: true/"already_used"
|
||||
|
||||
function createPID(){
|
||||
let pid = server.genstring(10); //collision chance is low enough, but we'll check anyways
|
||||
function createPID() {
|
||||
let pid = server.genstring(10) //collision chance is low enough, but we'll check anyways
|
||||
while (PIDS[pid] !== undefined) {
|
||||
pid = server.genstring(10);
|
||||
console.log(5, "pid collision");
|
||||
pid = server.genstring(10)
|
||||
console.log(5, 'pid collision')
|
||||
}
|
||||
PIDS[pid] = true;
|
||||
setTimeout(function() {
|
||||
PIDS[pid] = undefined;
|
||||
}, 40000);
|
||||
PIDS[pid] = true
|
||||
setTimeout(function () {
|
||||
PIDS[pid] = undefined
|
||||
}, 40000)
|
||||
return pid
|
||||
}
|
||||
|
||||
|
||||
router.get("/api/dms/pid", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
res.json({ "pid": createPID() });
|
||||
router.get('/api/dms/pid', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
res.json({ pid: createPID() })
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.post("/api/dms/post", function (req, res) {
|
||||
})
|
||||
router.post('/api/dms/post', function (req, res) {
|
||||
if (!req.body.message) {
|
||||
res.status(410)
|
||||
res.json({ "error": "no message to post" });
|
||||
return;
|
||||
res.json({ error: 'no message to post' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.message) !== "string") {
|
||||
if (typeof req.body.message !== 'string') {
|
||||
res.status(411)
|
||||
res.json({ "error": "no message to post" });
|
||||
return;
|
||||
res.json({ error: 'no message to post' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.pid) !== "string") {
|
||||
if (typeof req.body.pid !== 'string') {
|
||||
res.status(412)
|
||||
res.json({ "error": "no pid given" });
|
||||
return;
|
||||
res.json({ error: 'no pid given' })
|
||||
return
|
||||
}
|
||||
if (req.body.pid.length !== 10 || PIDS[req.body.pid] !== true) {
|
||||
res.status(413)
|
||||
res.json({ "error": "invalid pid given" });
|
||||
return;
|
||||
res.json({ error: 'invalid pid given' })
|
||||
return
|
||||
}
|
||||
PIDS[req.body.pid] = "already_used";
|
||||
let reply_id;
|
||||
PIDS[req.body.pid] = 'already_used'
|
||||
let reply_id
|
||||
if (!req.body.reply_id || req.body.reply_id < 0) {
|
||||
reply_id = 0;
|
||||
reply_id = 0
|
||||
} else {
|
||||
reply_id = req.body.reply_id
|
||||
}
|
||||
else {
|
||||
reply_id = req.body.reply_id;
|
||||
}
|
||||
if ((typeof reply_id) !== "number") {
|
||||
if (typeof reply_id !== 'number') {
|
||||
res.status(414)
|
||||
res.json({ "error": "no valid reply id given" });
|
||||
return;
|
||||
res.json({ error: 'no valid reply id given' })
|
||||
return
|
||||
}
|
||||
if (req.body.message.length > 1000) {
|
||||
res.status(415)
|
||||
res.json({ "error": "message too long" });
|
||||
return;
|
||||
res.json({ error: 'message too long' })
|
||||
return
|
||||
}
|
||||
req.body.message = encodeURIComponent(req.body.message.trim());
|
||||
req.body.message = encodeURIComponent(req.body.message.trim())
|
||||
if (req.body.message.length > 3000) {
|
||||
res.status(416)
|
||||
res.json({ "error": "message too long" }); //check again after URI encoding it
|
||||
return;
|
||||
res.json({ error: 'message too long' }) //check again after URI encoding it
|
||||
return
|
||||
}
|
||||
req.body.receiver = encodeURIComponent(req.body.receiver || "");
|
||||
if (req.body.receiver === "" || req.body.receiver === encodeURIComponent(res.locals.username) || req.body.receiver.length > 100) {
|
||||
res.status(417).json({ "error": "invalid receiver given" });
|
||||
return;
|
||||
req.body.receiver = encodeURIComponent(req.body.receiver || '')
|
||||
if (
|
||||
req.body.receiver === '' ||
|
||||
req.body.receiver === encodeURIComponent(res.locals.username) ||
|
||||
req.body.receiver.length > 100
|
||||
) {
|
||||
res.status(417).json({ error: 'invalid receiver given' })
|
||||
return
|
||||
}
|
||||
let otherperson = req.body.receiver;
|
||||
let otherperson = req.body.receiver
|
||||
if (!req.body.message) {
|
||||
res.status(418)
|
||||
res.json({ "error": "no message to post" });
|
||||
return;
|
||||
res.json({ error: 'no message to post' })
|
||||
return
|
||||
}
|
||||
let sql = `insert into ipost.dms (dms_user_name,dms_text,dms_time,dms_receiver,dms_from_bot,dms_reply_id) values (?,?,?,?,?,?);`;
|
||||
let values = [encodeURIComponent(res.locals.username), req.body.message, Date.now(), otherperson, res.locals.isbot, reply_id];
|
||||
let sql = `insert into ipost.dms (dms_user_name,dms_text,dms_time,dms_receiver,dms_from_bot,dms_reply_id) values (?,?,?,?,?,?);`
|
||||
let values = [
|
||||
encodeURIComponent(res.locals.username),
|
||||
req.body.message,
|
||||
Date.now(),
|
||||
otherperson,
|
||||
res.locals.isbot,
|
||||
reply_id,
|
||||
]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err) {
|
||||
res.status(500)
|
||||
res.json({"error":"there's been an internal error"})
|
||||
res.json({ error: "there's been an internal error" })
|
||||
console.error(err)
|
||||
return;
|
||||
return
|
||||
}
|
||||
res.json({ "success": "successfully posted dm" });
|
||||
console.log(5, `posted new dm by ${res.locals.username} to ${otherperson} : ${xor(encodeURIComponent(res.locals.username), otherperson)}`);
|
||||
});
|
||||
res.json({ success: 'successfully posted dm' })
|
||||
console.log(
|
||||
5,
|
||||
`posted new dm by ${res.locals.username} to ${otherperson} : ${xor(encodeURIComponent(res.locals.username), otherperson)}`
|
||||
)
|
||||
})
|
||||
//TODO: bring dms up-to-date with normal posts
|
||||
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
})
|
||||
return createPID
|
||||
};
|
||||
}
|
||||
export default {
|
||||
setup
|
||||
};
|
||||
setup,
|
||||
}
|
||||
|
||||
+24
-19
@@ -1,12 +1,12 @@
|
||||
import sharp from "sharp"
|
||||
async function addTextOnImage(text,buf) {
|
||||
import sharp from 'sharp'
|
||||
async function addTextOnImage(text, buf) {
|
||||
try {
|
||||
let img = await sharp(buf)
|
||||
|
||||
const metadata = await img.metadata()
|
||||
|
||||
const width = metadata.width;
|
||||
const height = metadata.height;
|
||||
const width = metadata.width
|
||||
const height = metadata.height
|
||||
|
||||
const svgImage = `
|
||||
<svg width="${width}" height="${height}">
|
||||
@@ -15,34 +15,39 @@ async function addTextOnImage(text,buf) {
|
||||
</style>
|
||||
<text x="50%" y="50%" text-anchor="middle" class="title">${text}</text>
|
||||
</svg>
|
||||
`;
|
||||
`
|
||||
|
||||
return await img
|
||||
.composite([
|
||||
{
|
||||
input: Buffer.from(svgImage),
|
||||
top: 0,
|
||||
left: 0,
|
||||
},
|
||||
]).webp({effort:6}).toBuffer()
|
||||
{
|
||||
input: Buffer.from(svgImage),
|
||||
top: 0,
|
||||
left: 0,
|
||||
},
|
||||
])
|
||||
.webp({ effort: 6 })
|
||||
.toBuffer()
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
console.log(error)
|
||||
}
|
||||
}
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
router.get("/api/getFileIcon/:icon",async function(req,res){
|
||||
router.get('/api/getFileIcon/:icon', async function (req, res) {
|
||||
let path = req.params.icon
|
||||
if(path.length > 4) {
|
||||
res.status(410).json({"error":"file ending is too long"})
|
||||
return;
|
||||
if (path.length > 4) {
|
||||
res.status(410).json({ error: 'file ending is too long' })
|
||||
return
|
||||
}
|
||||
addTextOnImage(path,await sharp("./images/empty_file.png").toBuffer()).then(buf => {
|
||||
res.set("content-type","image/png")
|
||||
addTextOnImage(
|
||||
path,
|
||||
await sharp('./images/empty_file.png').toBuffer()
|
||||
).then((buf) => {
|
||||
res.set('content-type', 'image/png')
|
||||
res.send(buf)
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+48
-46
@@ -1,65 +1,67 @@
|
||||
export const setup = function (router, con, server) {
|
||||
router.get("/api/getPosts", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
router.get('/api/getPosts', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
if (req.query.channel !== undefined) {
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,User_Avatar,file_0,file_1,file_2,file_3,file_4 from ipost.posts inner join ipost.users on (User_Name = post_user_name) where post_receiver_name = ? group by post_id order by post_id desc limit 30;`;
|
||||
con.query(sql, [encodeURIComponent(req.query.channel)], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
}
|
||||
else { //fallback
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where (post_receiver_name is null or post_receiver_name = 'everyone') group by post_id order by post_id desc limit 30;`;
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,User_Avatar,file_0,file_1,file_2,file_3,file_4 from ipost.posts inner join ipost.users on (User_Name = post_user_name) where post_receiver_name = ? group by post_id order by post_id desc limit 30;`
|
||||
con.query(
|
||||
sql,
|
||||
[encodeURIComponent(req.query.channel)],
|
||||
function (err, result) {
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
//fallback
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where (post_receiver_name is null or post_receiver_name = 'everyone') group by post_id order by post_id desc limit 30;`
|
||||
con.query(sql, [], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
})
|
||||
}
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/getPostsLowerThan", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
})
|
||||
router.get('/api/getPostsLowerThan', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
if (req.query.channel !== undefined) {
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where ((post_receiver_name = ?) and (post_id < ?)) group by post_id order by post_id desc limit 30;`;
|
||||
con.query(sql, [encodeURIComponent(req.query.channel), req.query.id], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
}
|
||||
else { //fallback
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where ((post_receiver_name is null or post_receiver_name = 'everyone') and (post_id < ?)) group by post_id order by post_id desc limit 30;`;
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where ((post_receiver_name = ?) and (post_id < ?)) group by post_id order by post_id desc limit 30;`
|
||||
con.query(
|
||||
sql,
|
||||
[encodeURIComponent(req.query.channel), req.query.id],
|
||||
function (err, result) {
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
//fallback
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4 from ipost.posts where ((post_receiver_name is null or post_receiver_name = 'everyone') and (post_id < ?)) group by post_id order by post_id desc limit 30;`
|
||||
con.query(sql, [req.query.id], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json(result);
|
||||
});
|
||||
if (err) throw err
|
||||
res.json(result)
|
||||
})
|
||||
}
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/getPost", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
let arg = req.query.id;
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,post_receiver_name,User_Avatar,file_0,file_1,file_2,file_3,file_4 from ipost.posts inner join ipost.users on (User_Name = post_user_name) where post_id=?;`;
|
||||
})
|
||||
router.get('/api/getPost', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
let arg = req.query.id
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id,post_from_bot,post_reply_id,post_receiver_name,User_Avatar,file_0,file_1,file_2,file_3,file_4 from ipost.posts inner join ipost.users on (User_Name = post_user_name) where post_id=?;`
|
||||
con.query(sql, [arg], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
res.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
res.json(result[0]);
|
||||
res.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
res.json(result[0])
|
||||
} else {
|
||||
res.json({ error: 'there is no such post!' })
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "there is no such post!" });
|
||||
}
|
||||
});
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+14
-14
@@ -1,18 +1,18 @@
|
||||
function allowAllTraffic(router, str, type) {
|
||||
router.options(str, function (req, res, next) {
|
||||
res.set("Access-Control-Allow-Origin", "test.ipost.rocks"); //we'll allow it for now
|
||||
res.set("Access-Control-Allow-Methods", type || "GET");
|
||||
res.set("Access-Control-Allow-Headers", "Content-Type");
|
||||
res.status(200).send("");
|
||||
});
|
||||
router.options(str, function (req, res, next) {
|
||||
res.set('Access-Control-Allow-Origin', 'test.ipost.rocks') //we'll allow it for now
|
||||
res.set('Access-Control-Allow-Methods', type || 'GET')
|
||||
res.set('Access-Control-Allow-Headers', 'Content-Type')
|
||||
res.status(200).send('')
|
||||
})
|
||||
}
|
||||
function setup(router, con, server) {
|
||||
allowAllTraffic(router, "/api/pid");
|
||||
allowAllTraffic(router, "/api/post", "POST");
|
||||
allowAllTraffic(router, "/api/getotheruser");
|
||||
allowAllTraffic(router, "/api/getPost");
|
||||
allowAllTraffic(router, "/api/getPostsLowerThan");
|
||||
allowAllTraffic(router, "/api/settings");
|
||||
allowAllTraffic(router, "/api/settings", "POST");
|
||||
allowAllTraffic(router, '/api/pid')
|
||||
allowAllTraffic(router, '/api/post', 'POST')
|
||||
allowAllTraffic(router, '/api/getotheruser')
|
||||
allowAllTraffic(router, '/api/getPost')
|
||||
allowAllTraffic(router, '/api/getPostsLowerThan')
|
||||
allowAllTraffic(router, '/api/settings')
|
||||
allowAllTraffic(router, '/api/settings', 'POST')
|
||||
}
|
||||
export { setup };
|
||||
export { setup }
|
||||
|
||||
+169
-126
@@ -1,218 +1,261 @@
|
||||
import sharp from "sharp";
|
||||
import {writeFile} from "fs";
|
||||
import sharp from 'sharp'
|
||||
import { writeFile } from 'fs'
|
||||
|
||||
const image_types = {
|
||||
"png":true,
|
||||
"jpg":true,
|
||||
"jpeg":true,
|
||||
"webp":true,
|
||||
"jfif":true
|
||||
png: true,
|
||||
jpg: true,
|
||||
jpeg: true,
|
||||
webp: true,
|
||||
jfif: true,
|
||||
}
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const PIDS = {}; //[pid]: true/"already_used"
|
||||
const PIDS = {} //[pid]: true/"already_used"
|
||||
|
||||
function isNotNull(a) {
|
||||
return typeof a !== "undefined" && a !== null
|
||||
return typeof a !== 'undefined' && a !== null
|
||||
}
|
||||
|
||||
function createPID(){
|
||||
let pid = server.genstring(10); //collision chance is low enough, but we'll check anyways
|
||||
function createPID() {
|
||||
let pid = server.genstring(10) //collision chance is low enough, but we'll check anyways
|
||||
while (PIDS[pid] !== undefined) {
|
||||
pid = server.genstring(10);
|
||||
console.log(5, "pid collision");
|
||||
pid = server.genstring(10)
|
||||
console.log(5, 'pid collision')
|
||||
}
|
||||
PIDS[pid] = true;
|
||||
setTimeout(function() {
|
||||
PIDS[pid] = undefined;
|
||||
}, 40000);
|
||||
PIDS[pid] = true
|
||||
setTimeout(function () {
|
||||
PIDS[pid] = undefined
|
||||
}, 40000)
|
||||
return pid
|
||||
}
|
||||
|
||||
router.get("/api/pid", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
res.json({ "pid": createPID() });
|
||||
router.get('/api/pid', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
res.json({ pid: createPID() })
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
})
|
||||
|
||||
function validateMessage(message) {
|
||||
if (!message) {
|
||||
throw {
|
||||
statusCode: 410,
|
||||
message: "no message to post"
|
||||
message: 'no message to post',
|
||||
}
|
||||
}
|
||||
if ((typeof message) !== "string") {
|
||||
if (typeof message !== 'string') {
|
||||
throw {
|
||||
statusCode: 411,
|
||||
message: "no message to post"
|
||||
message: 'no message to post',
|
||||
}
|
||||
}
|
||||
if (message.length > 1000) {
|
||||
throw {
|
||||
statusCode: 416,
|
||||
message: "message too long"
|
||||
message: 'message too long',
|
||||
}
|
||||
}
|
||||
message = encodeURIComponent(message.trim());
|
||||
message = encodeURIComponent(message.trim())
|
||||
if (message.length > 3000) {
|
||||
throw {
|
||||
statusCode: 417,
|
||||
message: "message too long"
|
||||
message: 'message too long',
|
||||
}
|
||||
}
|
||||
if (!message) {
|
||||
throw {
|
||||
statusCode: 418,
|
||||
message: "no message to post"
|
||||
message: 'no message to post',
|
||||
}
|
||||
} //backup check
|
||||
return message
|
||||
}
|
||||
|
||||
function validatePID(pid) {
|
||||
if (!pid || typeof pid !== "string") {
|
||||
if (!pid || typeof pid !== 'string') {
|
||||
throw {
|
||||
statusCode: 412,
|
||||
message: "no pid given"
|
||||
message: 'no pid given',
|
||||
}
|
||||
}
|
||||
if (pid.length !== 10 || PIDS[pid]!==true) {
|
||||
if (pid.length !== 10 || PIDS[pid] !== true) {
|
||||
throw {
|
||||
statusCode: 413,
|
||||
message: "invalid pid given"
|
||||
message: 'invalid pid given',
|
||||
}
|
||||
}
|
||||
PIDS[pid] = "already_used";
|
||||
PIDS[pid] = 'already_used'
|
||||
}
|
||||
|
||||
function validateReplyID(rid) {
|
||||
let reply_id;
|
||||
let reply_id
|
||||
if (!rid || rid < 0) {
|
||||
reply_id = 0
|
||||
}
|
||||
if(typeof rid === "string" && rid !== "") {
|
||||
reply_id = parseInt(rid,10)
|
||||
if(isNaN(reply_id)) {
|
||||
if (typeof rid === 'string' && rid !== '') {
|
||||
reply_id = parseInt(rid, 10)
|
||||
if (isNaN(reply_id)) {
|
||||
throw {
|
||||
statusCode: 414,
|
||||
message: "no valid reply id given"
|
||||
message: 'no valid reply id given',
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof reply_id !== "number") {
|
||||
if (typeof reply_id !== 'number') {
|
||||
throw {
|
||||
statusCode: 415,
|
||||
message: "no valid reply id given"
|
||||
message: 'no valid reply id given',
|
||||
} //backup case
|
||||
}
|
||||
return reply_id
|
||||
}
|
||||
|
||||
function validateReceiver(rec) {
|
||||
let receiver = encodeURIComponent(rec || "");
|
||||
if (receiver === "")
|
||||
receiver = "everyone";
|
||||
let receiver = encodeURIComponent(rec || '')
|
||||
if (receiver === '') receiver = 'everyone'
|
||||
return receiver
|
||||
}
|
||||
|
||||
router.post("/api/post", async (req, res) => {
|
||||
router.post('/api/post', async (req, res) => {
|
||||
try {
|
||||
let message = validateMessage(req.body.message);
|
||||
validatePID(req.body.pid);
|
||||
let reply_id = validateReplyID(req.body.reply_id);
|
||||
let receiver = validateReceiver(req.body.receiver);
|
||||
let message = validateMessage(req.body.message)
|
||||
validatePID(req.body.pid)
|
||||
let reply_id = validateReplyID(req.body.reply_id)
|
||||
let receiver = validateReceiver(req.body.receiver)
|
||||
|
||||
let __dirname = server.dirname
|
||||
const file_names = ["","","","",""]
|
||||
if(isNotNull(req.files)) {
|
||||
for(let file_index=0;file_index<5;file_index++) {
|
||||
if(isNotNull(req.files[`file_${file_index}`])) {
|
||||
let file = req.files[`file_${file_index}`]
|
||||
const file_id = server.genstring(20)
|
||||
const file_name = `${file_id}/${(file.name.substring(0,25)).replace(/\.[^/.]+$/, "")}`
|
||||
let extension = file.name.substring(file.name.lastIndexOf("\.")+1)
|
||||
file_names[file_index]=`${file_name}${(extension in image_types && ".webp") || extension}`
|
||||
server.ensureExists(`${__dirname}/user_uploads/${file_id}`,undefined,async (err)=>{
|
||||
if(err) {
|
||||
let __dirname = server.dirname
|
||||
const file_names = ['', '', '', '', '']
|
||||
if (isNotNull(req.files)) {
|
||||
for (let file_index = 0; file_index < 5; file_index++) {
|
||||
if (isNotNull(req.files[`file_${file_index}`])) {
|
||||
let file = req.files[`file_${file_index}`]
|
||||
const file_id = server.genstring(20)
|
||||
const file_name = `${file_id}/${file.name.substring(0, 25).replace(/\.[^/.]+$/, '')}`
|
||||
let extension = file.name.substring(
|
||||
file.name.lastIndexOf('\.') + 1
|
||||
)
|
||||
file_names[file_index] =
|
||||
`${file_name}${(extension in image_types && '.webp') || extension}`
|
||||
server.ensureExists(
|
||||
`${__dirname}/user_uploads/${file_id}`,
|
||||
undefined,
|
||||
async (err) => {
|
||||
if (err) {
|
||||
console.error(err)
|
||||
return
|
||||
}
|
||||
if (extension in image_types) {
|
||||
writeFile(
|
||||
`${__dirname}/user_uploads/${file_name}.webp`,
|
||||
await sharp(file.data)
|
||||
.webp({ mixed: true, effort: 6 })
|
||||
.toBuffer(),
|
||||
(err2) => {
|
||||
if (err2) console.error(err2)
|
||||
}
|
||||
)
|
||||
server.ensureExists(
|
||||
`${__dirname}/user_uploads/previews/${file_id}`,
|
||||
undefined,
|
||||
async (error) => {
|
||||
if (error) {
|
||||
console.error(error)
|
||||
return
|
||||
}
|
||||
writeFile(
|
||||
`${__dirname}/user_uploads/previews/${file_name}.webp`,
|
||||
await sharp(file.data)
|
||||
.resize(100, 100, {
|
||||
fit: 'inside',
|
||||
})
|
||||
.webp({
|
||||
mixed: true,
|
||||
effort: 6,
|
||||
})
|
||||
.toBuffer(),
|
||||
(error2) => {
|
||||
if (error2)
|
||||
console.error(error2)
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
file.mv(
|
||||
`${__dirname}/user_uploads/${file_name}.${extension}`,
|
||||
(err2) => {
|
||||
if (err2) console.error(err2)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sql = `START TRANSACTION;INSERT INTO ipost.posts (post_user_name,post_text,post_time,post_receiver_name,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4) VALUES (?,?,?,?,?,?,?,?,?,?,?);SELECT LAST_INSERT_ID() as ID;COMMIT;`
|
||||
let values = [
|
||||
encodeURIComponent(res.locals.username),
|
||||
message,
|
||||
Date.now(),
|
||||
receiver,
|
||||
res.locals.isbot,
|
||||
reply_id,
|
||||
...file_names,
|
||||
]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err) {
|
||||
res.status(500)
|
||||
res.json({ error: "there's been an interal error" })
|
||||
console.error(err)
|
||||
return;
|
||||
}
|
||||
if(extension in image_types) {
|
||||
writeFile(`${__dirname}/user_uploads/${file_name}.webp`,await sharp(file.data).webp({mixed:true,effort:6}).toBuffer(),(err2)=>{
|
||||
if(err2)console.error(err2)
|
||||
})
|
||||
server.ensureExists(`${__dirname}/user_uploads/previews/${file_id}`,undefined,async (error) => {
|
||||
if(error) {
|
||||
console.error(error)
|
||||
return;
|
||||
}
|
||||
writeFile(`${__dirname}/user_uploads/previews/${file_name}.webp`,await sharp(file.data).resize(100,100,{fit: "inside"}).webp({mixed:true,effort:6}).toBuffer(),(error2)=>{
|
||||
if(error2)console.error(error2)
|
||||
})
|
||||
})
|
||||
} else {
|
||||
file.mv(`${__dirname}/user_uploads/${file_name}.${extension}`,(err2)=>{
|
||||
if(err2)console.error(err2)
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
let post_obj = {
|
||||
post_user_name: encodeURIComponent(res.locals.username),
|
||||
post_text: req.body.message,
|
||||
post_time: Date.now(),
|
||||
post_special_text: '',
|
||||
post_receiver_name: req.body.receiver,
|
||||
post_from_bot: res.locals.isbot,
|
||||
post_reply_id: reply_id,
|
||||
user_avatar: res.locals.avatar,
|
||||
files: file_names,
|
||||
post_id: result[0].ID,
|
||||
}
|
||||
let message = {
|
||||
message: 'new_post',
|
||||
data: post_obj,
|
||||
}
|
||||
let messagestr = JSON.stringify(message)
|
||||
//console.log(5,server.wss.clients); /* DEBUG: Log websocket clients */
|
||||
server.wss.clients.forEach(function (ws) {
|
||||
//console.log(5,ws); /* DEBUG: Log websocket clients */
|
||||
ws.send(messagestr)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sql = `START TRANSACTION;INSERT INTO ipost.posts (post_user_name,post_text,post_time,post_receiver_name,post_from_bot,post_reply_id,file_0,file_1,file_2,file_3,file_4) VALUES (?,?,?,?,?,?,?,?,?,?,?);SELECT LAST_INSERT_ID() as ID;COMMIT;`;
|
||||
let values = [encodeURIComponent(res.locals.username), message, Date.now(), receiver, res.locals.isbot, reply_id,...file_names];
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err){
|
||||
res.status(500)
|
||||
res.json({"error":"there's been an interal error"})
|
||||
console.error(err)
|
||||
return;
|
||||
}
|
||||
let post_obj = {
|
||||
post_user_name: encodeURIComponent(res.locals.username),
|
||||
post_text: req.body.message,
|
||||
post_time: Date.now(),
|
||||
post_special_text: "",
|
||||
post_receiver_name: req.body.receiver,
|
||||
post_from_bot: res.locals.isbot,
|
||||
post_reply_id: reply_id,
|
||||
user_avatar: res.locals.avatar,
|
||||
files: file_names,
|
||||
post_id: result[0].ID
|
||||
};
|
||||
let message = {
|
||||
message: "new_post",
|
||||
data: post_obj
|
||||
};
|
||||
let messagestr = JSON.stringify(message);
|
||||
//console.log(5,server.wss.clients); /* DEBUG: Log websocket clients */
|
||||
server.wss.clients.forEach(function(ws) {
|
||||
//console.log(5,ws); /* DEBUG: Log websocket clients */
|
||||
ws.send(messagestr);
|
||||
});
|
||||
res.json({ "success": "successfully posted message" });
|
||||
console.log(5, `posted new message by ${res.locals.username} : ${req.body.message}`);
|
||||
});
|
||||
res.json({ success: 'successfully posted message' })
|
||||
console.log(
|
||||
5,
|
||||
`posted new message by ${res.locals.username} : ${req.body.message}`
|
||||
)
|
||||
})
|
||||
} catch (error) {
|
||||
if(error.statusCode) {
|
||||
if (error.statusCode) {
|
||||
res.status(error.statusCode)
|
||||
res.json({ "error": error.message, "status": error.statusCode });
|
||||
res.json({ error: error.message, status: error.statusCode })
|
||||
} else {
|
||||
console.error("some error: ", error)
|
||||
console.error('some error: ', error)
|
||||
res.status(500)
|
||||
res.json({"error":"internal server error", "status": 500})
|
||||
res.json({ error: 'internal server error', status: 500 })
|
||||
}
|
||||
}
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
})
|
||||
return createPID
|
||||
};
|
||||
}
|
||||
export default {
|
||||
setup
|
||||
};
|
||||
setup,
|
||||
}
|
||||
|
||||
+32
-30
@@ -1,42 +1,44 @@
|
||||
export const setup = function (router, con, server) {
|
||||
router.get("/api/search", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
let type = req.query.type;
|
||||
let arg = encodeURIComponent(req.query.selector);
|
||||
if (type === "user") {
|
||||
let sql = `select User_Name,User_Bio,User_Avatar from ipost.users where User_Name like ? limit 10;`;
|
||||
router.get('/api/search', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
let type = req.query.type
|
||||
let arg = encodeURIComponent(req.query.selector)
|
||||
if (type === 'user') {
|
||||
let sql = `select User_Name,User_Bio,User_Avatar from ipost.users where User_Name like ? limit 10;`
|
||||
con.query(sql, [`%${arg}%`], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
result["message"] = "search has been deprecated as of 11/30/2022"
|
||||
res.json(result);
|
||||
result['message'] =
|
||||
'search has been deprecated as of 11/30/2022'
|
||||
res.json(result)
|
||||
} else {
|
||||
res.json({ error: 'there is no such user!' })
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "there is no such user!" });
|
||||
}
|
||||
});
|
||||
}
|
||||
else if (type === "post") {
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id from ipost.posts where post_text like ? and (post_receiver_name is null or post_receiver_name = 'everyone') order by post_id desc limit 20;`;
|
||||
})
|
||||
} else if (type === 'post') {
|
||||
let sql = `select post_user_name,post_text,post_time,post_special_text,post_id from ipost.posts where post_text like ? and (post_receiver_name is null or post_receiver_name = 'everyone') order by post_id desc limit 20;`
|
||||
con.query(sql, [`%${arg}%`], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
result["message"] = "search has been deprecated as of 11/30/2022"
|
||||
res.json(result);
|
||||
result['message'] =
|
||||
'search has been deprecated as of 11/30/2022'
|
||||
res.json(result)
|
||||
} else {
|
||||
res.json({
|
||||
error: 'there is no such post!',
|
||||
message: 'search has been deprecated as of 11/30/2022',
|
||||
})
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "there is no such post!", "message": "search has been deprecated as of 11/30/2022"});
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "invalid type passed along, expected `user` or `post`", "message": "search has been deprecated as of 11/30/2022"});
|
||||
})
|
||||
} else {
|
||||
res.json({
|
||||
error: 'invalid type passed along, expected `user` or `post`',
|
||||
message: 'search has been deprecated as of 11/30/2022',
|
||||
})
|
||||
}
|
||||
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,60 +1,71 @@
|
||||
const allowed_settings = {
|
||||
"ACCR": ["boolean"]
|
||||
};
|
||||
ACCR: ['boolean'],
|
||||
}
|
||||
export const setup = function (router, con, server) {
|
||||
router.get("/api/settings", function (req, res) {
|
||||
res.json(res.locals.settings);
|
||||
router.get('/api/settings', function (req, res) {
|
||||
res.json(res.locals.settings)
|
||||
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.post("/api/settings", function (req, res) {
|
||||
})
|
||||
router.post('/api/settings', function (req, res) {
|
||||
if (!req.body.setting) {
|
||||
res.status(410)
|
||||
res.json({ "error": "no setting to change" });
|
||||
return;
|
||||
res.json({ error: 'no setting to change' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.setting) !== "string") {
|
||||
if (typeof req.body.setting !== 'string') {
|
||||
res.status(411)
|
||||
res.json({ "error": "no setting to change" });
|
||||
return;
|
||||
res.json({ error: 'no setting to change' })
|
||||
return
|
||||
}
|
||||
let types = allowed_settings[req.body.setting];
|
||||
let allowed = false;
|
||||
let got = typeof req.body.value;
|
||||
let types = allowed_settings[req.body.setting]
|
||||
let allowed = false
|
||||
let got = typeof req.body.value
|
||||
for (let index = 0; index < types.length; index++) {
|
||||
if (types[index] === got) {
|
||||
allowed = true;
|
||||
break;
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!allowed) {
|
||||
console.log(5, "incorrect type given, received, expected", typeof req.body.value, allowed_settings[req.body.setting]);
|
||||
console.log(
|
||||
5,
|
||||
'incorrect type given, received, expected',
|
||||
typeof req.body.value,
|
||||
allowed_settings[req.body.setting]
|
||||
)
|
||||
res.status(412)
|
||||
res.json({ "error": "no new setting value given" });
|
||||
return;
|
||||
res.json({ error: 'no new setting value given' })
|
||||
return
|
||||
}
|
||||
let setting_to_change = req.body.setting;
|
||||
let setting_new_value = req.body.value;
|
||||
res.locals.settings[setting_to_change] = setting_new_value;
|
||||
console.log(5, "changing settings", setting_to_change, setting_new_value, res.locals.settings);
|
||||
let sql = "update ipost.users set User_Settings=? where User_Name=?";
|
||||
let values = [JSON.stringify(res.locals.settings), res.locals.username];
|
||||
let setting_to_change = req.body.setting
|
||||
let setting_new_value = req.body.value
|
||||
res.locals.settings[setting_to_change] = setting_new_value
|
||||
console.log(
|
||||
5,
|
||||
'changing settings',
|
||||
setting_to_change,
|
||||
setting_new_value,
|
||||
res.locals.settings
|
||||
)
|
||||
let sql = 'update ipost.users set User_Settings=? where User_Name=?'
|
||||
let values = [JSON.stringify(res.locals.settings), res.locals.username]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err) {
|
||||
res.status(500)
|
||||
res.json({ "status": "error", "code": err });
|
||||
return;
|
||||
res.json({ status: 'error', code: err })
|
||||
return
|
||||
}
|
||||
res.json({ "status": "success" });
|
||||
});
|
||||
res.json({ status: 'success' })
|
||||
})
|
||||
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
export default {
|
||||
setup
|
||||
};
|
||||
setup,
|
||||
}
|
||||
|
||||
+237
-178
@@ -1,234 +1,293 @@
|
||||
import sharp from "sharp"
|
||||
import { ensureExists } from "../../extra_modules/ensureExists.js"
|
||||
import {SHA256} from "../../extra_modules/SHA.js";
|
||||
import getIP from "../../extra_modules/getip.js";
|
||||
import {getunsigned} from "../../extra_modules/unsign.js";
|
||||
import sharp from 'sharp'
|
||||
import { ensureExists } from '../../extra_modules/ensureExists.js'
|
||||
import { SHA256 } from '../../extra_modules/SHA.js'
|
||||
import getIP from '../../extra_modules/getip.js'
|
||||
import { getunsigned } from '../../extra_modules/unsign.js'
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const config = server.config
|
||||
const HASHES_DB = config.cookies.server_hashes;
|
||||
const HASHES_COOKIE = config.cookies.client_hashes;
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE;
|
||||
router.post("/api/setavatar", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
const HASHES_DB = config.cookies.server_hashes
|
||||
const HASHES_COOKIE = config.cookies.client_hashes
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE
|
||||
const __dirname = server.dirname
|
||||
|
||||
router.post('/api/setavatar', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
if (!req.files || Object.keys(req.files).length === 0) {
|
||||
return res.status(410).send('No files were uploaded. (req.files)');
|
||||
return res.status(410).send('No files were uploaded. (req.files)')
|
||||
}
|
||||
let avatar = req.files.avatar;
|
||||
let avatar = req.files.avatar
|
||||
if (!avatar) {
|
||||
return res.status(411).send('No files were uploaded. (req.files.)');
|
||||
return res.status(411).send('No files were uploaded. (req.files.)')
|
||||
}
|
||||
const avatars = __dirname + '/avatars/';
|
||||
const avatars = __dirname + '/avatars/'
|
||||
ensureExists(avatars, function (err) {
|
||||
if (err) {
|
||||
return res.status(500).json({ "error": "there's been an internal server error." });
|
||||
return res
|
||||
.status(500)
|
||||
.json({ error: "there's been an internal server error." })
|
||||
}
|
||||
if (res.locals.avatar) {
|
||||
try {
|
||||
unlinkSync(avatars + res.locals.avatar);
|
||||
} catch(ignored){}
|
||||
unlinkSync(avatars + res.locals.avatar)
|
||||
} catch (ignored) {}
|
||||
}
|
||||
let filename = genstring(95) + ".webp";
|
||||
while (existsSync(avatars + "/" + filename) || filename === ".webp") { //generate new filename until it's unique
|
||||
filename = genstring(95) + ".webp";
|
||||
let filename = genstring(95) + '.webp'
|
||||
while (
|
||||
existsSync(avatars + '/' + filename) ||
|
||||
filename === '.webp'
|
||||
) {
|
||||
//generate new filename until it's unique
|
||||
filename = genstring(95) + '.webp'
|
||||
}
|
||||
sharp(avatar.data).resize({ //resize avatar to 100x100 and convert it to a webp, then store it
|
||||
width: 100,
|
||||
height: 100
|
||||
}).webp({
|
||||
effort: 6,
|
||||
mixed: true
|
||||
}).toBuffer().then(function(data){
|
||||
writeFileSync(avatars + filename,data)
|
||||
let sql = `update ipost.users set User_Avatar=? where User_Name=?`;
|
||||
con.query(sql, [filename, encodeURIComponent(res.locals.username)], function (err) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json({ "success": "updated avatar" });
|
||||
});
|
||||
})
|
||||
});
|
||||
sharp(avatar.data)
|
||||
.resize({
|
||||
//resize avatar to 100x100 and convert it to a webp, then store it
|
||||
width: 100,
|
||||
height: 100,
|
||||
})
|
||||
.webp({
|
||||
effort: 6,
|
||||
mixed: true,
|
||||
})
|
||||
.toBuffer()
|
||||
.then(function (data) {
|
||||
writeFileSync(avatars + filename, data)
|
||||
let sql = `update ipost.users set User_Avatar=? where User_Name=?`
|
||||
con.query(
|
||||
sql,
|
||||
[filename, encodeURIComponent(res.locals.username)],
|
||||
function (err) {
|
||||
if (err) throw err
|
||||
res.json({ success: 'updated avatar' })
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/getuser", function (_req, res) {
|
||||
res.json({ "username": res.locals.username, "bio": res.locals.bio, "avatar": res.locals.avatar, "userid": res.locals.userid });
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
router.get('/api/getuser', function (_req, res) {
|
||||
res.json({
|
||||
username: res.locals.username,
|
||||
bio: res.locals.bio,
|
||||
avatar: res.locals.avatar,
|
||||
userid: res.locals.userid,
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/getalluserinformation", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", ""); //we don't want that here
|
||||
let unsigned = getunsigned(req, res); //has to be asking for it via the cookie
|
||||
if (!unsigned)
|
||||
return;
|
||||
unsigned = decodeURIComponent(unsigned);
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;`;
|
||||
let values = unsigned.split(" ");
|
||||
values[1] = SHA256(values[1], values[0], HASHES_DIFF);
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
router.get('/api/getalluserinformation', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '') //we don't want that here
|
||||
let unsigned = getunsigned(req, res) //has to be asking for it via the cookie
|
||||
if (!unsigned) return
|
||||
unsigned = decodeURIComponent(unsigned)
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;`
|
||||
let values = unsigned.split(' ')
|
||||
values[1] = SHA256(values[1], values[0], HASHES_DIFF)
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
res.status(200);
|
||||
res.json(result[0]);
|
||||
res.status(200)
|
||||
res.json(result[0])
|
||||
} else {
|
||||
res.status(402)
|
||||
res.json({
|
||||
error: 'you cannot access the api without being logged in',
|
||||
})
|
||||
}
|
||||
else {
|
||||
res.status(402);
|
||||
res.json({ "error": "you cannot access the api without being logged in" });
|
||||
}
|
||||
});
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.get("/api/getotheruser", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
let username = req.query.user;
|
||||
let sql = `select User_Name,User_Bio,User_Avatar from ipost.users where User_Name=?;`;
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
router.get('/api/getotheruser', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '*')
|
||||
let username = req.query.user
|
||||
let sql = `select User_Name,User_Bio,User_Avatar from ipost.users where User_Name=?;`
|
||||
con.query(sql, [username], function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
res.json({ "username": username, "bio": result[0].User_Bio, "avatar": result[0].User_Avatar, "publicKey": result[0].User_PublicKey });
|
||||
res.json({
|
||||
username: username,
|
||||
bio: result[0].User_Bio,
|
||||
avatar: result[0].User_Avatar,
|
||||
publicKey: result[0].User_PublicKey,
|
||||
})
|
||||
} else {
|
||||
res.json({ error: 'there is no such user!' })
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "there is no such user!" });
|
||||
}
|
||||
});
|
||||
});
|
||||
router.post("/api/setBio", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
let bio = req.body.Bio;
|
||||
})
|
||||
})
|
||||
router.post('/api/setBio', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
let bio = req.body.Bio
|
||||
if (!bio) {
|
||||
res.status(410);
|
||||
res.json({ "error": "no bio set!" });
|
||||
return;
|
||||
res.status(410)
|
||||
res.json({ error: 'no bio set!' })
|
||||
return
|
||||
}
|
||||
bio = encodeURIComponent(bio);
|
||||
bio = encodeURIComponent(bio)
|
||||
if (bio.length > 100) {
|
||||
res.status(411);
|
||||
res.json({ "error": "the bio is too long!" });
|
||||
return;
|
||||
res.status(411)
|
||||
res.json({ error: 'the bio is too long!' })
|
||||
return
|
||||
}
|
||||
let sql = `update ipost.users set User_Bio=? where User_Name=?`;
|
||||
con.query(sql, [bio, encodeURIComponent(res.locals.username)], function (err) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.json({ "success": "updated bio" });
|
||||
});
|
||||
let sql = `update ipost.users set User_Bio=? where User_Name=?`
|
||||
con.query(
|
||||
sql,
|
||||
[bio, encodeURIComponent(res.locals.username)],
|
||||
function (err) {
|
||||
if (err) throw err
|
||||
res.json({ success: 'updated bio' })
|
||||
}
|
||||
)
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.post("/api/changePW", (req, res) => {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
if ((typeof req.body.newPW) !== "string") {
|
||||
res.json({ "error": "incorrect password" });
|
||||
return;
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
router.post('/api/changePW', (req, res) => {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
if (typeof req.body.newPW !== 'string') {
|
||||
res.json({ error: 'incorrect password' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.currentPW) !== "string") {
|
||||
res.json({ "error": "incorrect password" });
|
||||
return;
|
||||
if (typeof req.body.currentPW !== 'string') {
|
||||
res.json({ error: 'incorrect password' })
|
||||
return
|
||||
}
|
||||
if (req.body.newPW.length < 10) {
|
||||
res.status(410);
|
||||
res.json({ "error": "password is too short" });
|
||||
return;
|
||||
res.status(410)
|
||||
res.json({ error: 'password is too short' })
|
||||
return
|
||||
}
|
||||
let hashed_pw = SHA256(req.body.currentPW, res.locals.username, HASHES_DB);
|
||||
let hashed_new_pw = SHA256(req.body.newPW, res.locals.username, HASHES_DB);
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;`;
|
||||
let values = [res.locals.username, hashed_pw];
|
||||
let hashed_pw = SHA256(
|
||||
req.body.currentPW,
|
||||
res.locals.username,
|
||||
HASHES_DB
|
||||
)
|
||||
let hashed_new_pw = SHA256(
|
||||
req.body.newPW,
|
||||
res.locals.username,
|
||||
HASHES_DB
|
||||
)
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;`
|
||||
let values = [res.locals.username, hashed_pw]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
let sql = `update ipost.users set User_PW=? where User_Name=? and User_PW=?;`;
|
||||
let values = [hashed_new_pw, res.locals.username, hashed_pw];
|
||||
let sql = `update ipost.users set User_PW=? where User_Name=? and User_PW=?;`
|
||||
let values = [hashed_new_pw, res.locals.username, hashed_pw]
|
||||
con.query(sql, values, (err2) => {
|
||||
if (err2)
|
||||
throw err2;
|
||||
let ip = getIP(req);
|
||||
if (err2) throw err2
|
||||
let ip = getIP(req)
|
||||
let setTo = `${res.locals.username} ${SHA256(req.body.newPW, res.locals.username, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + ip);
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, { maxAge: Math.pow(10, 10), httpOnly: true, secure: true });
|
||||
res.json({ "success": "successfully changed password" });
|
||||
});
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + ip)
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, {
|
||||
maxAge: Math.pow(10, 10),
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
})
|
||||
res.json({ success: 'successfully changed password' })
|
||||
})
|
||||
} else {
|
||||
res.json({ error: 'invalid password' })
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "invalid password" });
|
||||
}
|
||||
});
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
router.post("/api/changeUsername", function (req, res) {
|
||||
res.set("Access-Control-Allow-Origin", "");
|
||||
if ((typeof req.body.newUsername) !== "string") {
|
||||
res.status(410);
|
||||
res.json({ "error": "incorrect username" });
|
||||
return;
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
router.post('/api/changeUsername', function (req, res) {
|
||||
res.set('Access-Control-Allow-Origin', '')
|
||||
if (typeof req.body.newUsername !== 'string') {
|
||||
res.status(410)
|
||||
res.json({ error: 'incorrect username' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.currentPW) !== "string") {
|
||||
res.status(411);
|
||||
res.json({ "error": "incorrect password" });
|
||||
return;
|
||||
if (typeof req.body.currentPW !== 'string') {
|
||||
res.status(411)
|
||||
res.json({ error: 'incorrect password' })
|
||||
return
|
||||
}
|
||||
if (req.body.newUsername.length > 100) {
|
||||
res.status(412);
|
||||
res.json({ "error": "username is too long" });
|
||||
return;
|
||||
res.status(412)
|
||||
res.json({ error: 'username is too long' })
|
||||
return
|
||||
}
|
||||
if (req.body.newUsername === res.locals.username) {
|
||||
res.status(413);
|
||||
res.json({ "error": "username can't be the current one" });
|
||||
return;
|
||||
res.status(413)
|
||||
res.json({ error: "username can't be the current one" })
|
||||
return
|
||||
}
|
||||
let hashed_pw = SHA256(req.body.currentPW, res.locals.username, HASHES_DB);
|
||||
let hashed_new_pw = SHA256(req.body.currentPW, req.body.newUsername, HASHES_DB);
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;`; //check if pw is correct
|
||||
let values = [res.locals.username,hashed_pw];
|
||||
let hashed_pw = SHA256(
|
||||
req.body.currentPW,
|
||||
res.locals.username,
|
||||
HASHES_DB
|
||||
)
|
||||
let hashed_new_pw = SHA256(
|
||||
req.body.currentPW,
|
||||
req.body.newUsername,
|
||||
HASHES_DB
|
||||
)
|
||||
let sql = `select * from ipost.users where User_Name=? and User_PW=?;` //check if pw is correct
|
||||
let values = [res.locals.username, hashed_pw]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
let sql = `select * from ipost.users where User_Name=?;`; //check if newUsername isn't already used
|
||||
let values = [req.body.newUsername];
|
||||
let sql = `select * from ipost.users where User_Name=?;` //check if newUsername isn't already used
|
||||
let values = [req.body.newUsername]
|
||||
con.query(sql, values, function (err, result) {
|
||||
if (err)
|
||||
throw err;
|
||||
if (err) throw err
|
||||
if (result[0]) {
|
||||
res.json({ "error": "user with that username already exists" });
|
||||
return;
|
||||
res.json({
|
||||
error: 'user with that username already exists',
|
||||
})
|
||||
return
|
||||
}
|
||||
let sql = `update ipost.users set User_PW=?,User_Name=? where User_Name=? and User_PW=?;`; //change username in users
|
||||
let values = [hashed_new_pw, req.body.newUsername, res.locals.username, hashed_pw];
|
||||
let sql = `update ipost.users set User_PW=?,User_Name=? where User_Name=? and User_PW=?;` //change username in users
|
||||
let values = [
|
||||
hashed_new_pw,
|
||||
req.body.newUsername,
|
||||
res.locals.username,
|
||||
hashed_pw,
|
||||
]
|
||||
con.query(sql, values, function (err) {
|
||||
if (err)
|
||||
throw err;
|
||||
let ip = getIP(req);
|
||||
if (err) throw err
|
||||
let ip = getIP(req)
|
||||
let setTo = `${req.body.newUsername} ${SHA256(req.body.currentPW, req.body.newUsername, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + ip);
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, { maxAge: Math.pow(10, 10), httpOnly: true, secure: true });
|
||||
let cookiesigned = signature.sign(
|
||||
setTo,
|
||||
cookiesecret + ip
|
||||
)
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, {
|
||||
maxAge: Math.pow(10, 10),
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
})
|
||||
//updated username in the users table, but not yet on posts
|
||||
//TODO: update username on dms
|
||||
let sql = `update ipost.posts set post_user_name=? where post_user_name=?;`; //change username of every past post sent
|
||||
let values = [req.body.newUsername, res.locals.username, hashed_pw];
|
||||
let sql = `update ipost.posts set post_user_name=? where post_user_name=?;` //change username of every past post sent
|
||||
let values = [
|
||||
req.body.newUsername,
|
||||
res.locals.username,
|
||||
hashed_pw,
|
||||
]
|
||||
con.query(sql, values, () => {
|
||||
res.json({ "success": "successfully changed username" }); //done
|
||||
});
|
||||
});
|
||||
});
|
||||
res.json({
|
||||
success: 'successfully changed username',
|
||||
}) //done
|
||||
})
|
||||
})
|
||||
})
|
||||
} else {
|
||||
res.json({ error: 'invalid password' })
|
||||
}
|
||||
else {
|
||||
res.json({ "error": "invalid password" });
|
||||
}
|
||||
});
|
||||
})
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
});
|
||||
}
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
})
|
||||
}
|
||||
|
||||
+89
-68
@@ -1,59 +1,72 @@
|
||||
import {randomBytes} from "crypto"
|
||||
import {SHA256} from "../extra_modules/SHA.js";
|
||||
import {unsign} from "../extra_modules/unsign.js";
|
||||
import { randomBytes } from 'crypto'
|
||||
import { SHA256 } from '../extra_modules/SHA.js'
|
||||
import { unsign } from '../extra_modules/unsign.js'
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const temp_code_to_token = {}
|
||||
router.post("/authorize",async (req,res) => {
|
||||
if (!unsign(req.cookies.AUTH_COOKIE, req, res)){
|
||||
router.post('/authorize', async (req, res) => {
|
||||
if (!unsign(req.cookies.AUTH_COOKIE, req, res)) {
|
||||
return
|
||||
}
|
||||
|
||||
let data = await server.hcaptcha.verify(req.body["h-captcha-response"])
|
||||
|
||||
if(data.success) {
|
||||
let data = await server.hcaptcha.verify(req.body['h-captcha-response'])
|
||||
|
||||
if (data.success) {
|
||||
let appid = req.body.application_id
|
||||
if(typeof appid === "string") {
|
||||
if (typeof appid === 'string') {
|
||||
appid = Number(appid)
|
||||
}
|
||||
if(typeof appid === "number") {
|
||||
if (typeof appid === 'number') {
|
||||
const token = randomBytes(150).toString('base64')
|
||||
|
||||
const token = randomBytes(150).toString("base64")
|
||||
|
||||
let tokencode;
|
||||
while(tokencode===undefined || temp_code_to_token[tokencode]!==undefined) {
|
||||
tokencode = randomBytes(15).toString("base64").replaceAll("/","f").replaceAll("+","A") //"/" and "+" may break some apps
|
||||
let tokencode
|
||||
while (
|
||||
tokencode === undefined ||
|
||||
temp_code_to_token[tokencode] !== undefined
|
||||
) {
|
||||
tokencode = randomBytes(15)
|
||||
.toString('base64')
|
||||
.replaceAll('/', 'f')
|
||||
.replaceAll('+', 'A') //"/" and "+" may break some apps
|
||||
}
|
||||
temp_code_to_token[tokencode]={
|
||||
"userid":res.locals.userid,
|
||||
"appid":appid,
|
||||
"token":token
|
||||
temp_code_to_token[tokencode] = {
|
||||
userid: res.locals.userid,
|
||||
appid: appid,
|
||||
token: token,
|
||||
}
|
||||
setTimeout(() => {
|
||||
let data = temp_code_to_token[tokencode]
|
||||
if(data !== undefined && data.token===token && data.appid === appid && data.userid === res.locals.userid) {
|
||||
temp_code_to_token[tokencode]=undefined
|
||||
}
|
||||
}, 1000*60*5);
|
||||
setTimeout(
|
||||
() => {
|
||||
let data = temp_code_to_token[tokencode]
|
||||
if (
|
||||
data !== undefined &&
|
||||
data.token === token &&
|
||||
data.appid === appid &&
|
||||
data.userid === res.locals.userid
|
||||
) {
|
||||
temp_code_to_token[tokencode] = undefined
|
||||
}
|
||||
},
|
||||
1000 * 60 * 5
|
||||
)
|
||||
|
||||
const sql = "SELECT application_auth_url FROM ipost.application where application_id=?"
|
||||
const sql =
|
||||
'SELECT application_auth_url FROM ipost.application where application_id=?'
|
||||
|
||||
con.query(sql,[appid],(err,result) => {
|
||||
if(err || result.length !== 1) {
|
||||
con.query(sql, [appid], (err, result) => {
|
||||
if (err || result.length !== 1) {
|
||||
console.err(err)
|
||||
res.redirect(`/authorize?id=${req.body.application_id}`)
|
||||
return
|
||||
}
|
||||
let extra = ""
|
||||
if(req.body.application_extra !== "") {
|
||||
extra = "&extra="+String(req.body.application_extra)
|
||||
let extra = ''
|
||||
if (req.body.application_extra !== '') {
|
||||
extra = '&extra=' + String(req.body.application_extra)
|
||||
}
|
||||
res.redirect(`${result[0].application_auth_url}?code=${tokencode}${extra}`)
|
||||
res.redirect(
|
||||
`${result[0].application_auth_url}?code=${tokencode}${extra}`
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -65,71 +78,79 @@ export const setup = function (router, con, server) {
|
||||
}] */
|
||||
})
|
||||
|
||||
router.post("/redeemauthcode", (req,res) => {
|
||||
|
||||
if(temp_code_to_token[req.body.authcode]===undefined) {
|
||||
router.post('/redeemauthcode', (req, res) => {
|
||||
if (temp_code_to_token[req.body.authcode] === undefined) {
|
||||
res.status(400)
|
||||
res.json({"status":400,"message":"invalid code given"})
|
||||
res.json({ status: 400, message: 'invalid code given' })
|
||||
return
|
||||
}
|
||||
|
||||
if(typeof req.body.auth === "string") {
|
||||
try{
|
||||
if (typeof req.body.auth === 'string') {
|
||||
try {
|
||||
req.body.auth = JSON.parse(req.body.auth)
|
||||
} catch(err) {
|
||||
console.log("error parsing",err)
|
||||
} catch (err) {
|
||||
console.log('error parsing', err)
|
||||
}
|
||||
}
|
||||
if(
|
||||
typeof req.body.auth !== "object" ||
|
||||
typeof req.body.auth.secret !== "string" ||
|
||||
typeof req.body.auth.appid !== "number" ||
|
||||
req.body.auth.secret.length !== 200 ||
|
||||
Buffer.from(req.body.auth.secret,"base64").length !== 150 ||
|
||||
if (
|
||||
typeof req.body.auth !== 'object' ||
|
||||
typeof req.body.auth.secret !== 'string' ||
|
||||
typeof req.body.auth.appid !== 'number' ||
|
||||
req.body.auth.secret.length !== 200 ||
|
||||
Buffer.from(req.body.auth.secret, 'base64').length !== 150 ||
|
||||
req.body.auth.appid !== temp_code_to_token[req.body.authcode].appid
|
||||
) {
|
||||
//console.log(1,req.body.auth,temp_code_to_token[req.body.authcode].appid)
|
||||
res.status(420).send("invalid authentication object")
|
||||
return;
|
||||
res.status(420).send('invalid authentication object')
|
||||
return
|
||||
}
|
||||
|
||||
const appid = req.body.auth.appid
|
||||
|
||||
const checksecret = SHA256(req.body.auth.secret,appid,10000)
|
||||
const checksecret = SHA256(req.body.auth.secret, appid, 10000)
|
||||
|
||||
const checksql = "SELECT application_id from ipost.application where application_secret=? and application_id=?"
|
||||
const checkvalues = [checksecret,appid]
|
||||
const checksql =
|
||||
'SELECT application_id from ipost.application where application_secret=? and application_id=?'
|
||||
const checkvalues = [checksecret, appid]
|
||||
|
||||
con.query(checksql,checkvalues,(error,result_object) => {
|
||||
|
||||
if(error || result_object[0]===undefined || result_object[0].application_id!==appid) {
|
||||
con.query(checksql, checkvalues, (error, result_object) => {
|
||||
if (
|
||||
error ||
|
||||
result_object[0] === undefined ||
|
||||
result_object[0].application_id !== appid
|
||||
) {
|
||||
res.status(400)
|
||||
res.json({"status":400,"message":"invalid code given"})
|
||||
res.json({ status: 400, message: 'invalid code given' })
|
||||
return
|
||||
}
|
||||
|
||||
let data = temp_code_to_token[req.body.authcode]
|
||||
temp_code_to_token[req.body.authcode] = undefined
|
||||
|
||||
const sql =
|
||||
'INSERT INTO `ipost`.`auth_tokens`(`auth_token`,`auth_token_u_id`,`auth_token_isfrom_application_id`) VALUES(?,?,?);'
|
||||
|
||||
const sql = "INSERT INTO `ipost`.`auth_tokens`(`auth_token`,`auth_token_u_id`,`auth_token_isfrom_application_id`) VALUES(?,?,?);"
|
||||
|
||||
const values = [SHA256(data.token,appid,10000),data.userid,data.appid] //token,id,appid
|
||||
con.query(sql,values,(err,result) => {
|
||||
if(err) {
|
||||
res.json({"status":500,"message":"error redeeming code"})
|
||||
const values = [
|
||||
SHA256(data.token, appid, 10000),
|
||||
data.userid,
|
||||
data.appid,
|
||||
] //token,id,appid
|
||||
con.query(sql, values, (err, result) => {
|
||||
if (err) {
|
||||
res.json({ status: 500, message: 'error redeeming code' })
|
||||
console.err(err)
|
||||
} else {
|
||||
res.json({"status":200,"message":"successfully redeemed code","token":data.token})
|
||||
res.json({
|
||||
status: 200,
|
||||
message: 'successfully redeemed code',
|
||||
token: data.token,
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
})
|
||||
|
||||
/* #swagger.security = [{
|
||||
"appTokenAuthHeader": []
|
||||
}] */
|
||||
}
|
||||
}
|
||||
|
||||
+10
-7
@@ -1,10 +1,13 @@
|
||||
export const setup = function (router, con, server) {
|
||||
|
||||
const increaseUSERCall = server.increaseUSERCall
|
||||
|
||||
router.get("/logout", function (req, res) {
|
||||
if (!increaseUSERCall(req, res))return;
|
||||
res.cookie("AUTH_COOKIE", "", { maxAge: 0, httpOnly: true, secure: true });
|
||||
res.redirect("/");
|
||||
});
|
||||
}
|
||||
router.get('/logout', function (req, res) {
|
||||
if (!increaseUSERCall(req, res)) return
|
||||
res.cookie('AUTH_COOKIE', '', {
|
||||
maxAge: 0,
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
})
|
||||
res.redirect('/')
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,74 +1,73 @@
|
||||
import {existsSync} from "fs"
|
||||
import { existsSync } from 'fs'
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const increaseUSERCall = server.increaseUSERCall
|
||||
const __dirname = server.dirname
|
||||
const dir = __dirname + "/"
|
||||
|
||||
router.get("/users/:user", function (req, res) {
|
||||
if (!increaseUSERCall(req, res))
|
||||
return;
|
||||
res.sendFile(dir + "views/otheruser.html");
|
||||
});
|
||||
router.get("/css/:file", (request, response) => {
|
||||
if (!increaseUSERCall(request, response))
|
||||
return;
|
||||
const dir = __dirname + '/'
|
||||
|
||||
router.get('/users/:user', function (req, res) {
|
||||
if (!increaseUSERCall(req, res)) return
|
||||
res.sendFile(dir + 'views/otheruser.html')
|
||||
})
|
||||
router.get('/css/:file', (request, response) => {
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
if (existsSync(`${__dirname}/css/${request.params.file}`)) {
|
||||
response.sendFile(`${__dirname}/css/${request.params.file}`);
|
||||
response.sendFile(`${__dirname}/css/${request.params.file}`)
|
||||
} else {
|
||||
response.status(404).send('no file with that name found')
|
||||
}
|
||||
else {
|
||||
response.status(404).send("no file with that name found");
|
||||
}
|
||||
return;
|
||||
});
|
||||
router.get("/js/:file", (request, response) => {
|
||||
if (!increaseUSERCall(request, response))
|
||||
return;
|
||||
return
|
||||
})
|
||||
router.get('/js/:file', (request, response) => {
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
if (existsSync(`${__dirname}/js/${request.params.file}`)) {
|
||||
response.sendFile(`${__dirname}/js/${request.params.file}`);
|
||||
response.sendFile(`${__dirname}/js/${request.params.file}`)
|
||||
} else {
|
||||
response.status(404).send('no file with that name found')
|
||||
}
|
||||
else {
|
||||
response.status(404).send("no file with that name found");
|
||||
}
|
||||
return;
|
||||
});
|
||||
router.get("/images/:file", (request, response) => {
|
||||
if (!increaseUSERCall(request, response))
|
||||
return;
|
||||
return
|
||||
})
|
||||
router.get('/images/:file', (request, response) => {
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
if (existsSync(`${__dirname}/images/${request.params.file}`)) {
|
||||
response.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
response.sendFile(`${__dirname}/images/${request.params.file}`);
|
||||
response.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
response.sendFile(`${__dirname}/images/${request.params.file}`)
|
||||
} else if (
|
||||
existsSync(
|
||||
`${__dirname}/images/${request.params.file.toLowerCase()}`
|
||||
)
|
||||
) {
|
||||
response.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
response.sendFile(
|
||||
`${__dirname}/images/${request.params.file.toLowerCase()}`
|
||||
)
|
||||
} else {
|
||||
response.status(404).send('no file with that name found')
|
||||
}
|
||||
else if(existsSync(`${__dirname}/images/${request.params.file.toLowerCase()}`)){
|
||||
response.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
response.sendFile(`${__dirname}/images/${request.params.file.toLowerCase()}`);
|
||||
}
|
||||
else {
|
||||
response.status(404).send("no file with that name found");
|
||||
}
|
||||
return;
|
||||
});
|
||||
|
||||
router.get("/user_uploads/:file", (request, response) => {
|
||||
if (!increaseUSERCall(request, response))
|
||||
return;
|
||||
return
|
||||
})
|
||||
|
||||
router.get('/user_uploads/:file', (request, response) => {
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
if (existsSync(`${__dirname}/user_uploads/${request.params.file}`)) {
|
||||
response.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
response.sendFile(`${__dirname}/user_uploads/${request.params.file}`);
|
||||
response.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
response.sendFile(
|
||||
`${__dirname}/user_uploads/${request.params.file}`
|
||||
)
|
||||
} else {
|
||||
response.status(404).send('no file with that name found')
|
||||
}
|
||||
else {
|
||||
response.status(404).send("no file with that name found");
|
||||
}
|
||||
return;
|
||||
});
|
||||
|
||||
router.get("/avatars/:avatar", (request, response) => {
|
||||
if (!increaseUSERCall(request, response))
|
||||
return;
|
||||
response.set('Cache-Control', 'public, max-age=2592000'); //cache it for one month-ish
|
||||
return
|
||||
})
|
||||
|
||||
router.get('/avatars/:avatar', (request, response) => {
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
response.set('Cache-Control', 'public, max-age=2592000') //cache it for one month-ish
|
||||
if (existsSync(`${__dirname}/avatars/${request.params.avatar}`)) {
|
||||
return response.sendFile(`${__dirname}/avatars/${request.params.avatar}`);
|
||||
return response.sendFile(
|
||||
`${__dirname}/avatars/${request.params.avatar}`
|
||||
)
|
||||
}
|
||||
response.status(404).send("No avatar with that name found");
|
||||
});
|
||||
}
|
||||
response.status(404).send('No avatar with that name found')
|
||||
})
|
||||
}
|
||||
|
||||
+20
-21
@@ -1,29 +1,28 @@
|
||||
import { setup as optionssetup } from "./api/options.js";
|
||||
import { setup as allsetup } from "./api/all.js";
|
||||
import { setup as settingshandlersetup } from "./api/settingshandler.js";
|
||||
import { setup as postsetup } from "./api/post.js";
|
||||
import { setup as dmsPersonalMessagessetup } from "./api/dms/PersonalMessages.js";
|
||||
import { setup as dmspostsetup } from "./api/dms/post.js";
|
||||
import { setup as fileiconsetup } from "./api/getFileIcon.js";
|
||||
import { setup as searchsetup } from "./api/search.js";
|
||||
import { setup as getpostssetup } from "./api/getPosts.js";
|
||||
import { setup as userroutessetup } from "./api/userRoutes.js";
|
||||
import { setup as servefilessetup} from "./serve_static_files.js"
|
||||
import { setup as userfilessetup} from "./userfiles.js"
|
||||
import { setup as userauthsetup} from "./user_auth.js"
|
||||
import { setup as applicationsetup} from "./authorize.js"
|
||||
import { setup as logoutsetup} from "./logout.js"
|
||||
|
||||
import { setup as optionssetup } from './api/options.js'
|
||||
import { setup as allsetup } from './api/all.js'
|
||||
import { setup as settingshandlersetup } from './api/settingshandler.js'
|
||||
import { setup as postsetup } from './api/post.js'
|
||||
import { setup as dmsPersonalMessagessetup } from './api/dms/PersonalMessages.js'
|
||||
import { setup as dmspostsetup } from './api/dms/post.js'
|
||||
import { setup as fileiconsetup } from './api/getFileIcon.js'
|
||||
import { setup as searchsetup } from './api/search.js'
|
||||
import { setup as getpostssetup } from './api/getPosts.js'
|
||||
import { setup as userroutessetup } from './api/userRoutes.js'
|
||||
import { setup as servefilessetup } from './serve_static_files.js'
|
||||
import { setup as userfilessetup } from './userfiles.js'
|
||||
import { setup as userauthsetup } from './user_auth.js'
|
||||
import { setup as applicationsetup } from './authorize.js'
|
||||
import { setup as logoutsetup } from './logout.js'
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const setuproute = handler => handler(router,con,server)
|
||||
const setuproute = (handler) => handler(router, con, server)
|
||||
|
||||
setuproute(optionssetup)
|
||||
setuproute(allsetup)
|
||||
setuproute(settingshandlersetup)
|
||||
const get_pid = setuproute(postsetup);
|
||||
const get_pid = setuproute(postsetup)
|
||||
setuproute(dmsPersonalMessagessetup)
|
||||
const get_dmpid = setuproute(dmspostsetup);
|
||||
const get_dmpid = setuproute(dmspostsetup)
|
||||
setuproute(fileiconsetup)
|
||||
setuproute(searchsetup)
|
||||
setuproute(getpostssetup)
|
||||
@@ -36,8 +35,8 @@ export const setup = function (router, con, server) {
|
||||
}
|
||||
server.global_page_variables = global_page_variables
|
||||
setuproute(userfilessetup) //needs getPID and getDMPID
|
||||
|
||||
|
||||
setuproute(userauthsetup) //login & register
|
||||
|
||||
setuproute(applicationsetup)
|
||||
}
|
||||
}
|
||||
|
||||
+160
-132
@@ -1,172 +1,200 @@
|
||||
import {SHA256} from "../extra_modules/SHA.js";
|
||||
import * as signature from "cookie-signature";
|
||||
import getIP from "../extra_modules/getip.js";
|
||||
import {readFileSync} from "fs"
|
||||
import { SHA256 } from '../extra_modules/SHA.js'
|
||||
import * as signature from 'cookie-signature'
|
||||
import getIP from '../extra_modules/getip.js'
|
||||
import { readFileSync } from 'fs'
|
||||
|
||||
const cookiesecret = readFileSync("cookiesecret.txt").toString();
|
||||
const cookiesecret = readFileSync('cookiesecret.txt').toString()
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
const config = server.config
|
||||
const DID_I_FINALLY_ADD_HTTPS = server.DID_I_FINALLY_ADD_HTTPS
|
||||
const increaseAPICall = server.increaseAPICall
|
||||
const HASHES_DB = config.cookies.server_hashes;
|
||||
const HASHES_COOKIE = config.cookies.client_hashes;
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE;
|
||||
const HASHES_DB = config.cookies.server_hashes
|
||||
const HASHES_COOKIE = config.cookies.client_hashes
|
||||
const HASHES_DIFF = HASHES_DB - HASHES_COOKIE
|
||||
|
||||
router.post("/register", function (req, res) {
|
||||
for (let i = 0; i < 10; i++) { //don't want people spam registering
|
||||
if (!increaseAPICall(req, res))
|
||||
return;
|
||||
router.post('/register', function (req, res) {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
//don't want people spam registering
|
||||
if (!increaseAPICall(req, res)) return
|
||||
}
|
||||
res.status(200);
|
||||
if ((typeof req.body.user) !== "string") {
|
||||
res.status(416);
|
||||
res.json({ "error": "incorrect username" });
|
||||
return;
|
||||
res.status(200)
|
||||
if (typeof req.body.user !== 'string') {
|
||||
res.status(416)
|
||||
res.json({ error: 'incorrect username' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.pass) !== "string") {
|
||||
res.status(417);
|
||||
res.json({ "error": "incorrect password" });
|
||||
return;
|
||||
if (typeof req.body.pass !== 'string') {
|
||||
res.status(417)
|
||||
res.json({ error: 'incorrect password' })
|
||||
return
|
||||
}
|
||||
let username = req.body.user.toString();
|
||||
username = username.replace(/\s/gi, "");
|
||||
let password = req.body.pass.toString();
|
||||
let username = req.body.user.toString()
|
||||
username = username.replace(/\s/gi, '')
|
||||
let password = req.body.pass.toString()
|
||||
if (!username) {
|
||||
res.status(410);
|
||||
res.redirect("/register?success=false&reason=username");
|
||||
return;
|
||||
res.status(410)
|
||||
res.redirect('/register?success=false&reason=username')
|
||||
return
|
||||
}
|
||||
if (username === "") {
|
||||
res.status(411);
|
||||
res.redirect("/register?success=false&reason=username");
|
||||
return;
|
||||
if (username === '') {
|
||||
res.status(411)
|
||||
res.redirect('/register?success=false&reason=username')
|
||||
return
|
||||
}
|
||||
if (password.length < 10) {
|
||||
res.status(412);
|
||||
res.send("password is too short");
|
||||
return;
|
||||
res.status(412)
|
||||
res.send('password is too short')
|
||||
return
|
||||
}
|
||||
if (username.length > 25) {
|
||||
res.status(413);
|
||||
res.send("username is too long");
|
||||
return;
|
||||
res.status(413)
|
||||
res.send('username is too long')
|
||||
return
|
||||
}
|
||||
if (username.search("@") !== -1) {
|
||||
res.status(414);
|
||||
res.send("username can't contain @-characters");
|
||||
return;
|
||||
if (username.search('@') !== -1) {
|
||||
res.status(414)
|
||||
res.send("username can't contain @-characters")
|
||||
return
|
||||
}
|
||||
if (!password) {
|
||||
res.status(415);
|
||||
res.redirect("/register?success=false&reason=password");
|
||||
return;
|
||||
res.status(415)
|
||||
res.redirect('/register?success=false&reason=password')
|
||||
return
|
||||
}
|
||||
let userexistssql = `SELECT User_Name from ipost.users where User_Name = ?`;
|
||||
con.query(userexistssql, [encodeURIComponent(username)], function (_error, result) {
|
||||
if (result && result[0] && result[0].User_Name) {
|
||||
res.status(418);
|
||||
res.redirect("/register?success=false&reason=already_exists");
|
||||
return;
|
||||
}
|
||||
let less_hashed_pw = SHA256(password, username, HASHES_DIFF);
|
||||
let hashed_pw = SHA256(less_hashed_pw, username, HASHES_COOKIE);
|
||||
let ip = getIP(req);
|
||||
let setTo = `${username} ${SHA256(password, username, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + ip);
|
||||
ip = SHA256(ip, setTo, HASHES_DB);
|
||||
const default_settings = {};
|
||||
let values = [encodeURIComponent(username), hashed_pw, Date.now(), ip, ip, JSON.stringify(default_settings)];
|
||||
let sql = `INSERT INTO ipost.users (User_Name, User_PW, User_CreationStamp, User_CreationIP, User_LastIP, User_Settings) VALUES (?, ?, ?, ?, ?, ?);`;
|
||||
con.query(sql, values, function (err) {
|
||||
if (err)
|
||||
throw err;
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, { maxAge: Math.pow(10, 10), httpOnly: true, secure: DID_I_FINALLY_ADD_HTTPS });
|
||||
if(req.body.r !== undefined) {
|
||||
res.redirect(decodeURIComponent(req.body.r))
|
||||
} else {
|
||||
res.redirect("/user");
|
||||
let userexistssql = `SELECT User_Name from ipost.users where User_Name = ?`
|
||||
con.query(
|
||||
userexistssql,
|
||||
[encodeURIComponent(username)],
|
||||
function (_error, result) {
|
||||
if (result && result[0] && result[0].User_Name) {
|
||||
res.status(418)
|
||||
res.redirect(
|
||||
'/register?success=false&reason=already_exists'
|
||||
)
|
||||
return
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
router.post("/login", function (req, res) {
|
||||
if (!increaseAPICall(req, res))
|
||||
return;
|
||||
if ((typeof req.body.user) !== "string") {
|
||||
res.status(416);
|
||||
res.json({ "error": "incorrect username" });
|
||||
return;
|
||||
let less_hashed_pw = SHA256(password, username, HASHES_DIFF)
|
||||
let hashed_pw = SHA256(less_hashed_pw, username, HASHES_COOKIE)
|
||||
let ip = getIP(req)
|
||||
let setTo = `${username} ${SHA256(password, username, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + ip)
|
||||
ip = SHA256(ip, setTo, HASHES_DB)
|
||||
const default_settings = {}
|
||||
let values = [
|
||||
encodeURIComponent(username),
|
||||
hashed_pw,
|
||||
Date.now(),
|
||||
ip,
|
||||
ip,
|
||||
JSON.stringify(default_settings),
|
||||
]
|
||||
let sql = `INSERT INTO ipost.users (User_Name, User_PW, User_CreationStamp, User_CreationIP, User_LastIP, User_Settings) VALUES (?, ?, ?, ?, ?, ?);`
|
||||
con.query(sql, values, function (err) {
|
||||
if (err) throw err
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, {
|
||||
maxAge: Math.pow(10, 10),
|
||||
httpOnly: true,
|
||||
secure: DID_I_FINALLY_ADD_HTTPS,
|
||||
})
|
||||
if (req.body.r !== undefined) {
|
||||
res.redirect(decodeURIComponent(req.body.r))
|
||||
} else {
|
||||
res.redirect('/user')
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
router.post('/login', function (req, res) {
|
||||
if (!increaseAPICall(req, res)) return
|
||||
if (typeof req.body.user !== 'string') {
|
||||
res.status(416)
|
||||
res.json({ error: 'incorrect username' })
|
||||
return
|
||||
}
|
||||
if ((typeof req.body.pass) !== "string") {
|
||||
res.status(417);
|
||||
res.json({ "error": "incorrect password" });
|
||||
return;
|
||||
if (typeof req.body.pass !== 'string') {
|
||||
res.status(417)
|
||||
res.json({ error: 'incorrect password' })
|
||||
return
|
||||
}
|
||||
if (!req.body.user) {
|
||||
res.status(410);
|
||||
res.send("no username given");
|
||||
return;
|
||||
res.status(410)
|
||||
res.send('no username given')
|
||||
return
|
||||
}
|
||||
if (!req.body.pass) {
|
||||
res.status(411);
|
||||
res.send("no password given");
|
||||
return;
|
||||
res.status(411)
|
||||
res.send('no password given')
|
||||
return
|
||||
}
|
||||
let username = req.body.user.toString();
|
||||
username = username.replace(" ", "");
|
||||
let password = req.body.pass.toString();
|
||||
let username = req.body.user.toString()
|
||||
username = username.replace(' ', '')
|
||||
let password = req.body.pass.toString()
|
||||
if (!username) {
|
||||
res.status(412);
|
||||
res.send("no username given");
|
||||
return;
|
||||
res.status(412)
|
||||
res.send('no username given')
|
||||
return
|
||||
}
|
||||
if (username.length > 25) {
|
||||
res.status(413);
|
||||
res.send("username is too long");
|
||||
return;
|
||||
res.status(413)
|
||||
res.send('username is too long')
|
||||
return
|
||||
}
|
||||
if (password.length < 10) {
|
||||
res.status(414);
|
||||
res.send("password is too short");
|
||||
return;
|
||||
res.status(414)
|
||||
res.send('password is too short')
|
||||
return
|
||||
}
|
||||
if (!password) {
|
||||
res.status(415);
|
||||
res.send("no password given");
|
||||
return;
|
||||
res.status(415)
|
||||
res.send('no password given')
|
||||
return
|
||||
}
|
||||
|
||||
const no_ip_lock = username.endsWith("@unsafe")
|
||||
username = username.replace("@unsafe","")
|
||||
const no_ip_lock = username.endsWith('@unsafe')
|
||||
username = username.replace('@unsafe', '')
|
||||
|
||||
let less_hashed_pw = SHA256(password, username, HASHES_DIFF);
|
||||
let hashed_pw = SHA256(less_hashed_pw, username, HASHES_COOKIE);
|
||||
let userexistssql = `SELECT * from ipost.users where User_Name = ? and User_PW = ?;`;
|
||||
con.query(userexistssql, [encodeURIComponent(username), hashed_pw], function (_error, result) {
|
||||
if (result && result[0]) {
|
||||
let ip = getIP(req);
|
||||
let setTo = `${username} ${SHA256(password, username, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(setTo, cookiesecret + (!no_ip_lock ? ip : ""));
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, { maxAge: Math.pow(10, 10), httpOnly: true, secure: DID_I_FINALLY_ADD_HTTPS });
|
||||
ip = SHA256(ip, setTo, HASHES_DB);
|
||||
if (result[0].User_LastIP !== ip) {
|
||||
let sql = `update ipost.users set User_LastIP = ? where User_Name = ?;`;
|
||||
con.query(sql, [ip, encodeURIComponent(username)], function (error) {
|
||||
if (error)
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
if(req.body.r !== undefined) {
|
||||
res.redirect(decodeURIComponent(req.body.r))
|
||||
let less_hashed_pw = SHA256(password, username, HASHES_DIFF)
|
||||
let hashed_pw = SHA256(less_hashed_pw, username, HASHES_COOKIE)
|
||||
let userexistssql = `SELECT * from ipost.users where User_Name = ? and User_PW = ?;`
|
||||
con.query(
|
||||
userexistssql,
|
||||
[encodeURIComponent(username), hashed_pw],
|
||||
function (_error, result) {
|
||||
if (result && result[0]) {
|
||||
let ip = getIP(req)
|
||||
let setTo = `${username} ${SHA256(password, username, HASHES_COOKIE)}`
|
||||
let cookiesigned = signature.sign(
|
||||
setTo,
|
||||
cookiesecret + (!no_ip_lock ? ip : '')
|
||||
)
|
||||
res.cookie('AUTH_COOKIE', cookiesigned, {
|
||||
maxAge: Math.pow(10, 10),
|
||||
httpOnly: true,
|
||||
secure: DID_I_FINALLY_ADD_HTTPS,
|
||||
})
|
||||
ip = SHA256(ip, setTo, HASHES_DB)
|
||||
if (result[0].User_LastIP !== ip) {
|
||||
let sql = `update ipost.users set User_LastIP = ? where User_Name = ?;`
|
||||
con.query(
|
||||
sql,
|
||||
[ip, encodeURIComponent(username)],
|
||||
function (error) {
|
||||
if (error) throw error
|
||||
}
|
||||
)
|
||||
}
|
||||
if (req.body.r !== undefined) {
|
||||
res.redirect(decodeURIComponent(req.body.r))
|
||||
} else {
|
||||
res.redirect('/user')
|
||||
}
|
||||
} else {
|
||||
res.redirect("/user");
|
||||
console.log(5, 'login failed, username: ', username)
|
||||
res.redirect('/login?success=false?reason=noUser')
|
||||
}
|
||||
}
|
||||
else {
|
||||
console.log(5,"login failed, username: ", username);
|
||||
res.redirect("/login?success=false?reason=noUser");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
+133
-112
@@ -1,15 +1,14 @@
|
||||
import ejs from "ejs"
|
||||
import { LRUCache as LRU } from "lru-cache"
|
||||
import { minify as min_js } from "uglify-js"
|
||||
import Clean from 'clean-css';
|
||||
import Minifier from 'html-minifier-terser';
|
||||
import { web_version } from "unsafe_encrypt";
|
||||
import { existsSync, readFileSync, readFile } from "fs"
|
||||
import ejs from 'ejs'
|
||||
import { LRUCache as LRU } from 'lru-cache'
|
||||
import { minify as min_js } from 'uglify-js'
|
||||
import Clean from 'clean-css'
|
||||
import Minifier from 'html-minifier-terser'
|
||||
import { web_version } from 'unsafe_encrypt'
|
||||
import { existsSync, readFileSync, readFile } from 'fs'
|
||||
|
||||
export const setup = function (router, con, server) {
|
||||
|
||||
const increaseUSERCall = server.increaseUSERCall
|
||||
const dir = server.dirname + "/"
|
||||
const dir = server.dirname + '/'
|
||||
|
||||
ejs.cache = new LRU({ max: 20 })
|
||||
|
||||
@@ -22,47 +21,47 @@ export const setup = function (router, con, server) {
|
||||
ttl: 1000 * 60,
|
||||
allowStale: true,
|
||||
updateAgeOnGet: true,
|
||||
updateAgeOnHas: true
|
||||
updateAgeOnHas: true,
|
||||
})
|
||||
|
||||
function load_var(filePath) {
|
||||
if (load_var_cache.has(filePath)) {
|
||||
return load_var_cache.get(filePath);
|
||||
return load_var_cache.get(filePath)
|
||||
}
|
||||
|
||||
if (!existsSync(filePath)) {
|
||||
console.log(1, 'Tried loading non-existent file', filePath);
|
||||
load_var_cache.set(filePath, '');
|
||||
return '';
|
||||
console.log(1, 'Tried loading non-existent file', filePath)
|
||||
load_var_cache.set(filePath, '')
|
||||
return ''
|
||||
}
|
||||
|
||||
let output = readFileSync(filePath);
|
||||
let output = readFileSync(filePath)
|
||||
|
||||
if (filePath.endsWith('.js')) {
|
||||
output = min_js(output.toString()).code;
|
||||
output = min_js(output.toString()).code
|
||||
} else if (filePath.endsWith('.css')) {
|
||||
const { styles } = new Clean({}).minify(output.toString());
|
||||
output = styles;
|
||||
const { styles } = new Clean({}).minify(output.toString())
|
||||
output = styles
|
||||
}
|
||||
load_var_cache.set(filePath, output);
|
||||
return output;
|
||||
load_var_cache.set(filePath, output)
|
||||
return output
|
||||
}
|
||||
|
||||
function get_channels() {
|
||||
return new Promise(function (resolve, reject) {
|
||||
let sql = `select post_receiver_name from ipost.posts where post_is_private = '0' group by post_receiver_name;`;
|
||||
let sql = `select post_receiver_name from ipost.posts where post_is_private = '0' group by post_receiver_name;`
|
||||
con.query(sql, [], function (err, result) {
|
||||
if (err) reject(err)
|
||||
|
||||
let out = []
|
||||
|
||||
for (let channel of result) {
|
||||
if (channel.post_receiver_name === "") continue;
|
||||
if (channel.post_receiver_name === '') continue
|
||||
out[out.length] = channel.post_receiver_name
|
||||
}
|
||||
|
||||
resolve(out)
|
||||
});
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -78,52 +77,55 @@ export const setup = function (router, con, server) {
|
||||
res(appId_Cache.get(appid) || {})
|
||||
return
|
||||
}
|
||||
con.query("SELECT * FROM ipost.application WHERE application_id=?", [appid], (err, result) => {
|
||||
if (err) {
|
||||
console.error(err)
|
||||
rej({})
|
||||
return
|
||||
con.query(
|
||||
'SELECT * FROM ipost.application WHERE application_id=?',
|
||||
[appid],
|
||||
(err, result) => {
|
||||
if (err) {
|
||||
console.error(err)
|
||||
rej({})
|
||||
return
|
||||
}
|
||||
appId_Cache.set(appid, result[0])
|
||||
res(result[0] || {})
|
||||
}
|
||||
appId_Cache.set(appid, result[0])
|
||||
res(result[0] || {})
|
||||
})
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
let global_page_variables = {
|
||||
globalcss: load_var("./css/global.css"),
|
||||
httppostjs: load_var("./js/httppost.js"),
|
||||
navbar: load_var("./extra_modules/navbar.html"),
|
||||
markdownjs: load_var("./js/markdown.js"),
|
||||
htmlescapejs: load_var("./js/htmlescape.js"),
|
||||
warnmessagejs: load_var("./js/warn_message.js"),
|
||||
globalcss: load_var('./css/global.css'),
|
||||
httppostjs: load_var('./js/httppost.js'),
|
||||
navbar: load_var('./extra_modules/navbar.html'),
|
||||
markdownjs: load_var('./js/markdown.js'),
|
||||
htmlescapejs: load_var('./js/htmlescape.js'),
|
||||
warnmessagejs: load_var('./js/warn_message.js'),
|
||||
loadfile: load_var,
|
||||
getChannels: get_channels,
|
||||
encryptJS: min_js(web_version().toString()).code,
|
||||
cookiebanner: `<script id="cookieyes" type="text/javascript" src="https://cdn-cookieyes.com/client_data/3cf33f6b631f3587bf83813b/script.js" async></script>`,
|
||||
getPID: server.global_page_variables.getPID,
|
||||
getDMPID: server.global_page_variables.getDMPID,
|
||||
unauthorized_description: "Chat now by creating an account on IPost",
|
||||
unauthorized_description: 'Chat now by creating an account on IPost',
|
||||
hcaptcha_sitekey: server.hcaptcha.sitekey,
|
||||
getAppWithId: getAppWithId
|
||||
getAppWithId: getAppWithId,
|
||||
}
|
||||
|
||||
|
||||
|
||||
async function handleUserFiles(request, response, overrideurl) {
|
||||
if (!increaseUSERCall(request, response)) return;
|
||||
if (typeof overrideurl !== "string") overrideurl = undefined;
|
||||
if (!increaseUSERCall(request, response)) return
|
||||
if (typeof overrideurl !== 'string') overrideurl = undefined
|
||||
|
||||
let originalUrl = overrideurl
|
||||
|| request.params.file
|
||||
|| request.originalUrl.split("?").shift(); //backup in case anything goes wrong
|
||||
let originalUrl =
|
||||
overrideurl ||
|
||||
request.params.file ||
|
||||
request.originalUrl.split('?').shift() //backup in case anything goes wrong
|
||||
|
||||
let path = ""
|
||||
if (existsSync(dir + "views/" + originalUrl)) {
|
||||
path = dir + "views/" + originalUrl
|
||||
let path = ''
|
||||
if (existsSync(dir + 'views/' + originalUrl)) {
|
||||
path = dir + 'views/' + originalUrl
|
||||
//send .txt files as plaintext to help browsers interpret it correctly
|
||||
if (originalUrl.endsWith(".txt")) {
|
||||
response.set('Content-Type', 'text/plain');
|
||||
if (originalUrl.endsWith('.txt')) {
|
||||
response.set('Content-Type', 'text/plain')
|
||||
readFile(path, (err, data) => {
|
||||
if (err) return
|
||||
response.send(data)
|
||||
@@ -131,90 +133,109 @@ export const setup = function (router, con, server) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (existsSync(dir + "views/" + originalUrl + "index.html")) {
|
||||
path = dir + "views/" + originalUrl + "index.html"
|
||||
if (existsSync(dir + 'views/' + originalUrl + 'index.html')) {
|
||||
path = dir + 'views/' + originalUrl + 'index.html'
|
||||
}
|
||||
if (existsSync(dir + "views/" + originalUrl + ".html")) {
|
||||
path = dir + "views/" + originalUrl + ".html"
|
||||
if (existsSync(dir + 'views/' + originalUrl + '.html')) {
|
||||
path = dir + 'views/' + originalUrl + '.html'
|
||||
}
|
||||
if (existsSync(dir + "views" + originalUrl + ".html")) {
|
||||
path = dir + "views" + originalUrl + ".html"
|
||||
if (existsSync(dir + 'views' + originalUrl + '.html')) {
|
||||
path = dir + 'views' + originalUrl + '.html'
|
||||
}
|
||||
|
||||
if (path !== "" && originalUrl !== "favicon.ico" && originalUrl !== "api_documentation" && originalUrl !== "api_documentation.html") {
|
||||
if (
|
||||
path !== '' &&
|
||||
originalUrl !== 'favicon.ico' &&
|
||||
originalUrl !== 'api_documentation' &&
|
||||
originalUrl !== 'api_documentation.html'
|
||||
) {
|
||||
console.log(originalUrl)
|
||||
global_page_variables.user = { "username": response.locals.username, "bio": response.locals.bio, "avatar": response.locals.avatar }
|
||||
global_page_variables.query = request.query
|
||||
if (originalUrl === "authorize") {
|
||||
global_page_variables.application = await getAppWithId(request.query.id)
|
||||
global_page_variables.user = {
|
||||
username: response.locals.username,
|
||||
bio: response.locals.bio,
|
||||
avatar: response.locals.avatar,
|
||||
}
|
||||
ejs.renderFile(path, global_page_variables, { async: true }, async function (err, str) {
|
||||
str = await str
|
||||
err = await err
|
||||
if (err) {
|
||||
console.log(1, err)
|
||||
response.status(500)
|
||||
response.send("error")
|
||||
//TODO: make error page
|
||||
return
|
||||
}
|
||||
try {
|
||||
str = await Minifier.minify(str, {
|
||||
removeComments: true,
|
||||
removeCommentsFromCDATA: true,
|
||||
removeCDATASectionsFromCDATA: true,
|
||||
collapseWhitespace: true,
|
||||
collapseBooleanAttributes: true,
|
||||
removeAttributeQuotes: true,
|
||||
removeRedundantAttributes: true,
|
||||
useShortDoctype: true,
|
||||
removeEmptyAttributes: true
|
||||
})
|
||||
} catch (ignored) {
|
||||
console.log(2, "error minifying", originalUrl);
|
||||
}
|
||||
global_page_variables.query = request.query
|
||||
if (originalUrl === 'authorize') {
|
||||
global_page_variables.application = await getAppWithId(
|
||||
request.query.id
|
||||
)
|
||||
}
|
||||
ejs.renderFile(
|
||||
path,
|
||||
global_page_variables,
|
||||
{ async: true },
|
||||
async function (err, str) {
|
||||
str = await str
|
||||
err = await err
|
||||
if (err) {
|
||||
console.log(1, err)
|
||||
response.status(500)
|
||||
response.send('error')
|
||||
//TODO: make error page
|
||||
return
|
||||
}
|
||||
try {
|
||||
str = await Minifier.minify(str, {
|
||||
removeComments: true,
|
||||
removeCommentsFromCDATA: true,
|
||||
removeCDATASectionsFromCDATA: true,
|
||||
collapseWhitespace: true,
|
||||
collapseBooleanAttributes: true,
|
||||
removeAttributeQuotes: true,
|
||||
removeRedundantAttributes: true,
|
||||
useShortDoctype: true,
|
||||
removeEmptyAttributes: true,
|
||||
})
|
||||
} catch (ignored) {
|
||||
console.log(2, 'error minifying', originalUrl)
|
||||
}
|
||||
|
||||
try {
|
||||
response.send(str)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
try {
|
||||
response.send(str)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
return;
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (originalUrl === "api_documentation" || originalUrl === "api_documentation.html") {
|
||||
response.set('Cache-Control', 'public, max-age=2592000');
|
||||
if (
|
||||
originalUrl === 'api_documentation' ||
|
||||
originalUrl === 'api_documentation.html'
|
||||
) {
|
||||
response.set('Cache-Control', 'public, max-age=2592000')
|
||||
response.set('Content-Type', 'text/html')
|
||||
response.send(load_var("./views/api_documentation.html"))
|
||||
response.send(load_var('./views/api_documentation.html'))
|
||||
return
|
||||
}
|
||||
|
||||
if (originalUrl === "favicon.ico") {
|
||||
response.set('Cache-Control', 'public, max-age=2592000');
|
||||
response.sendFile(dir + "/views/favicon.ico")
|
||||
if (originalUrl === 'favicon.ico') {
|
||||
response.set('Cache-Control', 'public, max-age=2592000')
|
||||
response.sendFile(dir + '/views/favicon.ico')
|
||||
return
|
||||
}
|
||||
|
||||
console.log(5, "no file found", originalUrl);
|
||||
console.log(5, 'no file found', originalUrl)
|
||||
try {
|
||||
response.status(404).send("No file with that name found");
|
||||
response.status(404).send('No file with that name found')
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle default URI as /index (interpreted redirect: "localhost" -> "localhost/index" )
|
||||
*/
|
||||
router.get("/", (req, res) => {
|
||||
req.params.file = "index"
|
||||
handleUserFiles(req, res, "/index")
|
||||
});
|
||||
* Handle default URI as /index (interpreted redirect: "localhost" -> "localhost/index" )
|
||||
*/
|
||||
router.get('/', (req, res) => {
|
||||
req.params.file = 'index'
|
||||
handleUserFiles(req, res, '/index')
|
||||
})
|
||||
|
||||
router.get("/:file", handleUserFiles);
|
||||
router.get("/:folder/:file", (req, res) => {
|
||||
req.params.file = req.params.folder + "/" + req.params.file
|
||||
router.get('/:file', handleUserFiles)
|
||||
router.get('/:folder/:file', (req, res) => {
|
||||
req.params.file = req.params.folder + '/' + req.params.file
|
||||
handleUserFiles(req, res)
|
||||
});
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user