From 4e4e8bfee29943ba375b6a3c9a316fc6cfa42261 Mon Sep 17 00:00:00 2001 From: newtbot Date: Thu, 18 Jan 2024 03:15:31 +0800 Subject: [PATCH] a --- consumerWebsite/Vivian/login.html | 21 --- consumerWebsite/Vivian/signup.html | 24 ---- consumerWebsite/Vivian/signup.js | 35 ----- consumerWebsite/modules/app.js | 47 ++++--- consumerWebsite/public/js/jquery.js | 179 ++++++++++++++++++++++++ consumerWebsite/public/signuplogin.html | 58 ++++++++ consumerWebsite/routes/user.js | 17 +-- 7 files changed, 268 insertions(+), 113 deletions(-) delete mode 100644 consumerWebsite/Vivian/login.html delete mode 100644 consumerWebsite/Vivian/signup.html delete mode 100644 consumerWebsite/Vivian/signup.js create mode 100644 consumerWebsite/public/js/jquery.js create mode 100644 consumerWebsite/public/signuplogin.html diff --git a/consumerWebsite/Vivian/login.html b/consumerWebsite/Vivian/login.html deleted file mode 100644 index 25f261c..0000000 --- a/consumerWebsite/Vivian/login.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - Login Page - - - -

Login

-
- - - - - - - -
- - diff --git a/consumerWebsite/Vivian/signup.html b/consumerWebsite/Vivian/signup.html deleted file mode 100644 index 28a7d84..0000000 --- a/consumerWebsite/Vivian/signup.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - Signup Page - - - -

Signup

-
- - - - - - - - - - -
- - diff --git a/consumerWebsite/Vivian/signup.js b/consumerWebsite/Vivian/signup.js deleted file mode 100644 index 2f036a4..0000000 --- a/consumerWebsite/Vivian/signup.js +++ /dev/null @@ -1,35 +0,0 @@ -function validateForm() { - var userid = document.getElementById('user_id').value; - var username = document.getElementById('user_name').value; - var email = document.getElementById('email').value; - var password = document.getElementById('password').value; - var confirmPassword = document.getElementById('confirmPassword').value; - var email = document.getElementById('email').value; - - // Perform basic validation - if (password !== confirmPassword) { - alert('Passwords do not match'); - return; - } - - // If validation passes, send data to the server - sendDataToServer(username, email, password); -} - -function sendDataToServer(username, password) { - // Use AJAX or fetch to send data to the server - // Example using fetch: - fetch('/signup', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ username, email, password }), - }) - .then(response => response.json()) - .then(data => { - // Handle the response from the server - console.log(data); - }) - .catch(error => console.error('Error:', error)); -} diff --git a/consumerWebsite/modules/app.js b/consumerWebsite/modules/app.js index 0ae4bbf..680beba 100644 --- a/consumerWebsite/modules/app.js +++ b/consumerWebsite/modules/app.js @@ -1,19 +1,24 @@ - const express = require("express"); const helmet = require("helmet"); - +const path = require("path"); const app = express(); -app.use(helmet()); 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 app.disable("x-powered-by"); - app.use(express.json()); 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() ) -//app.use('/api/v0', APIlogger, require('../routes/api_route.js')); +//add token middeware upon login to validate routes that require token //route logic app.use("/api/v0", require("../routes/api_routes")); //consumerWebsite\routes\api_routes.js @@ -28,33 +33,33 @@ app.use(function (req, res, next) { }); // 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); - if(![ 404].includes(err.status || res.status)){ - console.error(err.message); - console.error(err.stack); - console.error('========================================='); + if (![404].includes(err.status || res.status)) { + console.error(err.message); + console.error(err.stack); + console.error("========================================="); } - + console.log(err.name + " validation error"); // Parse key error for Sequilzw - let keyErrors = {} - if(['SequelizeValidationError'].includes(err.name) && err.errors){ - for(let item of err.errors){ - if(item.path){ - keyErrors[item.path] = item.message + let keyErrors = {}; + if (["SequelizeValidationError"].includes(err.name) && err.errors) { + for (let item of err.errors) { + if (item.path) { + keyErrors[item.path] = item.message; } } } - + res.status(err.status || 500); console.log(keyErrors); res.json({ - name: err.name, - message: err.message, - keyErrors, + name: err.name, + message: err.message, + keyErrors, }); - }); +}); app.listen(port, () => { console.log(`app listening on port ${port}`); }); diff --git a/consumerWebsite/public/js/jquery.js b/consumerWebsite/public/js/jquery.js new file mode 100644 index 0000000..78db376 --- /dev/null +++ b/consumerWebsite/public/js/jquery.js @@ -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( + '
Loading...
', + $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 + } + }); + +} \ No newline at end of file diff --git a/consumerWebsite/public/signuplogin.html b/consumerWebsite/public/signuplogin.html new file mode 100644 index 0000000..6f00c07 --- /dev/null +++ b/consumerWebsite/public/signuplogin.html @@ -0,0 +1,58 @@ + + + + + + + + Login & Signup Form + + + + +
+ + + + + +
+ + + + + \ No newline at end of file diff --git a/consumerWebsite/routes/user.js b/consumerWebsite/routes/user.js index 639fe14..d3c211d 100644 --- a/consumerWebsite/routes/user.js +++ b/consumerWebsite/routes/user.js @@ -14,19 +14,12 @@ router.get("/", async (req, res, next) => { } }); -/* -1) req.body is taken from html form or wtv -2) bcrpyt and hash the password on the server side -3) pass to db -*/ -router.post("/new", async (req, res, next) => { +// /user/register +router.post("/register", async (req, res, next) => { try { - //pass pass to hashPassword - let hash = await hashPassword(req.body.password); - //add hash back to req.body - req.body.password = hash; - await addUser(req.body); - res.sendStatus(200); + console.log(req.body); + //await addUser(req.body); + //res.sendStatus(200); } catch (error) { console.error(error); next(error);