Significant API progress
This commit is contained in:
parent
ea72d194c2
commit
01227bb28f
27 changed files with 2378 additions and 0 deletions
6
backend/.gitignore
vendored
Normal file
6
backend/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
dist
|
||||||
|
.env
|
||||||
|
icloud.js
|
||||||
|
combined.log
|
||||||
|
error.log
|
||||||
|
node_modules
|
||||||
27
backend/Dockerfile
Normal file
27
backend/Dockerfile
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
FROM node:14 AS builder
|
||||||
|
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN npm run build-ts
|
||||||
|
|
||||||
|
FROM node:14-alpine AS server
|
||||||
|
|
||||||
|
WORKDIR /usr/src/app
|
||||||
|
RUN chown -R node:node /usr/src/app
|
||||||
|
|
||||||
|
USER node
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install --production
|
||||||
|
|
||||||
|
COPY --from=0 /usr/src/app/dist dist
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
CMD ["node", "dist/server.js"]
|
||||||
1715
backend/package-lock.json
generated
Normal file
1715
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
46
backend/package.json
Normal file
46
backend/package.json
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
{
|
||||||
|
"name": "opencommerce-api",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "An API for maintaining and running your own E-Commerce Shop!",
|
||||||
|
"main": "",
|
||||||
|
"scripts": {
|
||||||
|
"start": "npm run serve",
|
||||||
|
"build": "npm run build-ts",
|
||||||
|
"serve": "node dist/server.js",
|
||||||
|
"watch-node": "nodemon dist/server.js",
|
||||||
|
"watch": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"cyan.bold,green.bold\" \"npm run watch-ts\" \"npm run watch-node\"",
|
||||||
|
"build-ts": "tsc",
|
||||||
|
"watch-ts": "tsc -w",
|
||||||
|
"serve-debug": "nodemon --inspect dist/server.js",
|
||||||
|
"debug": "npm run build && npm run watch-debug",
|
||||||
|
"watch-debug": "concurrently -k -p \"[{name}]\" -n \"TypeScript,Node\" -c \"cyan.bold,green.bold\" \"npm run watch-ts\" \"npm run serve-debug\""
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@types/body-parser": "^1.19.0",
|
||||||
|
"@types/cors": "^2.8.8",
|
||||||
|
"@types/express": "^4.17.6",
|
||||||
|
"@types/jsonwebtoken": "^8.5.0",
|
||||||
|
"@types/nodemailer": "^6.4.4",
|
||||||
|
"@types/shortid": "0.0.29",
|
||||||
|
"body-parser": "^1.19.0",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"dotenv": "^16.0.0",
|
||||||
|
"email-validator": "^2.0.4",
|
||||||
|
"express": "^4.17.1",
|
||||||
|
"jsonwebtoken": "^8.5.1",
|
||||||
|
"moment": "^2.29.1",
|
||||||
|
"mongoose": "^6.3.0",
|
||||||
|
"nodemailer": "^6.7.0",
|
||||||
|
"shortid": "^2.2.15",
|
||||||
|
"square": "^17.3.0",
|
||||||
|
"uuid": "^8.3.2",
|
||||||
|
"winston": "^3.4.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/uuid": "^8.3.3",
|
||||||
|
"typescript": "^4.6.3"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC"
|
||||||
|
}
|
||||||
48
backend/src/app.ts
Normal file
48
backend/src/app.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
import { json, urlencoded } from "body-parser";
|
||||||
|
import cors from "cors";
|
||||||
|
import express from "express";
|
||||||
|
import Routes from "./app/controllers/routes";
|
||||||
|
import AccessLog from "./app/middleware/AccessLog";
|
||||||
|
import UserInjection from "./app/middleware/UserInjection";
|
||||||
|
import { UserModel } from "./app/models/User";
|
||||||
|
|
||||||
|
interface AuthenticatableRequest {
|
||||||
|
user: UserModel | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request extends AuthenticatableRequest {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.use(cors());
|
||||||
|
app.use(json());
|
||||||
|
app.use(urlencoded({ extended: true }));
|
||||||
|
app.use(UserInjection());
|
||||||
|
app.use(AccessLog());
|
||||||
|
|
||||||
|
Routes.forEach(({ path, httpMethod, handler }) => {
|
||||||
|
switch (httpMethod) {
|
||||||
|
case "GET":
|
||||||
|
app.get(path, handler);
|
||||||
|
break;
|
||||||
|
case "POST":
|
||||||
|
app.post(path, handler);
|
||||||
|
break;
|
||||||
|
case "DELETE":
|
||||||
|
app.delete(path, handler);
|
||||||
|
break;
|
||||||
|
case "PUT":
|
||||||
|
app.put(path, handler);
|
||||||
|
break;
|
||||||
|
case "PATCH":
|
||||||
|
app.patch(path, handler);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
console.log(`${httpMethod}: ${path}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default app;
|
||||||
1
backend/src/app/controllers/admin/routes.ts
Normal file
1
backend/src/app/controllers/admin/routes.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export default [];
|
||||||
18
backend/src/app/controllers/product/crud/create.ts
Normal file
18
backend/src/app/controllers/product/crud/create.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Products from "../../../models/Product";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.user?.admin) {
|
||||||
|
return res.status(403).send();
|
||||||
|
}
|
||||||
|
|
||||||
|
const tmp = new Products(req.body);
|
||||||
|
await tmp.save();
|
||||||
|
return res.status(200).json(tmp);
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
30
backend/src/app/controllers/product/crud/delete.ts
Normal file
30
backend/src/app/controllers/product/crud/delete.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Products from "../../../models/Product";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.user?.admin) {
|
||||||
|
return res.status(403).send();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.params.id) {
|
||||||
|
return res
|
||||||
|
.status(422)
|
||||||
|
.json({ error: "Request is missing Parameter 'id'" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = await Products.findById(req.params.id);
|
||||||
|
if (!product) {
|
||||||
|
return res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: `No such product with ID ${req.params.id} found` });
|
||||||
|
}
|
||||||
|
|
||||||
|
await product.delete();
|
||||||
|
return res.status(200).json({ "Successfully Deleted": product });
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
24
backend/src/app/controllers/product/crud/get.ts
Normal file
24
backend/src/app/controllers/product/crud/get.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Products from "../../../models/Product";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.params.id) {
|
||||||
|
return res
|
||||||
|
.status(422)
|
||||||
|
.json({ error: "Request is missing Parameter 'id'" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = await Products.findById(req.params.id);
|
||||||
|
|
||||||
|
return !!product
|
||||||
|
? res.status(200).json(product)
|
||||||
|
: res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: `No product with ID ${req.params.id} was found.` });
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
13
backend/src/app/controllers/product/crud/list.ts
Normal file
13
backend/src/app/controllers/product/crud/list.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Products from "../../../models/Product";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const products = await Products.find(req.body.searchParams || {});
|
||||||
|
return res.status(200).send(products);
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
35
backend/src/app/controllers/product/crud/update.ts
Normal file
35
backend/src/app/controllers/product/crud/update.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
import Products from "../../../models/Product";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.user?.admin) {
|
||||||
|
return res.status(403).send();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!req.params.id) {
|
||||||
|
return res
|
||||||
|
.status(422)
|
||||||
|
.json({ error: "Request is missing Parameter 'id'" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const product = await Products.findById(req.params.id);
|
||||||
|
|
||||||
|
if (!product) {
|
||||||
|
return res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: `No such product with ID ${req.params.id} found` });
|
||||||
|
}
|
||||||
|
|
||||||
|
product.quantity = req.body.quantity || product.quantity;
|
||||||
|
product.price = req.body.price || product.price;
|
||||||
|
product.hidden = req.body.hidden || product.hidden;
|
||||||
|
|
||||||
|
await product.save();
|
||||||
|
return res.status(200).json(product);
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
36
backend/src/app/controllers/product/routes.ts
Normal file
36
backend/src/app/controllers/product/routes.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
import { RouteCollection } from "../routes";
|
||||||
|
import create from "./crud/create";
|
||||||
|
import del from "./crud/delete";
|
||||||
|
import get from "./crud/get";
|
||||||
|
import list from "./crud/list";
|
||||||
|
import update from "./crud/update";
|
||||||
|
|
||||||
|
const routes: RouteCollection[] = [
|
||||||
|
{
|
||||||
|
httpMethod: "GET",
|
||||||
|
path: "/api/v1/products",
|
||||||
|
handler: list,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "GET",
|
||||||
|
path: "/api/v1/products/:id",
|
||||||
|
handler: get,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "PUT",
|
||||||
|
path: "/api/v1/products",
|
||||||
|
handler: create,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "PATCH",
|
||||||
|
path: "/api/v1/products/:id",
|
||||||
|
handler: update,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "DELETE",
|
||||||
|
path: "/api/v1/products/:id",
|
||||||
|
handler: del,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default routes;
|
||||||
1
backend/src/app/controllers/review/routes.ts
Normal file
1
backend/src/app/controllers/review/routes.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export default [];
|
||||||
20
backend/src/app/controllers/routes.ts
Normal file
20
backend/src/app/controllers/routes.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import AdminRoutes from "./admin/routes";
|
||||||
|
import ProductRoutes from "./product/routes";
|
||||||
|
import ReviewRoutes from "./review/routes";
|
||||||
|
import UserRoutes from "./user/routes";
|
||||||
|
|
||||||
|
export type RouteCollection = {
|
||||||
|
httpMethod: "GET" | "POST" | "DELETE" | "PUT" | "PATCH";
|
||||||
|
path: string;
|
||||||
|
handler: (arg1: Request, arg2: Response) => any;
|
||||||
|
};
|
||||||
|
|
||||||
|
const routes: RouteCollection[] = [
|
||||||
|
...ProductRoutes,
|
||||||
|
...UserRoutes,
|
||||||
|
...ReviewRoutes,
|
||||||
|
...AdminRoutes,
|
||||||
|
];
|
||||||
|
|
||||||
|
export default routes;
|
||||||
44
backend/src/app/controllers/user/crud/create.ts
Normal file
44
backend/src/app/controllers/user/crud/create.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
import EmailValidator from "email-validator";
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Users from "../../../models/User";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const { first, last, email, password } = req.body;
|
||||||
|
const fmtEmail = email.toLowerCase();
|
||||||
|
|
||||||
|
if (!first || !last || !first.length || !last.length) {
|
||||||
|
return res.status(422).json({
|
||||||
|
error: "First and Last Name are Required Fields",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fmtEmail || !fmtEmail.length || !EmailValidator.validate(fmtEmail)) {
|
||||||
|
return res.status(422).json({
|
||||||
|
error: "A valid email is required",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!password || password.length < 8) {
|
||||||
|
return res.status(422).json({
|
||||||
|
error: "Password is required and must contain at least 8 characters",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await Users.find({ email: fmtEmail });
|
||||||
|
if (existing && existing.length) {
|
||||||
|
return res
|
||||||
|
.status(422)
|
||||||
|
.json({ error: `Email address ${fmtEmail} is already registered.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
const created = new Users({ first, last, email: fmtEmail });
|
||||||
|
created.password = created.hashPassword(password);
|
||||||
|
await created.save();
|
||||||
|
return res.status(200).json(created);
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
29
backend/src/app/controllers/user/crud/delete.ts
Normal file
29
backend/src/app/controllers/user/crud/delete.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import EmailValidator from "email-validator";
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import Users from "../../../models/User";
|
||||||
|
import { LOGGER } from "../../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
if (!req.user) {
|
||||||
|
return res
|
||||||
|
.status(422)
|
||||||
|
.json({ error: "Cannot delete user since you are not logged in." });
|
||||||
|
}
|
||||||
|
|
||||||
|
// If you're an admin it's assumed you're deleting someone else's account for them
|
||||||
|
const userIdToDel = req.user.admin ? req.body._id : req.user._id;
|
||||||
|
const user = await Users.findById(userIdToDel);
|
||||||
|
if (!user) {
|
||||||
|
return res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: `User with id ${userIdToDel} not found` });
|
||||||
|
}
|
||||||
|
|
||||||
|
await user.delete();
|
||||||
|
return res.status(200).json({ "Successfully Deleted": user });
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
47
backend/src/app/controllers/user/login.ts
Normal file
47
backend/src/app/controllers/user/login.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
/**
|
||||||
|
* @author Jose Stovall: stovallj1995@gmail.com
|
||||||
|
* This file is the REST API endpoint in charge of logging in a user
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Request, Response } from "express";
|
||||||
|
import * as jwt from "jsonwebtoken";
|
||||||
|
import moment from "moment";
|
||||||
|
import Users, { UserModel } from "../../models/User";
|
||||||
|
import { LOGGER } from "../../util/Logger";
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const user: UserModel | null = await Users.findOne({
|
||||||
|
email: req.body.email.toLowerCase(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: "Email address is not registered." });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user.validPassword(req.body.password)) {
|
||||||
|
return res
|
||||||
|
.status(404)
|
||||||
|
.json({ error: "Invalid password for the email address provided." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = jwt.sign(
|
||||||
|
{
|
||||||
|
_id: user._id,
|
||||||
|
email: user.email,
|
||||||
|
first: user.first,
|
||||||
|
last: user.last,
|
||||||
|
admin: user.admin,
|
||||||
|
expiresAt: moment().add(1, "day").toISOString(),
|
||||||
|
},
|
||||||
|
process.env.JWT_SECRET as string
|
||||||
|
);
|
||||||
|
|
||||||
|
return res.status(200).json({ token });
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(ex);
|
||||||
|
return res.status(500).json({ error: ex });
|
||||||
|
}
|
||||||
|
};
|
||||||
24
backend/src/app/controllers/user/routes.ts
Normal file
24
backend/src/app/controllers/user/routes.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import { RouteCollection } from "../routes";
|
||||||
|
import create from "./crud/create";
|
||||||
|
import del from "./crud/delete";
|
||||||
|
import login from "./login";
|
||||||
|
|
||||||
|
const routes: RouteCollection[] = [
|
||||||
|
{
|
||||||
|
httpMethod: "PUT",
|
||||||
|
path: "/api/v1/user",
|
||||||
|
handler: create,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "DELETE",
|
||||||
|
path: "/api/v1/user",
|
||||||
|
handler: del,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
httpMethod: "POST",
|
||||||
|
path: "/api/v1/user/login",
|
||||||
|
handler: login,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export default routes;
|
||||||
9
backend/src/app/middleware/AccessLog.ts
Normal file
9
backend/src/app/middleware/AccessLog.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
import { logAccess } from "../util/Logger";
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
logAccess(req);
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
};
|
||||||
30
backend/src/app/middleware/UserInjection.ts
Normal file
30
backend/src/app/middleware/UserInjection.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { NextFunction, Request, Response } from "express";
|
||||||
|
import * as jwt from "jsonwebtoken";
|
||||||
|
import moment from "moment";
|
||||||
|
import Users from "../models/User";
|
||||||
|
|
||||||
|
export default () => {
|
||||||
|
return async (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
const token = req.header("auth-token");
|
||||||
|
if (!token) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const { _id, expiresAt } = jwt.verify(
|
||||||
|
token,
|
||||||
|
process.env.JWT_SECRET as string
|
||||||
|
) as { _id: string; expiresAt: string };
|
||||||
|
|
||||||
|
if (moment(moment()).isAfter(expiresAt)) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await Users.findById(_id);
|
||||||
|
req.user = user;
|
||||||
|
next();
|
||||||
|
} catch (err) {
|
||||||
|
return res.status(400).json({ error: `Invalid Token: ${err}` });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
30
backend/src/app/models/Product.ts
Normal file
30
backend/src/app/models/Product.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
import { Document, model, Schema } from "mongoose";
|
||||||
|
|
||||||
|
export type ProductModel = Document & {
|
||||||
|
name: string;
|
||||||
|
quantity: number;
|
||||||
|
price: number;
|
||||||
|
hidden: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ProductSchema = new Schema<ProductModel>({
|
||||||
|
name: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
quantity: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
price: {
|
||||||
|
type: Number,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
hidden: {
|
||||||
|
type: Boolean,
|
||||||
|
required: true,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export default model<ProductModel>("products", ProductSchema, "products");
|
||||||
27
backend/src/app/models/Review.ts
Normal file
27
backend/src/app/models/Review.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { Document, model, Schema, ObjectId, Types } from "mongoose";
|
||||||
|
|
||||||
|
export type ReviewModel = Document & {
|
||||||
|
productId: ObjectId;
|
||||||
|
userId: ObjectId;
|
||||||
|
rating: number; // Out of Decimal from 0.0 to 5.0 (stars)
|
||||||
|
reviewTitle: string; // General title of the review left
|
||||||
|
reviewBody: string; // The actual review left behind.
|
||||||
|
};
|
||||||
|
|
||||||
|
const PRSchema = new Schema<ReviewModel>({
|
||||||
|
productId: {
|
||||||
|
type: Types.ObjectId,
|
||||||
|
ref: "products",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
userId: {
|
||||||
|
type: Types.ObjectId,
|
||||||
|
ref: "users",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
rating: Number,
|
||||||
|
reviewTitle: String,
|
||||||
|
reviewBody: String,
|
||||||
|
});
|
||||||
|
|
||||||
|
export default model<ReviewModel>("productReviews", PRSchema, "productReviews");
|
||||||
38
backend/src/app/models/User.ts
Normal file
38
backend/src/app/models/User.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { Document, model, Schema } from "mongoose";
|
||||||
|
import { scryptSync, randomBytes, timingSafeEqual } from "crypto";
|
||||||
|
|
||||||
|
export type UserModel = Document & {
|
||||||
|
first: string;
|
||||||
|
last: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
admin: boolean;
|
||||||
|
hashPassword: (password: string) => string;
|
||||||
|
validPassword: (password: string) => boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const UserSchema = new Schema<UserModel>({
|
||||||
|
first: String,
|
||||||
|
last: String,
|
||||||
|
email: String,
|
||||||
|
password: String,
|
||||||
|
admin: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
UserSchema.methods.hashPassword = function (password: string) {
|
||||||
|
const salt = randomBytes(16).toString("hex");
|
||||||
|
const hash = scryptSync(password, salt, 64).toString("hex");
|
||||||
|
return `${salt}:${hash}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
UserSchema.methods.validPassword = function (inp: string) {
|
||||||
|
const [salt, key] = this.password.split(":");
|
||||||
|
const hashedBuf = scryptSync(inp, salt, 64);
|
||||||
|
const keyBuf = Buffer.from(key, "hex");
|
||||||
|
return timingSafeEqual(hashedBuf, keyBuf);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default model<UserModel>("users", UserSchema, "users");
|
||||||
23
backend/src/app/util/Logger.ts
Normal file
23
backend/src/app/util/Logger.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { Request } from "express";
|
||||||
|
import winston from "winston";
|
||||||
|
|
||||||
|
export const LOGGER = winston.createLogger({
|
||||||
|
level: "info",
|
||||||
|
format: winston.format.combine(
|
||||||
|
winston.format.timestamp(),
|
||||||
|
winston.format.json()
|
||||||
|
),
|
||||||
|
defaultMeta: { service: "api" },
|
||||||
|
transports: [
|
||||||
|
new winston.transports.File({ filename: "error.log", level: "error" }),
|
||||||
|
new winston.transports.File({ filename: "combined.log" }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
export const logAccess = (req: Request) => {
|
||||||
|
LOGGER.info(
|
||||||
|
`Accessed endpoint ${req.path}. User is ${
|
||||||
|
req.user ? "authenticated" : "not authenticated"
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
};
|
||||||
16
backend/src/db.ts
Normal file
16
backend/src/db.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
import mongoose from "mongoose";
|
||||||
|
import { LOGGER } from "./app/util/Logger";
|
||||||
|
|
||||||
|
export default async () => {
|
||||||
|
try {
|
||||||
|
await mongoose.connect(
|
||||||
|
`mongodb://${process.env.MONGO_URI}/${process.env.MONGO_COLLECTION}`,
|
||||||
|
{ autoIndex: true }
|
||||||
|
);
|
||||||
|
} catch (ex) {
|
||||||
|
LOGGER.error(
|
||||||
|
`Failed to connect to Database. Connection failed with error:`
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
21
backend/src/server.ts
Normal file
21
backend/src/server.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { config as LoadDotenv } from "dotenv";
|
||||||
|
import winston from "winston";
|
||||||
|
import app from "./app";
|
||||||
|
import { LOGGER } from "./app/util/Logger";
|
||||||
|
import ConnectDb from "./db";
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== "production") {
|
||||||
|
LoadDotenv();
|
||||||
|
LOGGER.add(
|
||||||
|
new winston.transports.Console({
|
||||||
|
format: winston.format.simple(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ConnectDb();
|
||||||
|
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
app.listen(port, () =>
|
||||||
|
LOGGER.info(`Server started. Listening on port ${port}`)
|
||||||
|
);
|
||||||
20
backend/tsconfig.json
Normal file
20
backend/tsconfig.json
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "es2017",
|
||||||
|
"noImplicitAny": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "dist",
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"*": ["node_modules/*"]
|
||||||
|
},
|
||||||
|
"lib": ["es2019"]
|
||||||
|
},
|
||||||
|
"include": ["src/**/*", "src/types.d.ts"],
|
||||||
|
"exclude": ["test/**/*"]
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue