1 Commits

Author SHA1 Message Date
0b87b82a4d Initial commit for management 2023-01-19 10:05:47 -05:00
15 changed files with 152 additions and 688 deletions

View File

@@ -17,16 +17,12 @@ config.mail.pass = "password";
config.mail.from = "name";
/*
* Session settings
* Session purge settings
*/
// Maximum session length in days
config.maxSessionLength = 1;
config.maxRefreshLength = 360;
// Session string character length
config.sessionCharacterLength = 25;
config.refreshChracterLength = 60;
/*
* SSL settings
*/
@@ -53,4 +49,5 @@ config.http.port = 8080;
config.db = {}
config.db.connection = 'mongodb://localhost:27017/kno-logic';
module.exports = config;

View File

@@ -13,6 +13,7 @@ const postRoutes = require('./routes/post.route');
const categoryRoutes = require('./routes/category.route');
const mongoSanitize = require('express-mongo-sanitize');
const fs = require("fs");
const { Http2ServerRequest } = require('http2');
const https = require('https');
console.log("Starting Kno-Logic Backend Server");
@@ -45,11 +46,10 @@ app.use(function(req, res, next) {
app.use(mongoSanitize());
// Express routes
app.use('/v1/admin', adminRoutes);
app.use('/v1/user', userRoutes);
app.use('/v1/post', postRoutes);
app.use('/v1/category', categoryRoutes);
app.use('/manage', express.static('public'));
app.use('/admin', adminRoutes);
app.use('/user', userRoutes);
app.use('/post', postRoutes);
app.use('/category', categoryRoutes);
app.listen(config.http.port, () => {
console.log('Express server running on port:', PORT);
@@ -63,6 +63,7 @@ if (config.ssl.use) {
https.createServer(options, app).listen(config.ssl.port);
}
// Cron jobs
var purge = new CronJob('*/5 * * * *', utils.cron.purgeSessions);
purge.start();

View File

@@ -1,24 +1 @@
const backendURL = "http://127.0.0.1:8080";
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
const backendURL = "http://127.0.0.1:8080";

View File

@@ -1,12 +1,10 @@
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
@@ -48,7 +46,7 @@
</center>
</body>
<script src="./consts.js"></script>
<script src="./consts.js"></script>
<script>
function login() {
@@ -64,17 +62,11 @@
},
body: JSON.stringify({ email: email, password: password })
});
const content = await rawResponse.json();
const content = await rawResponse.text();
if (content.success) {
setCookie("userId", content.response.userId, 1);
setCookie("sessionId", content.response.sessionId, 1);
window.location.replace("/manage/manageHome.html");
} else {
alert("Incorrect email/password.");
}
console.log(content);
})();
}
</script>

View File

@@ -1,156 +0,0 @@
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>Kno-Logic Management Portal</h1>
<table border="black">
<th colspan="4">
Manage Categories
</th>
<tr>
<td>
<a href="/manage/manageHome.html">Home</a>
</td>
<td>
<a href="/manage/managePosts.html">Manage Posts</a>
</td>
<td>
<a href="/manage/manageCategories.html">Manage Categories</a>
</td>
<td>
<a href="/manage/manageHome.html">Analytics</a>
</td>
</tr>
</table>
<br>
<table border="black">
<th colspan="2">
Add Category
</th>
<tr>
<td>
<label for="name">Category Name: </label>
</td>
<td>
<input type="text" id="name" name="name">
</td>
</tr>
<tr>
<td>
<label for="color">Category Color: </label>
</td>
<td>
<input type="color" id="color" name="color">
</td>
</tr>
<tr>
<td colspan="2">
<center><button type="button" onclick="addCategory()">Add Category</button></center>
</td>
</tr>
</table>
<br>
<table border="black" id="listTable">
<th colspan="2">
List Categories
</th>
<tr>
<td>
<strong>Name</strong>
</td>
<td>
<strong>Color</strong>
</td>
</th>
<tbody>
</tbody>
</table>
</center>
</body>
<script src="./consts.js"></script>
<script>
function verifySession() {
let userId = getCookie("userId");
let sessionId = getCookie("sessionId");
(async () => {
const rawResponse = await fetch(backendURL + '/v1/user/check-token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, sessionId: sessionId })
});
const content = await rawResponse.json();
if (!content.success) {
window.location.replace("/manage/index.html");
}
})();
}
function getCategories() {
(async () => {
const rawResponse = await fetch(backendURL + '/v1/category/all', {
method: 'GET',
});
const content = await rawResponse.json();
var tbodyRef = document.getElementById('listTable').getElementsByTagName('tbody')[0];
content.response.forEach(element => {
var newRow = tbodyRef.insertRow();
newRow.innerHTML = `<td>${element.name}</td><td><input type='color' value='${element.color}' disabled></td>`;
});
})();
}
function addCategory() {
let userId = getCookie("userId");
let sessionId = getCookie("sessionId");
let name = document.getElementById("name").value;
let color = document.getElementById("color").value;
(async () => {
const rawResponse = await fetch(backendURL + '/v1/category/create', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, sessionId: sessionId, category: { name: name, color: color } })
});
const content = await rawResponse.json();
if (content.success) {
window.location.reload();
} else {
alert("Could not add category: " + content.response);
}
console.log(content);
})();
}
verifySession();
getCategories();
</script>
</html>

View File

@@ -1,64 +1,59 @@
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>Kno-Logic Management Portal</h1>
<table border="black">
<th colspan="4">
Home
</th>
<tr>
<td>
<a href="/manage/manageHome.html">Home</a>
</td>
<td>
<a href="/manage/managePosts.html">Manage Posts</a>
</td>
<td>
<a href="/manage/manageCategories.html">Manage Categories</a>
</td>
<td>
<a href="/manage/manageHome.html">Analytics</a>
</td>
</tr>
</table>
<table border="black">
<th colspan="4">
Home
</th>
<tr>
<td>
<a href="/manage/manageHome.html">Home</a>
</td>
<td>
<a href="/manage/managePosts.html">Manage Posts</a>
</td>
<td>
<a href="/manage/manageCategories.html">Manage Categories</a>
</td>
<td>
<a href="/manage/manageHome.html">Analytics</a>
</td>
</tr>
</table>
</center>
</body>
<script src="./consts.js"></script>
<script src="./consts.js"></script>
<script>
function verifySession() {
let userId = getCookie("userId");
let sessionId = getCookie("sessionId");
function login() {
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
(async () => {
const rawResponse = await fetch(backendURL + '/v1/user/check-token', {
const rawResponse = await fetch(backendURL + '/v1/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, sessionId: sessionId })
body: JSON.stringify({ email: email, password: password })
});
const content = await rawResponse.json();
const content = await rawResponse.text();
if (!content.success) {
window.location.replace("/manage/index.html");
}
console.log(content);
})();
}
verifySession();
}
</script>
</html>

View File

@@ -1,250 +0,0 @@
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>Kno-Logic Management Portal</h1>
<table border="black">
<th colspan="4">
Manage Posts
</th>
<tr>
<td>
<a href="/manage/manageHome.html">Home</a>
</td>
<td>
<a href="/manage/managePosts.html">Manage Posts</a>
</td>
<td>
<a href="/manage/manageCategories.html">Manage Categories</a>
</td>
<td>
<a href="/manage/manageHome.html">Analytics</a>
</td>
</tr>
</table>
<br>
<table border="black">
<th colspan="2">
Add Post
</th>
<tr>
<td>
<label for="title">Title: </label>
</td>
<td>
<input type="text" id="title" name="title">
</td>
</tr>
<tr>
<td>
<label for="description">Description: </label>
</td>
<td>
<textarea id="description" name="description"></textarea>
</td>
</tr>
<tr>
<td>
<label for="author">Author: </label>
</td>
<td>
<input type="text" id="author" name="author">
</td>
</tr>
<tr>
<td>
<label for="category">Category (hold <code>CTRL</code> to select multiple): </label>
</td>
<td>
<select name="category" id="category" style="width: 100%; height: 100px;" multiple>
</select>
</td>
</tr>
<tr>
<td>
<label for="link">Link: </label>
</td>
<td>
<input type="text" id="link" name="link">
</td>
</tr>
<tr>
<td>
<label for="date">Date: </label>
</td>
<td>
<input type="date" id="date" name="date">
</td>
</tr>
<tr>
<td colspan="2">
<center><button type="button" onclick="addPost()">Add Post</button></center>
</td>
</tr>
</table>
<br>
<table border="black" id="listTable">
<th colspan="9">
List Posts
</th>
<tr>
<td>
<strong>Title</strong>
</td>
<td>
<strong>Description</strong>
</td>
<td>
<strong>Author</strong>
</td>
<td>
<strong>Category</strong>
</td>
<td>
<strong>Link</strong>
</td>
<td>
<strong>Date</strong>
</td>
<td>
<strong>Photo</strong>
</td>
<td>
<strong>Edit</strong>
</td>
<td>
<strong>Delete</strong>
</td>
</th>
<tbody>
</tbody>
</table>
</center>
</body>
<script src="./consts.js"></script>
<script>
function verifySession() {
let userId = getCookie("userId");
let sessionId = getCookie("sessionId");
(async () => {
const rawResponse = await fetch(backendURL + '/v1/user/check-token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, sessionId: sessionId })
});
const content = await rawResponse.json();
if (!content.success) {
window.location.replace("/manage/index.html");
}
})();
}
function getCategories() {
(async () => {
const rawResponse = await fetch(backendURL + '/v1/category/all', {
method: 'GET',
});
const content = await rawResponse.json();
var categoryRef = document.getElementById('category');
content.response.forEach(element => {
categoryRef.appendChild(new Option(element.name, element._id))
});
})();
}
function getPosts() {
(async () => {
const rawResponse = await fetch(backendURL + '/v1/post/all', {
method: 'GET',
});
const content = await rawResponse.json();
console.log(content);
var tbodyRef = document.getElementById('listTable').getElementsByTagName('tbody')[0];
content.response.forEach(element => {
var newRow = tbodyRef.insertRow();
newRow.innerHTML = `<td>${element.title}</td><td>${element.description}</td><td>${element.author}</td><td>${element.category.toString()}</td><td>${element.link}</td><td>${element.date}</td><td>${element.photo} <br> Edit Photo</td><td>Edit</td><td>Delete</td>`;
});
})();
}
function addPost() {
let userId = getCookie("userId");
let sessionId = getCookie("sessionId");
let title = document.getElementById("title").value;
let description = document.getElementById("description").value;
let author = document.getElementById("author").value;
let category = getSelectValues(document.getElementById("category"));
let link = document.getElementById("link").value;
let date = document.getElementById("date").value;
console.log(category);
(async () => {
const rawResponse = await fetch(backendURL + '/v1/post/create', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ userId: userId, sessionId: sessionId,
post: { title: title, description: description, author: author, category: category, link: link, date: date } })
});
const content = await rawResponse.json();
if (content.success) {
window.location.reload();
} else {
alert("Could not add post: " + content.response);
}
})();
}
function getSelectValues(select) {
let result = [];
let options = select && select.options;
let opt;
for (let i = 0, iLen = options.length; i < iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
verifySession();
getCategories();
getPosts();
</script>
</html>

View File

@@ -1,12 +1,10 @@
<html>
<head>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
@@ -56,7 +54,7 @@
</center>
</body>
<script src="./consts.js"></script>
<script src="./consts.js"></script>
<script>
function login() {

View File

@@ -15,7 +15,7 @@ let User = require('../schema/user.model');
*/
adminRoutes.route('/stats').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
}
utils.account.checkSession(req.body.userId, req.body.sessionId, (isValidId) => {
@@ -31,13 +31,13 @@ adminRoutes.route('/stats').post((req, res) => {
User.count({}, (err, userCount) => {
stats.userCount = userCount;
stats.date = Date();
res.status(200).json({ success: true, response: stats });
res.json(stats);
});
});
});
});
} else {
res.status(401).json({ success: false, response: "Invalid permissions to view stats" });
res.status(401).send("Invalid permissions to view stats.");
return;
}
})

View File

@@ -15,23 +15,23 @@ let User = require('../schema/user.model');
*/
categoryRoutes.route('/create').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
}
utils.account.checkSession(req.body.userId, req.body.sessionId, (isValidId) => {
utils.account.isAdmin(req.body.userId, (isAdmin) => {
if (isValidId && isAdmin) {
let c = new Category(req.body.category);
let c = new Category(req.body);
c.save()
.then(() => {
res.status(200).json({ success: true, response: c });
res.json(c);
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error creating category" });
res.status(500).send("Error creating category");
});
} else {
res.status(401).json({ success: false, response: "Invalid permissions to create category" });
res.status(401).send("Invalid permissions to create category.");
return;
}
})
@@ -47,10 +47,10 @@ categoryRoutes.route('/all').get((req, res) => {
Category.find({}, (err, cArr) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting categories" });
res.status(500).send("Error getting categories");
return;
}
res.status(200).json({ success: true, response: cArr });
res.status(200).send(cArr);
});
});
@@ -63,11 +63,11 @@ categoryRoutes.route('/posts').get((req, res) => {
Post.find({}, (err, postArr) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting posts" });
res.status(500).send("Error getting posts");
return;
}
postArr = postArr.filter(post => post.category.includes(req.body._id));
res.status(200).json({ success: true, response: postArr });
res.status(200).send(postArr);
});
});

View File

@@ -15,24 +15,24 @@ let User = require('../schema/user.model');
*/
postRoutes.route('/create').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
}
utils.account.checkSession(req.body.userId, req.body.sessionId, (isValidId) => {
utils.account.isAdmin(req.body.userId, (isAdmin) => {
if (isValidId && isAdmin) {
let p = new Post(req.body.post);
let p = new Post(req.body);
p.date = utils.date.dateToEpoch(p.date);
p.save()
.then(() => {
res.status(200).json({ success: true, response: p });
res.json(p);
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error creating post" });
res.status(500).send("Error creating post");
});
} else {
res.status(401).json({ success: false, response: "Invalid permissions to create post" });
res.status(401).send("Invalid permissions to create post.");
return;
}
})
@@ -47,7 +47,7 @@ postRoutes.route('/create').post((req, res) => {
*/
postRoutes.route('/delete').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
}
utils.account.checkSession(req.body.userId, req.body.sessionId, (isValidId) => {
@@ -55,13 +55,13 @@ postRoutes.route('/delete').post((req, res) => {
if (isValidId && isAdmin) {
Post.findByIdAndDelete(req.body._id, (err, r) => {
if (err) {
res.status(500).json({ success: false, response: "Error deleting post" });
res.status(500).send("Error deleting post");
return;
}
res.status(200).json({ success: true, response: "Deleted post" });
res.status(200).send("Deleted post");
});
} else {
res.status(401).json({ success: false, response: "Invalid permissions to delete post." });
res.status(401).send("Invalid permissions to delete post.");
return;
}
})
@@ -76,7 +76,7 @@ postRoutes.route('/delete').post((req, res) => {
*/
postRoutes.route('/edit').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
}
utils.account.checkSession(req.body.userId, req.body.sessionId, (isValidId) => {
@@ -84,7 +84,7 @@ postRoutes.route('/edit').post((req, res) => {
if (isValidId && isAdmin) {
Post.findById(req.body._id, (err, r) => {
if (err) {
res.status(500).json({ success: false, response: "Error editing post" });
res.status(500).send("Error editing post");
return;
}
r.save()
@@ -93,12 +93,12 @@ postRoutes.route('/edit').post((req, res) => {
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error creating post" });
res.status(500).send("Error creating post");
});
res.status(200).json({ success: true, response: "Edited post" });
res.status(200).send("Edited post");
});
} else {
res.status(401).json({ success: false, response: "Invalid permissions to delete post." });
res.status(401).send("Invalid permissions to delete post.");
return;
}
})
@@ -115,10 +115,10 @@ postRoutes.route('/id').post((req, res) => {
Post.findById(req.body._id, (err, post) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting posts" });
res.status(500).send("Error getting posts");
return;
}
res.status(200).json({ success: true, response: post });
res.status(200).send(post);
});
});
@@ -133,10 +133,10 @@ postRoutes.route('/date').post((req, res) => {
Post.find({ date: d}, (err, post) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting posts" });
res.status(500).send("Error getting posts");
return;
}
res.status(200).json({ success: true, response: post });
res.status(200).send(post);
});
});
@@ -150,10 +150,10 @@ postRoutes.route('/all').get((req, res) => {
Post.find({}, (err, postArr) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting posts" });
res.status(500).send("Error getting posts");
return;
}
res.status(200).json({ success: true, response: postArr });
res.status(200).send(postArr);
});
});
@@ -169,11 +169,13 @@ postRoutes.route('/today').get((req, res) => {
Post.find({ date: date }, (err, postArr) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error getting posts" });
res.status(500).send("Error getting posts");
return;
}
res.status(200).json({ success: true, response: postArr });
res.status(200).send(postArr);
});
});
module.exports = postRoutes;

View File

@@ -2,9 +2,9 @@ const utils = require('../utils/utils');
const express = require('express');
const bcrypt = require('bcrypt');
const userRoutes = express.Router();
const config = require('../config.js');
const saltRounds = 10;
const sessionLength = 25;
let Session = require('../schema/session.model');
let User = require('../schema/user.model');
@@ -19,44 +19,44 @@ let Reset = require('../schema/reset.model');
*/
userRoutes.route('/create').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
} else if (!req.body.email || !req.body.password || !req.body.name) {
res.status(401).json({ success: false, response: "Missing fields" });
res.status(401).send("Missing body");
return;
} else if (req.body.email == "" || req.body.password == "" || req.body.name == "") {
res.status(401).json({ success: false, response: "Empty fields" });
res.status(401).send("Empty fields");
return;
}
let u = new User(req.body);
bcrypt.hash(u.password, saltRounds, (err, hash) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error creating user" });
res.status(500).send("Error creating user");;
} else {
u.password = hash;
User.find({ email: u.email }, (err, arr) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error creating user" });
res.status(500).send("Error creating user");
}
// Account already exists
if (arr.length != 0) {
res.status(409).json({ success: false, response: "Account already exists" });
res.status(409).send("Account already exists");
return;
}
u.permission = 0;
u.save()
.then(() => {
res.status(201).json({ success: true, response: "Success creating user" });
res.status(201).send("Success creating user");
})
.catch(() => {
res.status(500).json({ success: false, response: "Error creating user" });
res.status(500).send("Error creating user");;
});
});
}
});
});
/*
@@ -67,57 +67,49 @@ userRoutes.route('/create').post((req, res) => {
*/
userRoutes.route('/login').post((req, res) => {
if (!req.body) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
} else if (!req.body.email || !req.body.password) {
res.status(401).json({ success: false, response: "Missing body" });
res.status(401).send("Missing body");
return;
} else if (req.body.email == "" || req.body.password == "") {
res.status(401).json({ success: false, response: "Empty fields" });
res.status(401).send("Empty fields");
return;
}
User.findOne({ email: req.body.email }, (err, u) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error logging in user" });
res.status(500).send("Error logging in user");
return;
}
if (!u) {
res.status(401).json({ success: false, response: "No user exists with that email" });
res.status(401).send("No user exists with that email");
return;
}
bcrypt.compare(req.body.password, u.password, (err, result) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error logging in user" });
res.status(500).send("Error logging in user");
return;
}
if (result) {
let refresh = new Session();
refresh.sessionId = generateSession(config.refreshChracterLength);
refresh.userId = u._id;
refresh.date = new Date();
refresh.type = 1;
let s = new Session();
s.sessionId = generateSession(config.sessionCharacterLength);
s.sessionId = generateSession();
s.userId = u._id;
s.date = new Date();
s.type = 0;
s.save()
.then(() => {
let send = { userId: u._id, sessionId: s.sessionId, refresh: refresh.sessionId}
res.status(200).json({ success: true, response: send});
res.json(s);
})
.catch(() => {
res.status(500).json({ success: false, response: "Error logging in user"});
res.status(500).send("Error logging in user");
});
} else {
res.status(401).json({ success: false, response: "Incorrect password"});
res.status(401).send("Incorrect password");
}
});
@@ -134,23 +126,24 @@ userRoutes.route('/logout').post((req, res) => {
Session.findOne({ sessionId: req.body.sessionId }, (err, sess) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error logging out" });
res.status(500).send("Error logging out");
return;
}
if (!sess) {
res.status(400).json({ success: false, response: "No session found" });
res.status(400).send("No session found");
return;
}
sess.delete()
.then(() => {
res.status(201).json({ success: true, response: "Success deleting session" });
res.status(201).send("Success deleting session");
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error logging out" });
res.status(500).send("Error logging out");
});
});
});
@@ -168,21 +161,21 @@ userRoutes.route('/favorite/add').post((req, res) => {
User.findById(req.body.userId, (err, user) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error adding article" });
res.status(500).send("Error adding article");
return;
}
user.favorites.push(req.body.postId);
user.save()
.then(() => {
res.status(201).json({ success: true, response: "Success saving article" });
res.status(201).send("Success saving article");
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error saving article" });
res.status(500).send("Error saving article");
});
})
} else {
res.status(401).json({ success: false, response: "Unauthorized" });
res.status(401).send("Unauthorized");
}
})
})
@@ -199,21 +192,21 @@ userRoutes.route('/favorite/remove').post((req, res) => {
User.findById(req.body.userId, (err, user) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error removing article" });
res.status(500).send("Error removing article");
return;
}
user.favorites = utils.array.removeValue(user.favorites, req.body.articleId);
user.save()
.then(() => {
res.status(201).json({ success: true, response: "Success removing article" });
res.status(201).send("Success removing article");
})
.catch((e) => {
console.error(e);
res.status(500).json({ success: false, response: "Error removing article" });
res.status(500).send("Error removing article");
});
})
} else {
res.status(401).json({ success: false, response: "Unauthorized"});
res.status(401).send("Unauthorized");
}
})
})
@@ -230,30 +223,19 @@ userRoutes.route('/favorite/get').post((req, res) => {
User.findById(req.body.userId, (err, user) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, response: "Error removing article" });
res.status(500).send("Error removing article");
return;
}
Post.find({ '_id': { $in: user.favorites } }, (err, postArray) => {
res.status(200).json({ success: true, response: postArray });
res.json(postArray);
})
})
} else {
res.status(401).json({ success: false, response: "Unauthorized" });
res.status(401).send("Unauthorized");
}
})
})
userRoutes.route('/check-token').post((req, res) => {
utils.account.checkSession(req.body.userId, req.body.sessionId, valid => {
if (valid) {
res.status(200).json({ success: true, response: "Valid SessionId" });
} else {
res.status(401).json({ success: false, response: "Incorrect SessionId" });
}
});
});
userRoutes.route('/refresh').post((req, res) => {
utils.account.checkRefresh(req.body.userId, req.body.refresh, valid => {
if (valid) {
@@ -264,13 +246,13 @@ userRoutes.route('/refresh').post((req, res) => {
s.save()
.then(() => {
res.status(200).json({ success: true, response: s });
res.json(s);
})
.catch(() => {
res.status(500).json({ success: false, response: "Error logging in user" });
res.status(500).send("Error logging in user");
});
} else {
res.status(401).json({ success: false, response: "Incorrect refresh token" });
res.status(401).send("Incorrect refresh token");
}
}
)
@@ -283,9 +265,9 @@ userRoutes.route('/check-email').post((req, res) => {
}
if (arr.length > 0) {
res.status(400).json({ success: false, response: "Email already in use" });
res.status(400).send("Email already in use");
} else {
res.status(200).json({ success: true, response: "Email not in use" });
res.status(200).send("Email not in use");
}
})
});
@@ -300,13 +282,13 @@ userRoutes.route('/change-name').post((req, res) => {
if (user) {
user.name = req.body.name;
user.save();
res.status(200).json({ success: true, response: "Success changing name" });
res.status(200).send("Success changing name");
} else {
res.status(400).json({ success: false, response: "No user found with that ID" });
res.status(400).send("No user found with that ID");
}
})
} else {
res.status(401).json({ success: false, response: "Unauthorized" });
res.status(401).send("Unauthorized");
}
})
});
@@ -321,13 +303,13 @@ userRoutes.route('/change-email').post((req, res) => {
if (user) {
user.email = req.body.email;
user.save();
res.status(200).json({ success: true, response: "Success changing email" });
res.status(200).send("Success changing email");
} else {
res.status(400).json({ success: false, response: "No user found with that ID" });
res.status(400).send("No user found with that ID");
}
})
} else {
res.status(401).json({ success: false, response: "Unauthorized" });
res.status(401).send("Unauthorized");
}
})
});
@@ -342,13 +324,13 @@ userRoutes.route('/change-password').post((req, res) => {
if (user) {
user.password = req.body.password;
user.save();
res.status(200).json({ success: true, response: "Success changing password" });
res.status(200).send("Success changing password");
} else {
res.status(400).json({ success: false, response: "No user found with that ID" });
res.status(400).send("No user found with that ID");
}
})
} else {
res.status(401).json({ success: false, response: "Unauthorized" });
res.status(401).send("Unauthorized");
}
})
});
@@ -367,9 +349,9 @@ userRoutes.route('/forgot-password').post((req, res) => {
r.date = new Date();
r.save();
utils.mail.sendMail(user, "forgotPassword", [{from: "%name%", to: user.name}, {from: "%pin%", to: pin}]);
res.status(200).json({ success: true, response: "Success sending reset email" });
res.status(200).send("Success sending reset email");
} else {
res.status(400).json({ success: false, response: "No user found with that email" });
res.status(400).send("No user found with that email");
}
}
)
@@ -391,13 +373,13 @@ userRoutes.route('/reset-password').post((req, res) => {
reset.remove();
user.password = req.body.password;
user.save();
res.status(200).json({ success: true, response: "Success resetting password" });
res.status(200).send("Success resetting password");
} else {
res.status(400).json({ success: false, response: "Invalid pin" });
res.status(400).send("Invalid pin");
}
})
} else {
res.status(400).json({ success: false, response: "No user found with that email" });
res.status(400).send("No user found with that email");
}
}
)
@@ -407,7 +389,8 @@ userRoutes.route('/reset-password').post((req, res) => {
module.exports = userRoutes;
function generateSession(length) {
function generateSession() {
var length = sessionLength;
var result = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-+!@#$%^&*()';
var charactersLength = characters.length;

View File

@@ -1,70 +0,0 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Database schema for an email message
let AnalyticData = new Schema({
date: {
type: Date
},
viewCount: {
type: String
},
articleViewCounts: {
type: Array
},
systemTime: {
type: String
},
systemUptime: {
type: String
},
systemCPUBrand: {
type: String
},
systemCPUSpeed: {
type: String
},
systemCPUSpeedMax: {
type: String
},
systemCPUCores: {
type: String
},
systemCPUAverage: {
type: String
},
systemCPUTemperature: {
type: String
},
systemMemoryTotal: {
type: String
},
systemMemoryUsed: {
type: String
},
systemSwapTotal: {
type: String
},
systemSwapUsed: {
type: String
},
systemOSPlatform: {
type: String
},
systemOSDistro: {
type: String
},
systemOSRelease: {
type: String
},
systemOSKernel: {
type: String
},
systemCurrentLoad: {
type: String
},
}, {
collection: 'categories'
});
module.exports = mongoose.model('AnalyticData', AnalyticData);

View File

@@ -4,17 +4,12 @@ const bcrypt = require('bcrypt');
// checkSession(userId, sessionId) checks if the sessionId is valid for the user
const checkSession = (userId, sessionId, f) => {
let success = false;
Session.find({ userId: userId, sessionId: sessionId }, (err, res) => {
res.forEach(element => {
if (element.type == 0 && !success) {
success = true;
f(true);
return;
}
})
if (!success)
f(false);
if (res && res.type == 0) {
f(true);
return;
}
f(false);
});
}

View File