Merge branch 'Dev-branch'

This commit is contained in:
newtbot 2024-01-18 03:17:00 +08:00
commit 63f07add82
3 changed files with 208 additions and 22 deletions

View File

@ -1,19 +1,24 @@
const express = require("express"); const express = require("express");
const helmet = require("helmet"); const helmet = require("helmet");
const path = require("path");
const app = express(); const app = express();
app.use(helmet());
const port = 80; const port = 80;
const bodyParser = require('body-parser'); // Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(helmet());
//disable x-powered-by header for security reasons //disable x-powered-by header for security reasons
app.disable("x-powered-by"); app.disable("x-powered-by");
app.use(express.json()); app.use(express.json());
app.set("json spaces", 2); app.set("json spaces", 2);
//public folder with path to static files
app.use(express.static(path.join(__dirname, "../public")));
//middleware logic ( called by next() ) //middleware logic ( called by next() )
//app.use('/api/v0', APIlogger, require('../routes/api_route.js')); //add token middeware upon login to validate routes that require token
//route logic //route logic
app.use("/api/v0", require("../routes/api_routes")); //consumerWebsite\routes\api_routes.js app.use("/api/v0", require("../routes/api_routes")); //consumerWebsite\routes\api_routes.js
@ -28,21 +33,21 @@ app.use(function (req, res, next) {
}); });
// Error handler. This is where `next()` will go on error // Error handler. This is where `next()` will go on error
app.use(function(err, req, res, next) { app.use(function (err, req, res, next) {
console.error(err.status || res.status, err.name, req.method, req.url); console.error(err.status || res.status, err.name, req.method, req.url);
if(![ 404].includes(err.status || res.status)){ if (![404].includes(err.status || res.status)) {
console.error(err.message); console.error(err.message);
console.error(err.stack); console.error(err.stack);
console.error('========================================='); console.error("=========================================");
} }
console.log(err.name + " validation error"); console.log(err.name + " validation error");
// Parse key error for Sequilzw // Parse key error for Sequilzw
let keyErrors = {} let keyErrors = {};
if(['SequelizeValidationError'].includes(err.name) && err.errors){ if (["SequelizeValidationError"].includes(err.name) && err.errors) {
for(let item of err.errors){ for (let item of err.errors) {
if(item.path){ if (item.path) {
keyErrors[item.path] = item.message keyErrors[item.path] = item.message;
} }
} }
} }
@ -50,11 +55,11 @@ app.use(function(err, req, res, next) {
res.status(err.status || 500); res.status(err.status || 500);
console.log(keyErrors); console.log(keyErrors);
res.json({ res.json({
name: err.name, name: err.name,
message: err.message, message: err.message,
keyErrors, keyErrors,
}); });
}); });
app.listen(port, () => { app.listen(port, () => {
console.log(`app listening on port ${port}`); console.log(`app listening on port ${port}`);
}); });

179
consumerWebsite/public/js/jquery.js vendored Normal file
View File

@ -0,0 +1,179 @@
var app = {};
/*
app.api = (function(app){
var baseURL = '/api/v0/'
function post(url, data, callback){
$.ajax({
type: 'POST',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
)
}
});
}
function put(url, data, callback){
$.ajax({
type: 'PUT',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
)
}
});
}
function remove(url, callback, callback2){
if(!$.isFunction(callback)) callback = callback2;
$.ajax({
type: 'delete',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
)
}
});
}
function get(url, callback){
$.ajax({
type: 'GET',
url: baseURL+url,
headers:{
'auth-token': app.auth.getToken()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function(res, text){
callback(
text !== 'success' ? res.statusText : null,
JSON.parse(res.responseText),
res.status
)
}
});
}
return {post: post, get: get, put: put, delete: remove}
})(app)
*/
app.auth = (function(app) {
var user = {}
function setToken(token){
localStorage.setItem('APIToken', token);
}
function getToken(){
return localStorage.getItem('APIToken');
}
function isLoggedIn(callback){
if(getToken()){
return app.api.get('user/me', function(error, data){
if(!error) app.auth.user = data;
return callback(error, data);
});
}else{
callback(null, false);
}
}
function logIn(args, callback){
app.api.post('auth/login', args, function(error, data){
if(data.login){
setToken(data.token);
}
callback(error, !!data.token);
});
}
function logOut(callback){
localStorage.removeItem('APIToken');
callback();
}
function forceLogin(){
$.holdReady( true );
app.auth.isLoggedIn(function(error, isLoggedIn){
if(error || !isLoggedIn){
app.auth.logOut(function(){})
location.replace(`/login${location.href.replace(location.origin, '')}`);
}else{
$.holdReady( false );
}
});
}
function logInRedirect(){
window.location.href = location.href.replace(location.origin+'/login', '') || '/'
}
return {
getToken: getToken,
setToken: setToken,
isLoggedIn: isLoggedIn,
logIn: logIn,
logOut: logOut,
forceLogin,
logInRedirect,
}
})(app);
//ajax form submit
function formAJAX( btn, del ) {
event.preventDefault(); // avoid to execute the actual submit of the form.
var $form = $(btn).closest( '[action]' ); // gets the 'form' parent
var formData = $form.find( '[name]' ).serializeObject(); // builds query formDataing
var method = $form.attr('method') || 'post';
// if( !$form.validate()) {
// app.util.actionMessage('Please fix the form errors.', $form, 'danger')
// return false;
// }
app.util.actionMessage(
'<div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div>',
$form,
'info'
);
app.api[method]($form.attr('action'), formData, function(error, data){
app.util.actionMessage(data.message, $form, error ? 'danger' : 'success'); //re-populate table
if(!error){
$form.trigger("reset");
eval($form.attr('evalAJAX')); //gets JS to run after completion
}
});
}

View File

@ -15,9 +15,11 @@ router.get("/", async (req, res, next) => {
}); });
router.post("/register", async (req, res, next) => {
// /user/register
router.post("/register", async (req, res, next) => { router.post("/register", async (req, res, next) => {
try { try {
await addUser(req.body); //await addUser(req.body);
res.sendStatus(200); res.sendStatus(200);
} catch (error) { } catch (error) {
console.error(error); console.error(error);