mirror of
https://github.com/GithubOrgProjectPiza/server.git
synced 2026-09-04 16:46:07 +02:00
Merge branch 'dev' into routes-implementation
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import express from "express";
|
||||
import { Request, Response } from "express";
|
||||
import prisma from "../lib/prisma.lib";
|
||||
import { Role, Status } from "@prisma/client";
|
||||
import { createDefaultError, createDefaultSucces } from "../lib/standardResponse";
|
||||
import argon2 from "argon2";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { emailClient } from "../lib/redis.lib";
|
||||
import { nanoid } from "nanoid";
|
||||
import { verificationMail } from "../lib/mail";
|
||||
|
||||
const JWT_SECRET = process.env.jwtsecret || "secret";
|
||||
|
||||
interface registerBody {
|
||||
name: string;
|
||||
password: string;
|
||||
role: string;
|
||||
organization?: number;
|
||||
}
|
||||
|
||||
export interface authJwt {
|
||||
id: number;
|
||||
role: string;
|
||||
}
|
||||
|
||||
const ROLES: readonly string[] = [Role.ADMIN, Role.USER];
|
||||
|
||||
export const register = async (req: Request, res: Response) => {
|
||||
const { name, password, role, organization } = req.body || {};
|
||||
|
||||
if (
|
||||
!(
|
||||
typeof name === "string" &&
|
||||
typeof password === "string" &&
|
||||
ROLES.includes(role) &&
|
||||
typeof organization === "number"
|
||||
)
|
||||
) {
|
||||
return res.status(400).json(
|
||||
createDefaultError("Request body does not match required parameters", {
|
||||
name: "string",
|
||||
password: "string",
|
||||
organization: "int",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const hash = await argon2.hash("salty" + password + "salty",{
|
||||
type: argon2.argon2id
|
||||
});
|
||||
|
||||
if (!(await prisma.organization.findUnique({ where: { id: organization } }))) {
|
||||
return res.status(404).json(createDefaultError(`Could not find organization with id ${organization}`, {}));
|
||||
}
|
||||
|
||||
if (role ? ("USER" as Role) === Role.ADMIN : Role) {
|
||||
if (req.auth?.role !== Role.ADMIN) {
|
||||
return res.status(401).json(createDefaultError(`Unauthorized`, {}));
|
||||
}
|
||||
}
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email: name,
|
||||
passwordSalt: "salty",
|
||||
passwordHash: hash,
|
||||
role: role as Role,
|
||||
status: role === Role.ADMIN ? Status.UNVERIFIED : Status.ENABLED,
|
||||
organization: { connect: { id: organization } || undefined },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
const usid = nanoid();
|
||||
|
||||
(await emailClient).set(usid, user.id);
|
||||
|
||||
verificationMail(name, usid);
|
||||
|
||||
res.status(201).json(createDefaultSucces("User created succesfully", user));
|
||||
};
|
||||
|
||||
export const authenthicate = async (req: Request, res: Response) => {
|
||||
const { name, password } = req.body || {};
|
||||
|
||||
if (!(typeof name === "string" && typeof password === "string")) {
|
||||
return res.status(400).json(
|
||||
createDefaultError("Request body does not match required parameters", {
|
||||
name: "string",
|
||||
password: "string",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const hash = await argon2.hash("salty" + password + "salty",{
|
||||
type: argon2.argon2id
|
||||
});
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { email: name } });
|
||||
|
||||
if (!user) {
|
||||
return res.status(403).json(createDefaultError("Username or Password wrong", {}));
|
||||
}
|
||||
|
||||
if (await argon2.verify(user.passwordHash,hash)) {
|
||||
return res.status(403).json(createDefaultError("Username or Password wrong", {}));
|
||||
}
|
||||
|
||||
const userjwt: authJwt = {
|
||||
id: user.id,
|
||||
role: user.role,
|
||||
};
|
||||
|
||||
req.headers.authorization = jwt.sign(userjwt, JWT_SECRET);
|
||||
|
||||
res.status(200).json(createDefaultSucces("Logged in succesfully",{}))
|
||||
};
|
||||
|
||||
export const verifyEmail = async (req: Request, res: Response) => {
|
||||
const { code } = req.body || {};
|
||||
|
||||
if (!(typeof code === "string")) {
|
||||
return res.status(400).json(
|
||||
createDefaultError("Request body does not match required parameters", {
|
||||
code: "string",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const acc: number | undefined = emailClient.get(code);
|
||||
|
||||
if (!acc) {
|
||||
return res.status(404).json(createDefaultError("The code is invalid", {}));
|
||||
}
|
||||
|
||||
const user = prisma.user.update({
|
||||
where: {
|
||||
id: acc,
|
||||
},
|
||||
data: {
|
||||
status: Status.VERIFIED,
|
||||
},
|
||||
});
|
||||
};
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import { authJwt } from "./controller/auth.controller";
|
||||
|
||||
declare module "express-serve-static-core" {
|
||||
interface Request {
|
||||
auth?: authJwt & { isAuthenthicated: boolean };
|
||||
}
|
||||
}
|
||||
+22
-2
@@ -1,12 +1,32 @@
|
||||
import express from "express";
|
||||
const app = express();
|
||||
import express, { NextFunction, Request, Response } from "express";
|
||||
import dotenv from "dotenv";
|
||||
|
||||
import adminRoutes from "./routes/auth.route";
|
||||
const ordersRoutes = require("./routes/orders.route");
|
||||
const organizationsRoutes = require("./routes/organisations.route");
|
||||
const pizzasRoutes = require("./routes/pizzas.route");
|
||||
const restaurantsRoutes = require("./routes/restaurants.route");
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
|
||||
// Bodyparser and urlencoded to parse post request bodies
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json());
|
||||
|
||||
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
|
||||
if (err) {
|
||||
res.status(400).send({
|
||||
type: "error",
|
||||
payload: "The body of your request did not contain valid data",
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
app.use("/auth", adminRoutes);
|
||||
app.use("/order", ordersRoutes);
|
||||
app.use("/organization", organizationsRoutes);
|
||||
app.use("/pizza", pizzasRoutes);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import Handlebars, { template } from "handlebars";
|
||||
import nodemailer from "nodemailer";
|
||||
import SMTPTransport from "nodemailer/lib/smtp-transport";
|
||||
|
||||
import mjml from "./mjml";
|
||||
|
||||
export let mailAccount = {
|
||||
user: process.env.MAILUSER + "@mail." + process.env.DOMAIN,
|
||||
pass: process.env.MAILPASSWORD || "password",
|
||||
};
|
||||
|
||||
let transporter =
|
||||
process.env.DEV == "true" || process.env.DOMAIN == undefined
|
||||
? (async () => {
|
||||
mailAccount = await nodemailer.createTestAccount();
|
||||
//mailAccount = {
|
||||
// user: "",
|
||||
// pass: "",
|
||||
//};
|
||||
if (process.env.NODE_ENV != "test") {
|
||||
console.log(mailAccount);
|
||||
}
|
||||
return nodemailer.createTransport({
|
||||
host: "smtp.ethereal.email",
|
||||
port: 587,
|
||||
secure: false, // true for 465, false for other ports
|
||||
auth: {
|
||||
user: mailAccount.user, // generated ethereal user
|
||||
pass: mailAccount.pass, // generated ethereal password
|
||||
},
|
||||
});
|
||||
})()
|
||||
: nodemailer.createTransport(
|
||||
new SMTPTransport({
|
||||
host: "localhost",
|
||||
port: 587,
|
||||
secure: false,
|
||||
auth: {
|
||||
user: mailAccount.user,
|
||||
pass: mailAccount.pass,
|
||||
},
|
||||
tls: {
|
||||
rejectUnauthorized: false,
|
||||
secureProtocol: "TLSv1_method",
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const sendMail = async (from: string, to: string, subject: string, text?: string, html?: string) => {
|
||||
return await (
|
||||
await transporter
|
||||
).sendMail({
|
||||
from: from,
|
||||
to: to,
|
||||
subject: subject,
|
||||
text: text,
|
||||
html: html,
|
||||
});
|
||||
};
|
||||
|
||||
export const verificationMail = async (to: string, id: string) => {
|
||||
const raw = mjml.getTemplate("verify");
|
||||
|
||||
//TODO: Replace other handlebars with final values
|
||||
const message = Handlebars.compile(raw);
|
||||
|
||||
const data = {};
|
||||
const compiled = message(data);
|
||||
|
||||
sendMail(mailAccount.user, to, "Verify Email", undefined, compiled);
|
||||
};
|
||||
|
||||
export default { sendMail };
|
||||
@@ -0,0 +1,33 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import mjml from "mjml";
|
||||
|
||||
const template_folder = __dirname + "/../../resources/email/templates/";
|
||||
|
||||
const compileTemplates = () => {
|
||||
console.log("Compiling templates: ");
|
||||
|
||||
fs.readdir(template_folder, (err, files) => {
|
||||
if (err) console.log(err);
|
||||
|
||||
files.forEach((file) => {
|
||||
if (path.extname(file) !== ".mjml") return;
|
||||
|
||||
let content = fs.readFileSync(template_folder + file);
|
||||
let mjmlres = mjml(content.toString());
|
||||
|
||||
let hbs = template_folder + file.replace(".mjml", ".hbs");
|
||||
fs.writeFileSync(hbs, mjmlres.html);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
compileTemplates(); // This will compile all templates when this file is first included
|
||||
|
||||
const getTemplate = (name: string): string => {
|
||||
let file = "";
|
||||
file = fs.readFileSync(path.join(template_folder, name + ".hbs")).toString();
|
||||
return file;
|
||||
};
|
||||
|
||||
export default { getTemplate };
|
||||
@@ -6,3 +6,4 @@ let prisma: PrismaClient;
|
||||
prisma = new PrismaClient();
|
||||
|
||||
export default prisma;
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import redis, { createClient } from "redis";
|
||||
import { promisify } from "util";
|
||||
|
||||
function createAsyncClient(client: redis.RedisClientType) {
|
||||
return {
|
||||
get: promisify(client.get).bind(client),
|
||||
set: promisify(client.set).bind(client),
|
||||
};
|
||||
}
|
||||
|
||||
/*----E-mail verify----*/
|
||||
|
||||
const email: redis.RedisClientType = createClient({
|
||||
url: "redis://localhost:6379",
|
||||
});
|
||||
|
||||
email.connect();
|
||||
|
||||
export const emailClient = createAsyncClient(email);
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
export const createDefaultError = (message: string, context: any) => ({
|
||||
"type": "error",
|
||||
"payload": {
|
||||
"message": message,
|
||||
"context": context,
|
||||
}
|
||||
})
|
||||
|
||||
export const createDefaultSucces = (message: string, context: any) => ({
|
||||
"type": "success",
|
||||
"payload": {
|
||||
"message": message,
|
||||
"context": context,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
/// <reference path="../custom.d.ts" />
|
||||
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import { createDefaultError } from "../lib/standardResponse";
|
||||
import jwt, { JwtPayload } from "jsonwebtoken";
|
||||
import { authJwt } from "../controller/auth.controller";
|
||||
import prisma from "../lib/prisma.lib";
|
||||
import { emailClient } from "../lib/redis.lib";
|
||||
|
||||
const verifyAuthorizationFormat = (authorization: string) => /^Bearer .+$/.test(authorization);
|
||||
|
||||
const getBearerToken = (authorization: string) => authorization.slice(7);
|
||||
|
||||
const JWT_SECRET = process.env.jwtsecret || "secret";
|
||||
|
||||
export const getAuthenthication = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { authorization } = req.headers;
|
||||
|
||||
if (!authorization) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!verifyAuthorizationFormat(authorization)) {
|
||||
return res.status(400).json(createDefaultError("Malformed Bearer Token", { format: "Bearer <token>" }));
|
||||
}
|
||||
|
||||
let payload_: string | JwtPayload;
|
||||
|
||||
try {
|
||||
payload_ = jwt.verify(getBearerToken(authorization), JWT_SECRET);
|
||||
} catch (e) {
|
||||
return res.status(403).json(createDefaultError("The Token could not be verified, it might be expiered", null));
|
||||
}
|
||||
|
||||
const payload = payload_ as authJwt;
|
||||
|
||||
const { id } = payload;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
req.auth = {
|
||||
isAuthenthicated: true,
|
||||
id,
|
||||
role: user?.role || "user",
|
||||
};
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
export const requireAuthentication = async (req: Request, res: Response, next: NextFunction) => {
|
||||
const { authorization } = req.headers;
|
||||
|
||||
if (!authorization) {
|
||||
return res.status(403).json(createDefaultError("The request did not contain a authorization header", null));
|
||||
}
|
||||
|
||||
if (!verifyAuthorizationFormat(authorization)) {
|
||||
return res.status(400).json(createDefaultError("Malformed Bearer Token", { format: "Bearer <token>" }));
|
||||
}
|
||||
|
||||
let payload_: string | JwtPayload;
|
||||
|
||||
try {
|
||||
payload_ = jwt.verify(getBearerToken(authorization), JWT_SECRET);
|
||||
} catch (e) {
|
||||
return res.status(403).json(createDefaultError("The Token could not be verified, it might be expiered", null));
|
||||
}
|
||||
|
||||
const payload = payload_ as authJwt;
|
||||
|
||||
const { id } = payload;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
req.auth = {
|
||||
isAuthenthicated: true,
|
||||
id,
|
||||
role: user?.role || "USER",
|
||||
};
|
||||
|
||||
next();
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Router } from "express";
|
||||
import { authenthicate, register } from "../controller/auth.controller";
|
||||
import { getAuthenthication } from "../middleware/auth.middle";
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post("/register", getAuthenthication, register);
|
||||
router.post("/authenthicate",authenthicate);
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user