Initial commit

This commit is contained in:
Janis M
2022-03-26 11:26:10 +01:00
commit bfe995158e
18 changed files with 2843 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

127
.gitignore vendored Normal file
View File

@@ -0,0 +1,127 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

249
index.js Normal file
View File

@@ -0,0 +1,249 @@
const express = require('express')
const mysql_handler = require("./mysql_handler")
const bcrypt = require("bcryptjs")
const cookieParser = require("cookie-parser")
const jwt = require("jsonwebtoken")
const bodyParser = require("body-parser")
const app = express()
const port = 3000
const SECRET_KEY = "KEY"
app.set("view engine", "ejs")
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(cookieParser());
app.use(bodyParser.json())
app.use(express.static(__dirname + "/static"));
/*
const authcookie = req.cookies.authcookie;
if(!authcookie){
return false;
}
jwt.verify(authcookie, SECRET_KEY, (err, data) =>{
if(err){
return false;
} else if(data.user){
return true;
}
})
*/
function authenticateHandler(req, res, next){
const authcookie = req.cookies.authcookie;
jwt.verify(authcookie, SECRET_KEY, (err, data) =>{
if(err){
console.log(err)
res.redirect("/login")
} else if(data.user){
req.user = data.user;
mysql_handler.con.query(`SELECT * FROM users WHERE id = "${req.user}"`, function(err, result){
if(err) console.log(err);
let user = JSON.parse(JSON.stringify(result))[0];
req.isAdmin = user.isAdmin
req.username = user.username
req.firstname = user.firstname
req.lastname = user.lastname
next();
});
}
})
}
app.get("/", authenticateHandler, (req, res) => {
let dict = {
title: "Hallo",
isAdmin: req.isAdmin
}
res.render('index', dict)
})
app.get("/product/:productId", (req, res) => {
let productId = req.params.productId;
console.log(productId);
mysql_handler.con.query(`SELECT * FROM products WHERE id=${productId}` , function(err, result){
if(err) throw err;
let product = JSON.parse(JSON.stringify(result))[0];
let dict = {
title: "product",
product: product
}
res.render('product', dict)
});
})
app.get("/search", (req, res) => {
var products = [
{
title: "Panasonic LUMIX DC-GH5M2ME",
price: 1699.99,
img: "https://m.media-amazon.com/images/I/815eDw--FQS._AC_SL1500_.jpg",
desc: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
},
{
title: "Sony α 7 IV",
price: 2999.00,
img: "https://m.media-amazon.com/images/I/819+EOCsREL._AC_SL1500_.jpg",
desc: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
},
{
title: "Canon PowerShot G3 X",
price: 876.34,
img: "https://m.media-amazon.com/images/I/91bODLikNBL._AC_SL1500_.jpg",
desc: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
},
{
title: "Canon PowerShot SX710",
price: 495.00,
img: "https://m.media-amazon.com/images/I/91w6iw3JtiL._AC_SL1500_.jpg",
desc: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.",
},
]
let dict = {
title: "Suche",
products: products
}
mysql_handler.con.query("SELECT * FROM products", function(err, result){
if(err) throw err;
dict.products = JSON.parse(JSON.stringify(result));
res.render('search', dict)
});
})
// Admin
app.get("/admin/product/delete/:productId", authenticateHandler, (req, res) => {
if(req.isAdmin){
productId = req.params.productId
mysql_handler.con.query(`DELETE FROM products WHERE id=${productId}`, function(err, result){
if(err) console.log(err);
});
}
})
// AUTH
app.get("/logout/", authenticateHandler, (req, res) => {
res.clearCookie("authcookie")
res.end()
})
app.get("/register/", (req, res) => {
let dict = {
title: "Register",
error: ""
}
res.render('register', dict)
})
app.get("/login/", (req, res) => {
let dict = {
title: "Login",
error: ""
}
res.render('login', dict)
})
app.get("/register/:error", (req, res) => {
let dict = {
title: "Register",
error: req.params.error
}
res.render('register', dict)
})
app.get("/login/:error", (req, res) => {
let dict = {
title: "Login",
error: req.params.error
}
res.render('login', dict)
})
app.post("/auth/register", (req, res) =>{
let username = req.body.username;
let email = req.body.email;
let password1 = req.body.password1;
let password2 = req.body.password2;
let firstname = req.body.firstname;
let lastname = req.body.lastname;
let gender = req.body.gender;
error = ""
if(password1 != password2){
error += "Passwörter sind unterschiedlich!";
}else if(password1.length < 8){
error += "Passwort muss mindestens 8 Zeichen lang sein!"
}
if(username.length < 3){
error += "<br> Der Benutzername muss mindestens 3 Zeichen lang sein!";
}else if(username.length > 30){
error += "<br> Der Benutzername darf maximal 30 Zeichen lang sein!";
}
if(error != ""){
res.redirect(`/register/${error}`)
}else{
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password1, salt, function(err, hash){
mysql_handler.createUser(username, email, hash, firstname, lastname, gender);
res.redirect(`/login/`)
})
})
}
})
app.post("/auth/login", (req, res) =>{
let username = req.body.username;
let password = req.body.password;
error = ""
mysql_handler.con.query(`SELECT * FROM users WHERE username = "${username}"`, function(err, result){
if(err){
error = "Login-Daten falsch!"
}else{
if(JSON.parse(JSON.stringify(result))[0]){
user = JSON.parse(JSON.stringify(result))[0]
dbPassword = user.password;
bcrypt.compare(password, dbPassword, function(err, matched){
if(err) console.log(err);
if(matched){
// login
const token = jwt.sign({user:user.id}, SECRET_KEY)
res.cookie('authcookie', token, {maxAge: 900000, httpOnly: true})
res.redirect(`/`)
}else{
error = "Login-Daten falsch!"
}
})
}else{
error = "Login-Daten falsch!"
}
}
});
if(error != ""){
res.redirect(`/login/${error}`)
}
})
app.listen(port, () =>{
console.log("Listining to " + port)
})

113
mysql_handler.js Normal file
View File

@@ -0,0 +1,113 @@
let mysql = require('mysql')
let connected = false;
// TODO check here for errors and do not let the db throw an error in order to give the user feedback
/*
con.query("SELECT * FROM users", function(err, result){
if(err) throw err;
}
console.log(result);
});
*/
let con = mysql.createConnection({
host: "localhost",
user: "onlineshop",
password: "TestUser321",
database: "onlineshop"
});
con.connect(function(err){
if(err) throw err;
console.log("Connected to MySQL!");
connected = true
//createUser("dertyp", "address@email.com", "password", "Janis", "Meister", "Herr");
//createAddress("street", "1", "postcode", "city", "country", 18)
//createSeller("TEST", "test")
//createProduct("name", 1.2, "description", 2, 2, 1, 1)
//createReview("TESt", "Content", 6, 18, 1)
//createOrder(18, "tasddadse");
//createOrderProduct(1.5, 5, 1, 1)
})
function isConnected(){
if(connected){
return true;
}else{
console.log("not connected to mysql")
return false;
}
}
function sendQuery(sql){
if(isConnected){
con.query(sql, function(err, result){
if(err){
console.log(err);
return false;
}
return result;
});
}
}
// CREATES
function createOrder(userId, trackingnumber, received = 0){
createOrderStatus(trackingnumber);
sendQuery(`INSERT INTO orders(userId, order_statusId)
VALUES ((SELECT id FROM users WHERE id='${userId}'), (SELECT id FROM order_status WHERE trackingnumber='${trackingnumber}'))`);
}
function createOrderProduct(price, quantity, productId, orderId){
r = sendQuery(`INSERT INTO order_products(price, quantity, productId, orderId)
VALUES ('${price}','${quantity}',
(SELECT id FROM products WHERE id='${productId}'), (SELECT id FROM orders WHERE id='${orderId}'))`);
}
function createOrderStatus(trackingnumber, received = 0){
sendQuery(`INSERT INTO order_status(received, trackingnumber) VALUES (${received}, '${trackingnumber}')`);
}
function createReview(title, content, rating, userID, productId){
sendQuery(`INSERT INTO reviews(title, content, rating, userID, productId)
VALUES ('${title}','${content}','${rating}',
(SELECT id FROM users WHERE id='${userID}'), (SELECT id FROM products WHERE id='${productId}'))`);
}
function createProduct(name, price, description, quantity, delivery_time, sellerId, categoryId){
sendQuery(`INSERT INTO products(name, price, description, quantity, delivery_time, sellerId, categoryId)
VALUES ('${name}',${price},'${description}','${quantity}','${delivery_time}',
(SELECT id FROM sellers WHERE id='${sellerId}'), (SELECT id FROM categories WHERE id='${categoryId}'))`);
}
function createCategory(name){
sendQuery(`INSERT INTO categories(name) VALUES ('${name}')`);
}
function createSeller(name, description){
sendQuery(`INSERT INTO sellers(name, description) VALUES ('${name}', '${description}')`);
}
function createUser(username, email, password, firstname, lastname, gender){
result = sendQuery(`INSERT INTO users(username, email, password) VALUES ('${username}','${email}','${password}')`);
if(result){
sendQuery(`INSERT INTO userinfos(firstname, lastname, gender, userId) VALUES ('${firstname}','${lastname}','${gender}',
(SELECT id FROM users WHERE username='${username}' AND email='${email}'))`);
console.log(`User created: ${username}!`)
}
}
function createAddress(street, housenumber, postcode, city, country, userId){
sendQuery(`INSERT INTO addresses(street, housenumber, postcode, city, country, userId) VALUES ('${street}','${housenumber}','${postcode}','${city}','${country}',
(SELECT id FROM users WHERE id='${userId}'))`);
}
module.exports = {
sendQuery, createOrder, createOrderProduct, createOrderStatus, createReview,
createProduct, createCategory, createSeller, createUser, createAddress, con
}

318
onlineshop.sql Normal file
View File

@@ -0,0 +1,318 @@
-- MariaDB dump 10.19 Distrib 10.4.24-MariaDB, for Win64 (AMD64)
--
-- Host: localhost Database: onlineshop
-- ------------------------------------------------------
-- Server version 10.4.24-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `addresses`
--
DROP TABLE IF EXISTS `addresses`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addresses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`street` varchar(60) NOT NULL,
`housenumber` int(11) NOT NULL,
`postcode` varchar(30) NOT NULL,
`city` varchar(60) NOT NULL,
`country` varchar(60) NOT NULL,
`userId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `addresses_ibfk_1` (`userId`),
CONSTRAINT `addresses_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `addresses`
--
LOCK TABLES `addresses` WRITE;
/*!40000 ALTER TABLE `addresses` DISABLE KEYS */;
INSERT INTO `addresses` VALUES (1,'street',1,'postcode','city','country',18);
/*!40000 ALTER TABLE `addresses` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `categories`
--
DROP TABLE IF EXISTS `categories`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `categories`
--
LOCK TABLES `categories` WRITE;
/*!40000 ALTER TABLE `categories` DISABLE KEYS */;
INSERT INTO `categories` VALUES (3,'Bauwaren'),(1,'Elektrowaren'),(4,'Television');
/*!40000 ALTER TABLE `categories` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `order_products`
--
DROP TABLE IF EXISTS `order_products`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `order_products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`price` decimal(10,2) NOT NULL,
`quantity` int(11) NOT NULL,
`productId` int(11) NOT NULL,
`orderId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `order_products_ibfk_1` (`productId`),
KEY `orderId` (`orderId`),
CONSTRAINT `order_products_ibfk_1` FOREIGN KEY (`productId`) REFERENCES `products` (`id`) ON DELETE CASCADE,
CONSTRAINT `order_products_ibfk_2` FOREIGN KEY (`orderId`) REFERENCES `orders` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `order_products`
--
LOCK TABLES `order_products` WRITE;
/*!40000 ALTER TABLE `order_products` DISABLE KEYS */;
INSERT INTO `order_products` VALUES (6,1.50,50,1,1);
/*!40000 ALTER TABLE `order_products` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `order_status`
--
DROP TABLE IF EXISTS `order_status`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `order_status` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`received` tinyint(1) NOT NULL DEFAULT 0,
`trackingnumber` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `trackingnumber` (`trackingnumber`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `order_status`
--
LOCK TABLES `order_status` WRITE;
/*!40000 ALTER TABLE `order_status` DISABLE KEYS */;
INSERT INTO `order_status` VALUES (5,0,'undefined'),(8,0,'tasdadse'),(9,0,'tasddadse');
/*!40000 ALTER TABLE `order_status` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `orders`
--
DROP TABLE IF EXISTS `orders`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_statusId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `userId` (`userId`),
KEY `orders_ibfk_2` (`order_statusId`),
CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE,
CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`order_statusId`) REFERENCES `order_status` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `orders`
--
LOCK TABLES `orders` WRITE;
/*!40000 ALTER TABLE `orders` DISABLE KEYS */;
INSERT INTO `orders` VALUES (1,8,18),(2,9,18),(3,9,18);
/*!40000 ALTER TABLE `orders` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `products`
--
DROP TABLE IF EXISTS `products`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) NOT NULL,
`price` decimal(10,2) NOT NULL,
`description` text NOT NULL,
`quantity` int(11) NOT NULL DEFAULT 0,
`delivery_time` int(11) NOT NULL,
`sellerId` int(11) NOT NULL,
`categoryId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `article_ibfk_1` (`sellerId`),
KEY `article_ibfk_2` (`categoryId`),
CONSTRAINT `products_ibfk_1` FOREIGN KEY (`sellerId`) REFERENCES `sellers` (`id`) ON DELETE CASCADE,
CONSTRAINT `products_ibfk_2` FOREIGN KEY (`categoryId`) REFERENCES `categories` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `products`
--
LOCK TABLES `products` WRITE;
/*!40000 ALTER TABLE `products` DISABLE KEYS */;
INSERT INTO `products` VALUES (1,'LED Leiste mit RGBW',3.56,'Mit warmweiß funktion',2,2,1,1),(2,'Nagel ',2.00,'Gut zum nageln',200,2,1,3),(3,'Glühbirne x35 10000000 Watt',1.60,'Glühbirne mit viel Watt',2,2,1,1),(4,'LG TV 500x QHD',130.99,'Richtig guter TV mit perfekter Qualität',27,3,1,4);
/*!40000 ALTER TABLE `products` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `reviews`
--
DROP TABLE IF EXISTS `reviews`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reviews` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(60) NOT NULL,
`content` text NOT NULL,
`rating` int(2) NOT NULL DEFAULT 0,
`userId` int(11) NOT NULL,
`productId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `userId` (`userId`),
KEY `productId` (`productId`),
CONSTRAINT `reviews_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE,
CONSTRAINT `reviews_ibfk_2` FOREIGN KEY (`productId`) REFERENCES `products` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `reviews`
--
LOCK TABLES `reviews` WRITE;
/*!40000 ALTER TABLE `reviews` DISABLE KEYS */;
INSERT INTO `reviews` VALUES (1,'TESt','',6,18,1),(2,'TESt','Content',6,18,3),(3,'test','test',5,18,1);
/*!40000 ALTER TABLE `reviews` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sellers`
--
DROP TABLE IF EXISTS `sellers`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sellers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(60) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sellers`
--
LOCK TABLES `sellers` WRITE;
/*!40000 ALTER TABLE `sellers` DISABLE KEYS */;
INSERT INTO `sellers` VALUES (1,'Rüdiger','Hersteller für Wasserleitungen'),(2,'Hans-Jürgen GmbH','Hersteller von Elektrowaren'),(3,'Peter-Schmit','Hersteller von lauten Baugeräuschen während der Arbeitszeit.');
/*!40000 ALTER TABLE `sellers` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `userinfos`
--
DROP TABLE IF EXISTS `userinfos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userinfos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(60) NOT NULL,
`lastname` varchar(60) NOT NULL,
`gender` varchar(60) NOT NULL,
`userId` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `userinfos_ibfk_1` (`userId`),
CONSTRAINT `userinfos_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `userinfos`
--
LOCK TABLES `userinfos` WRITE;
/*!40000 ALTER TABLE `userinfos` DISABLE KEYS */;
/*!40000 ALTER TABLE `userinfos` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(60) NOT NULL,
`email` varchar(60) NOT NULL,
`password` varchar(255) NOT NULL,
`isAdmin` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `users`
--
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (18,'dertyp','address@email.com','password',0),(19,'janis','janis.meister87@gmail.com','$2a$10$uRt2KBcBcIHVD24XPdCIXeXfJmE6k/78CuXnSi0ukTEA9m0qfyKA6',0),(20,'janis2','jadnis.meister87@gmail.com','$2a$10$QuAII9wQsbKeFMVtJON/r.ke.jKGbUBBd24hUQWg65nKcVNDjJiGG',1);
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2022-03-26 11:24:57

1536
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "onlineshop",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.2",
"cookie-parser": "^1.4.6",
"ejs": "^3.1.6",
"express": "^4.17.3",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1"
}
}

22
static/auth.css Normal file
View File

@@ -0,0 +1,22 @@
h1{
text-align: center;
}
form{
display:block;
margin-left: auto;
margin-right: auto;
width: 500px;
}
form input{
width: 80%;
display:block;
margin-left: auto;
margin-right: auto;
height: 35px;
border-radius: 5px;
border: 2px solid rgb(0, 155, 194);
background-color: rgb(255, 255, 255);
margin-top: 20px;
}

3
static/style.css Normal file
View File

@@ -0,0 +1,3 @@
*{
font-family: Arial, Helvetica, sans-serif;
}

12
views/admin.ejs Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
</head>
<body>
<header>
<%- include('partials/header'); %>
</header>
</body>
</html>

10
views/index.ejs Normal file
View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
</head>
<body>
<h1>isAdmin: <%= isAdmin %></h1>
</body>
</html>

19
views/login.ejs Normal file
View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
<link rel="stylesheet" href="/auth.css">
</head>
<body>
<h1>Login</h1>
<form action="/auth/login" method="POST">
<p style="text-align:center;"><%- error %></p>
<input required type="text" name="username" id="usernameInput" placeholder="Enter your username">
<input required type="password" name="password" id="passwordInput" placeholder="Enter your password">
<input style="width: 40%;cursor:pointer;" type="submit" value="Login">
</form>
</body>
</html>

30
views/partials/footer.ejs Normal file
View File

@@ -0,0 +1,30 @@
<div class="footerDIV">
<div class="footerDIVLogo">
<img src="https://bock-drauf.com/wp-content/uploads/2019/09/amazon-logo-1024x576.png"/>
</div>
</div>
<style type="text/css">
.footerDIV {
width: 100%;
height:65px;
position: absolute;
bottom:-65px;
background-color: #414854;
}
/* LOGO PART */
.footerDIVLogo {
width: 20%;
height:80%;
margin-left: auto;
margin-right: auto;
}
.footerDIVLogo > img {
height: 80%;
position: relative;
top:20%;
left:40%;
margin-left: auto;
margin-right: auto;
}
</style>

6
views/partials/head.ejs Normal file
View File

@@ -0,0 +1,6 @@
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shop - <%= title %></title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="/style.css">

82
views/partials/header.ejs Normal file
View File

@@ -0,0 +1,82 @@
<div class="headerDIV">
<div class="headerDIVLogo">
<img src="https://bock-drauf.com/wp-content/uploads/2019/09/amazon-logo-1024x576.png">
</div><div class="headerDIVSearch">
<input placeholder="Suche" class="vertical-center"></input
><button class="vertical-center"><i class="material-icons">search</i></button>
</div><div class="headerDIVLogin">
<button class="vertical-center">Login</button>
</div>
</div>
<style type="text/css">
/* UTIL */
.vertical-center {
float: left;
top: 50%;
position: relative;
transform: translateY(-50%);
}
body {
margin: 0;
}
/* BACKGROUND */
.headerDIV > div {
height: 100%;
text-align: center;
display: inline-block;
vertical-align: top;
}
/* LOGO PART */
.headerDIVLogo {
width: 20%;
}
.headerDIVLogo > img {
float: left;
height: 80%;
position: relative;
top: 10%;
}
/* SEARCH PART */
.headerDIVSearch {
width: 60%;
}
.headerDIVSearch > input {
left: 10%;
width: calc(80% - 60px);
border-radius: 5px;
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
height: 20px;
padding: 3px 10px;
}
.headerDIVSearch > button {
width: 40px;
left: 10%;
border-radius: 5px;
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
height: 30px;
}
/* LOGIN PART */
.headerDIVLogin {
width: 20%;
}
.headerDIVLogin > button {
height: 30px;
float: right;
margin-right: 10px;
}
.headerDIV {
width: 100%;
height: 65px;
background-color: #414854;
margin: 0;
}
</style>

168
views/product.ejs Normal file
View File

@@ -0,0 +1,168 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
</head>
<body>
<header>
<%- include('partials/header'); %>
</header>
<div id="content">
<div id="top">
<div id="productPicture">
<!--BILD-->
</div>
<div id="info">
<h1 id="title"><%= product.name %></h1>
<p style="word-wrap: break-word;"></p>
<div>
<label style="margin-right: 30px; margin-left: 30px;
<% if(stockAmount > 0){%>
color: green;">
lieferbar in <%= shippingDays %> - <%= shippingDays + 1 %> Tagen</label>
<span><input type="number" id="quantity" min="1" max="<%= stockAmount %>" style="width: 30px;" value="1" ></span>
<label>/<%= stockAmount %></label>
<% } else { %>
color: red;">
nicht lieferbar</label>
<% } %>
</div>
</div>
</div>
<div id="description">
<h1 style="margin-left: 30px;">Beschreibung</h1>
<p style="margin-left: 30px;"><%= productDescription %></p>
</div>
<% if(loggedIn){ %>
<div id="newReview">
<h1 style="padding-left: 30px;">Bewertung</h1>
<textarea name="review" id="" cols="60" rows="5" style="margin-left: 30px; resize: none;"></textarea>
<button>Post</button>
</div>
<% } %>
<div id="reviews">
<% if(reviews > 0){ %>
<div id="reviewTemplate">
<div style="width: 100%; height: 200px; display: block; float: left;">
<div id= data >
<h3 style="padding-left: 30px; width: 100%;">187Boii 12.12.12 12:12</h3>
</div>
<div id="text" >
<p style="padding-left: 30px;";">junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text junge geiler text </p>
</div>
</div>
</div>
<% }else{ %>
<div style="width: 100%; height: 100px;">Leider hat dieses Produkt noch keine Bewertung. :(</div>
<% } %>
</div>
</div>
<style>
*{
padding:0;
}
#content
{
width: 1000px;
height:3000px;
background-color: rgb(59, 59, 59);
margin:auto;
}
#productPicture
{
width: 40%;
height: 400px;
background-color: rgb(85, 85, 85);
display: block;
float: left;
}
#info
{
width: 60%;
height: 400px;
display: block;
float: right;
background-color: rgb(121, 170, 182);
}
#description
{
width: 100%;
height: 250px;
display: block;
float: left;
background-color: rgb(103, 187, 183);
}
#title
{
margin-left: 30px;
}
#newReview{
width: 100%;
height: 200px;
display: block;
float: left;
background-color: rgb(45, 66, 94);
}
#reviews{
width: 100%;
height: 1600px;
display: block;
float: left;
background-color: rgb(39, 39, 39);
}
#reviewTemplate
{
width: 100%;
height: 200px;
float: left;
}
#reviewTemplatePicture
{
width: 200px;
height: 200px;
display: block;
float: left;
background-color: rgb(85, 158, 255);
}
#data
{
width: 100%;
height: 50px;
display: block;
float: left;
background-color: rgb(58, 94, 97);
}
#text
{
width: 100%;
height: 150px;
display: block;
float: left;
background-color: rgb(78, 129, 133);
}
#reviewTemplateText
{
background-color: rgb(235, 196, 228);
}
</style>
<%- include('partials/footer'); %>
</body>
</html>

24
views/register.ejs Normal file
View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
<link rel="stylesheet" href="/auth.css">
</head>
<body>
<h1>Register</h1>
<form action="/auth/register" method="POST">
<p style="text-align:center;"><%- error %></p>
<input required type="text" name="username" id="usernameInput" placeholder="Enter your username">
<input required type="email" name="email" id="emailInput" placeholder="Enter your E-Mail">
<input required type="password" name="password1" id="password1Input" placeholder="Enter your password">
<input required type="password" name="password2" id="password2Input" placeholder="Repeat your password">
<input required type="text" name="firstname" id="firstnameInput" placeholder="Enter your firstname">
<input required type="text" name="lastname" id="lastnameInput" placeholder="Enter your lastname">
<input required type="text" name="gender" id="genderInput" placeholder="How should we call you?">
<input style="width: 40%;cursor:pointer;" type="submit" value="Register">
</form>
</body>
</html>

102
views/search.ejs Normal file
View File

@@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('partials/head'); %>
</head>
<body>
<header>
<%- include('partials/header'); %>
</header>
<div class="allProductsDIV">
<% for(var i=0; i < products.length; i++) { var prod = products[i]; %>
<div class="productDIV">
<h4><%=prod.name %></h4>
<div class="productImage">
<img src="<%= prod.src %>">
</div>
<div class="productInfo"><%=prod.desc %></div>
</div>
<% } %>
</div>
</body>
</html>
<style type="text/css">
.productDIV > img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.productDIV > .productImage {
width: calc(50% - 15px);
height: calc(100% - 120px);
position: absolute;
background-color: red;
left: 10px;
bottom: 10px;
}
.productDIV > .productInfo {
width: calc(50% - 15px);
height: calc(100% - 120px);
position: absolute;
overflow-y: hidden;
background-color: blue;
right: 10px;
bottom: 10px;
}
.productDIV > h4 {
padding: 0px;
margin: 0px;
}
.productDIV {
font-size: 16px;
margin: 10px;
padding: 5px;
display: inline-block;
background-color: white;
border-style: solid;
border-width: 2px;
position: relative;
height: 250px;
}
.allProductsDIV {
font-size: 0;
margin: 0px;
width: calc(80% - 20px);
left: 10%;
position: absolute;
height: 100%;
padding: 10px;
background-color: white;
display: grid;
}
@media (max-width: 400px) {
.allProductsDIV {
grid-template-columns: 1fr;
}
}
@media (min-width: 800px) {
.allProductsDIV {
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1200px) {
.allProductsDIV {
grid-template-columns: 1fr 1fr 1fr;
}
}
</style>