Changed request system and post data

Changed from XMLHttpRequest to Axiios and made every POST call to look for params or json and not pass the values as headers. Token is still a header though
This commit is contained in:
Pitu 2017-01-19 02:37:35 -03:00
parent 93891ae1e5
commit 83aaef0f82
10 changed files with 303 additions and 310 deletions

View File

@ -6,16 +6,16 @@ let albumsController = {}
albumsController.list = function(req, res, next){ albumsController.list = function(req, res, next){
if(req.headers.auth !== config.adminToken) if(req.headers.auth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
let fields = ['id', 'name'] let fields = ['id', 'name']
if(req.headers.extended !== undefined) if(req.params.sidebar === undefined)
fields.push('timestamp') fields.push('timestamp')
db.table('albums').select(fields).where('enabled', 1).then((albums) => { db.table('albums').select(fields).where('enabled', 1).then((albums) => {
if(req.headers.extended === undefined) if(req.params.sidebar !== undefined)
return res.json({ success: true, albums }) return res.json({ success: true, albums })
let ids = [] let ids = []
@ -42,9 +42,9 @@ albumsController.list = function(req, res, next){
albumsController.create = function(req, res, next){ albumsController.create = function(req, res, next){
if(req.headers.auth !== config.adminToken) if(req.headers.auth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
let name = req.headers.name let name = req.body.name
if(name === undefined || name === '') if(name === undefined || name === '')
return res.json({ success: false, description: 'No album name specified' }) return res.json({ success: false, description: 'No album name specified' })

View File

@ -4,8 +4,8 @@ const db = require('knex')(config.database)
let tokenController = {} let tokenController = {}
tokenController.verify = function(req, res, next){ tokenController.verify = function(req, res, next){
let type = req.headers.type let type = req.body.type
let token = req.headers.token let token = req.body.token
if(type === undefined) return res.json({ success: false, description: 'No type provided.' }) if(type === undefined) return res.json({ success: false, description: 'No type provided.' })
if(token === undefined) return res.json({ success: false, description: 'No token provided.' }) if(token === undefined) return res.json({ success: false, description: 'No token provided.' })
@ -26,7 +26,7 @@ tokenController.verify = function(req, res, next){
tokenController.list = function(req, res, next){ tokenController.list = function(req, res, next){
if(req.headers.auth !== config.adminToken) if(req.headers.auth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
return res.json({ return res.json({
clientToken: config.clientToken, clientToken: config.clientToken,
@ -36,10 +36,10 @@ tokenController.list = function(req, res, next){
tokenController.change = function(req, res, next){ tokenController.change = function(req, res, next){
if(req.headers.auth !== config.adminToken) if(req.headers.auth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
let type = req.headers.type let type = req.body.type
let token = req.headers.token let token = req.body.token
if(type === undefined) return res.json({ success: false, description: 'No type provided.' }) if(type === undefined) return res.json({ success: false, description: 'No type provided.' })
if(token === undefined) return res.json({ success: false, description: 'No token provided.' }) if(token === undefined) return res.json({ success: false, description: 'No token provided.' })

View File

@ -24,13 +24,13 @@ uploadsController.upload = function(req, res, next){
if(config.private === true) if(config.private === true)
if(req.headers.auth !== config.clientToken) if(req.headers.auth !== config.clientToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
let album = req.headers.album let album = req.body.album
if(album !== undefined) if(album !== undefined)
if(req.headers.adminauth !== config.adminToken) if(req.headers.adminauth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
upload(req, res, function (err) { upload(req, res, function (err) {
if (err) { if (err) {
@ -81,14 +81,14 @@ uploadsController.upload = function(req, res, next){
uploadsController.list = function(req, res){ uploadsController.list = function(req, res){
if(req.headers.auth !== config.adminToken) if(req.headers.auth !== config.adminToken)
return res.status(401).send('not-authorized') return res.status(401).json({ success: false, description: 'not-authorized'})
db.table('files') db.table('files')
.where(function(){ .where(function(){
if(req.headers.albumid === undefined) if(req.params.id === undefined)
this.where('id', '<>', '') this.where('id', '<>', '')
else else
this.where('albumid', req.headers.albumid) this.where('albumid', req.params.id)
}) })
.then((files) => { .then((files) => {
db.table('albums').then((albums) => { db.table('albums').then((albums) => {
@ -114,7 +114,10 @@ uploadsController.list = function(req, res){
} }
return res.json(files) return res.json({
success: true,
files
})
}) })
}) })

View File

@ -1,6 +1,7 @@
const config = require('./config.js') const config = require('./config.js')
const api = require('./routes/api.js') const api = require('./routes/api.js')
const express = require('express') const express = require('express')
const bodyParser = require('body-parser')
const db = require('knex')(config.database) const db = require('knex')(config.database)
const fs = require('fs') const fs = require('fs')
const safe = express() const safe = express()
@ -10,6 +11,9 @@ require('./database/db.js')(db, config)
fs.existsSync('./' + config.uploads.folder) || fs.mkdirSync('./' + config.uploads.folder) fs.existsSync('./' + config.uploads.folder) || fs.mkdirSync('./' + config.uploads.folder)
fs.existsSync('./' + config.logsFolder) || fs.mkdirSync('./' + config.logsFolder) fs.existsSync('./' + config.logsFolder) || fs.mkdirSync('./' + config.logsFolder)
safe.use(bodyParser.urlencoded({ extended: true }))
safe.use(bodyParser.json())
safe.enable('trust proxy') safe.enable('trust proxy')
safe.use('/', express.static('./uploads')) safe.use('/', express.static('./uploads'))

View File

@ -15,6 +15,7 @@
}, },
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"body-parser": "^1.16.0",
"express": "^4.14.0", "express": "^4.14.0",
"knex": "^0.12.6", "knex": "^0.12.6",
"multer": "^1.2.1", "multer": "^1.2.1",

View File

@ -7,6 +7,7 @@
<link rel="stylesheet" type="text/css" href="/css/style.css"> <link rel="stylesheet" type="text/css" href="/css/style.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.min.js"></script>
<script type="text/javascript" src="/js/upload.js"></script> <script type="text/javascript" src="/js/upload.js"></script>
</head> </head>

View File

@ -6,6 +6,7 @@
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
<link rel="stylesheet" type="text/css" href="/css/style.css"> <link rel="stylesheet" type="text/css" href="/css/style.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.min.js"></script>
<script type="text/javascript" src="/js/panel.js"></script> <script type="text/javascript" src="/js/panel.js"></script>
</head> </head>
<body> <body>

View File

@ -15,17 +15,17 @@ panel.preparePage = function(){
} }
panel.verifyToken = function(token, reloadOnError = false){ panel.verifyToken = function(token, reloadOnError = false){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { axios.post('/api/tokens/verify', {
if (xhr.readyState == XMLHttpRequest.DONE) { type: 'admin',
token: token
var json = JSON.parse(xhr.responseText); })
if(json.success === false){ .then(function (response) {
if(response.data.success === false){
swal({ swal({
title: "An error ocurred", title: "An error ocurred",
text: json.description, text: response.data.description,
type: "error" type: "error"
}, function(){ }, function(){
if(reloadOnError){ if(reloadOnError){
@ -33,20 +33,20 @@ panel.verifyToken = function(token, reloadOnError = false){
location.reload(); location.reload();
} }
}) })
return; return;
} }
axios.defaults.headers.common['auth'] = token;
localStorage.admintoken = token; localStorage.admintoken = token;
panel.token = token; panel.token = token;
return panel.prepareDashboard(); return panel.prepareDashboard();
} })
} .catch(function (error) {
xhr.open('GET', '/api/tokens/verify', true); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
xhr.setRequestHeader('type', 'admin'); console.log(error);
xhr.setRequestHeader('token', token); });
xhr.send(null);
} }
panel.prepareDashboard = function(){ panel.prepareDashboard = function(){
@ -70,20 +70,19 @@ panel.prepareDashboard = function(){
} }
panel.getUploads = function(album = undefined){ panel.getUploads = function(album = undefined){
let url = '/api/uploads'
if(album !== undefined)
url = '/api/album/' + album
axios.get(url)
.then(function (response) {
if(response.data.success === false){
if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
else return swal("An error ocurred", response.data.description, "error");
}
panel.page.innerHTML = ''; panel.page.innerHTML = '';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE){
if(xhr.responseText === 'not-authorized')
return panel.verifyToken(panel.token);
var json = JSON.parse(xhr.responseText);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
var container = document.createElement('div'); var container = document.createElement('div');
container.innerHTML = ` container.innerHTML = `
<table class="table is-striped is-narrow"> <table class="table is-striped is-narrow">
@ -101,7 +100,7 @@ panel.getUploads = function(album = undefined){
var table = document.getElementById('table'); var table = document.getElementById('table');
for(var item of json){ for(var item of response.data.files){
var tr = document.createElement('tr'); var tr = document.createElement('tr');
tr.innerHTML = ` tr.innerHTML = `
@ -115,19 +114,24 @@ panel.getUploads = function(album = undefined){
table.appendChild(tr); table.appendChild(tr);
} }
} })
} .catch(function (error) {
xhr.open('GET', '/api/uploads', true); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
if(album !== undefined) console.log(error);
xhr.setRequestHeader('albumid', album); });
xhr.setRequestHeader('auth', panel.token);
xhr.send(null);
} }
panel.getAlbums = function(){ panel.getAlbums = function(){
panel.page.innerHTML = '';
var xhr = new XMLHttpRequest();
axios.get('/api/albums')
.then(function (response) {
if(response.data.success === false){
if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
else return swal("An error ocurred", response.data.description, "error");
}
panel.page.innerHTML = '';
var container = document.createElement('div'); var container = document.createElement('div');
container.className = "container"; container.className = "container";
container.innerHTML = ` container.innerHTML = `
@ -152,21 +156,10 @@ panel.getAlbums = function(){
</tbody> </tbody>
</table>`; </table>`;
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.responseText === 'not-authorized')
return panel.verifyToken(panel.token);
var json = JSON.parse(xhr.responseText);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
panel.page.appendChild(container); panel.page.appendChild(container);
var table = document.getElementById('table'); var table = document.getElementById('table');
for(var item of json.albums){ for(var item of response.data.albums){
var tr = document.createElement('tr'); var tr = document.createElement('tr');
tr.innerHTML = ` tr.innerHTML = `
@ -184,62 +177,55 @@ panel.getAlbums = function(){
panel.submitAlbum(); panel.submitAlbum();
}); });
}
}
xhr.open('GET', '/api/albums', true); })
xhr.setRequestHeader('auth', panel.token); .catch(function (error) {
xhr.setRequestHeader('extended', ''); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
xhr.send(null); console.log(error);
});
} }
panel.submitAlbum = function(){ panel.submitAlbum = function(){
var xhr = new XMLHttpRequest(); axios.post('/api/albums', {
name: document.getElementById('albumName').value
})
.then(function (response) {
xhr.onreadystatechange = function() { if(response.data.success === false){
if (xhr.readyState == XMLHttpRequest.DONE) { if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
else return swal("An error ocurred", response.data.description, "error");
if(xhr.responseText === 'not-authorized') }
return panel.verifyToken(panel.token);
var json = JSON.parse(xhr.responseText);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
swal("Woohoo!", "Album was added successfully", "success"); swal("Woohoo!", "Album was added successfully", "success");
panel.getAlbumsSidebar(); panel.getAlbumsSidebar();
panel.getAlbums(); panel.getAlbums();
return; return;
}
}
xhr.open('POST', '/api/albums', true); })
xhr.setRequestHeader('auth', panel.token); .catch(function (error) {
xhr.setRequestHeader('name', document.getElementById('albumName').value); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
xhr.send(null); console.log(error);
});
} }
panel.getAlbumsSidebar = function(){ panel.getAlbumsSidebar = function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { axios.get('/api/albums/sidebar')
if (xhr.readyState == XMLHttpRequest.DONE) { .then(function (response) {
if(response.data.success === false){
if(xhr.responseText === 'not-authorized') if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
return panel.verifyToken(panel.token); else return swal("An error ocurred", response.data.description, "error");
}
var json = JSON.parse(xhr.responseText);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
var albumsContainer = document.getElementById('albumsContainer'); var albumsContainer = document.getElementById('albumsContainer');
albumsContainer.innerHTML = ''; albumsContainer.innerHTML = '';
if(json.albums === undefined) return; if(response.data.albums === undefined) return;
for(var album of json.albums){ for(var album of response.data.albums){
li = document.createElement('li'); li = document.createElement('li');
a = document.createElement('a'); a = document.createElement('a');
@ -253,12 +239,14 @@ panel.getAlbumsSidebar = function(){
li.appendChild(a); li.appendChild(a);
albumsContainer.appendChild(li); albumsContainer.appendChild(li);
} }
}
}
xhr.open('GET', '/api/albums', true);
xhr.setRequestHeader('auth', panel.token); })
xhr.send(null); .catch(function (error) {
return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
console.log(error);
});
} }
panel.getAlbum = function(item){ panel.getAlbum = function(item){
@ -266,9 +254,15 @@ panel.getAlbum = function(item){
} }
panel.changeTokens = function(){ panel.changeTokens = function(){
panel.page.innerHTML = '';
var xhr = new XMLHttpRequest();
axios.get('/api/tokens')
.then(function (response) {
if(response.data.success === false){
if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
else return swal("An error ocurred", response.data.description, "error");
}
panel.page.innerHTML = '';
var container = document.createElement('div'); var container = document.createElement('div');
container.className = "container"; container.className = "container";
container.innerHTML = ` container.innerHTML = `
@ -287,23 +281,10 @@ panel.changeTokens = function(){
</p> </p>
`; `;
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.responseText === 'not-authorized')
return panel.verifyToken(panel.token);
var json = JSON.parse(xhr.responseText);
console.log(json);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
panel.page.appendChild(container); panel.page.appendChild(container);
document.getElementById('clientToken').value = json.clientToken; document.getElementById('clientToken').value = response.data.clientToken;
document.getElementById('adminToken').value = json.adminToken; document.getElementById('adminToken').value = response.data.adminToken;
document.getElementById('submitClientToken').addEventListener('click', function(){ document.getElementById('submitClientToken').addEventListener('click', function(){
panel.submitToken('client', document.getElementById('clientToken').value); panel.submitToken('client', document.getElementById('clientToken').value);
@ -312,29 +293,28 @@ panel.changeTokens = function(){
document.getElementById('submitAdminToken').addEventListener('click', function(){ document.getElementById('submitAdminToken').addEventListener('click', function(){
panel.submitToken('admin', document.getElementById('adminToken').value); panel.submitToken('admin', document.getElementById('adminToken').value);
}); });
}
}
xhr.open('GET', '/api/tokens', true);
xhr.setRequestHeader('auth', panel.token); })
xhr.send(null); .catch(function (error) {
return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
console.log(error);
});
} }
panel.submitToken = function(type, token){ panel.submitToken = function(type, token){
var xhr = new XMLHttpRequest(); axios.post('/api/tokens/change', {
xhr.onreadystatechange = function() { type: type,
if (xhr.readyState == XMLHttpRequest.DONE) { token: token
})
.then(function (response) {
if(xhr.responseText === 'not-authorized') if(response.data.success === false){
return panel.verifyToken(panel.token); if(response.data.description === 'not-authorized') return panel.verifyToken(panel.token);
else return swal("An error ocurred", response.data.description, "error");
var json = JSON.parse(xhr.responseText); }
console.log(json);
if(json.success === false)
return swal("An error ocurred", json.description, "error");
swal({ swal({
title: "Woohoo!", title: "Woohoo!",
@ -351,14 +331,12 @@ panel.submitToken = function(type, token){
}) })
} })
} .catch(function (error) {
return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
console.log(error);
});
xhr.open('POST', '/api/tokens/change', true);
xhr.setRequestHeader('auth', panel.token);
xhr.setRequestHeader('type', type);
xhr.setRequestHeader('token', token);
xhr.send(null);
} }
window.onload = function () { window.onload = function () {

View File

@ -5,16 +5,18 @@ upload.token = localStorage.token;
upload.maxFileSize; upload.maxFileSize;
upload.checkIfPublic = function(){ upload.checkIfPublic = function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { axios.get('/api/check')
if (xhr.readyState == XMLHttpRequest.DONE) { .then(function (response) {
upload.isPublic = JSON.parse(xhr.responseText).private; upload.isPublic = response.data.private;
upload.maxFileSize = JSON.parse(xhr.responseText).maxFileSize; upload.maxFileSize = response.data.maxFileSize;
upload.preparePage(); upload.preparePage();
} })
} .catch(function (error) {
xhr.open('GET', '/api/check', true); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
xhr.send(null); console.log(error);
});
} }
upload.preparePage = function(){ upload.preparePage = function(){
@ -30,17 +32,17 @@ upload.preparePage = function(){
} }
upload.verifyToken = function(token, reloadOnError = false){ upload.verifyToken = function(token, reloadOnError = false){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { axios.post('/api/tokens/verify', {
if (xhr.readyState == XMLHttpRequest.DONE) { type: 'client',
token: token
var json = JSON.parse(xhr.responseText); })
if(json.success === false){ .then(function (response) {
if(response.data.success === false){
swal({ swal({
title: "An error ocurred", title: "An error ocurred",
text: json.description, text: response.data.description,
type: "error" type: "error"
}, function(){ }, function(){
if(reloadOnError){ if(reloadOnError){
@ -48,7 +50,6 @@ upload.verifyToken = function(token, reloadOnError = false){
location.reload(); location.reload();
} }
}) })
return; return;
} }
@ -56,12 +57,12 @@ upload.verifyToken = function(token, reloadOnError = false){
upload.token = token; upload.token = token;
return upload.prepareUpload(); return upload.prepareUpload();
} })
} .catch(function (error) {
xhr.open('GET', '/api/tokens/verify', true); return swal("An error ocurred", 'There was an error with the request, please check the console for more information.', "error");
xhr.setRequestHeader('type', 'client'); console.log(error);
xhr.setRequestHeader('token', token); });
xhr.send(null);
} }
upload.prepareUpload = function(){ upload.prepareUpload = function(){

View File

@ -13,11 +13,15 @@ routes.get ('/check', (req, res, next) => {
routes.get ('/uploads', (req, res, next) => uploadController.list(req, res)) routes.get ('/uploads', (req, res, next) => uploadController.list(req, res))
routes.post ('/upload', (req, res, next) => uploadController.upload(req, res, next)) routes.post ('/upload', (req, res, next) => uploadController.upload(req, res, next))
routes.get ('/album/:id', (req, res, next) => uploadController.list(req, res, next))
routes.get ('/albums', (req, res, next) => albumsController.list(req, res, next)) routes.get ('/albums', (req, res, next) => albumsController.list(req, res, next))
routes.get ('/albums/:sidebar', (req, res, next) => albumsController.list(req, res, next))
routes.post ('/albums', (req, res, next) => albumsController.create(req, res, next)) routes.post ('/albums', (req, res, next) => albumsController.create(req, res, next))
routes.get ('/albums/test', (req, res, next) => albumsController.test(req, res, next)) routes.get ('/albums/test', (req, res, next) => albumsController.test(req, res, next))
routes.get ('/tokens/verify', (req, res, next) => tokenController.verify(req, res))
routes.get ('/tokens', (req, res, next) => tokenController.list(req, res)) routes.get ('/tokens', (req, res, next) => tokenController.list(req, res))
routes.post ('/tokens/verify', (req, res, next) => tokenController.verify(req, res))
routes.post ('/tokens/change', (req, res, next) => tokenController.change(req, res)) routes.post ('/tokens/change', (req, res, next) => tokenController.change(req, res))
module.exports = routes module.exports = routes