Remove testroutes; Update register endpoint; Add Redis lib

This commit is contained in:
Stefan-5422
2022-03-30 12:21:02 +02:00
parent 71e3a3c941
commit 8f9a8ebdea
9 changed files with 366 additions and 6 deletions
+46 -4
View File
@@ -1,9 +1,13 @@
import express from "express";
import { Request, Response } from "express";
import prisma from "../lib/prisma.lib";
import { Role } from "@prisma/client";
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";
const JWT_SECRET = process.env.jwtsecret || "secret";
interface registerBody {
name: string;
@@ -22,8 +26,6 @@ const ROLES: readonly string[] = [Role.ADMIN, Role.USER];
export const register = async (req: Request, res: Response) => {
const { name, password, role, organization } = req.body || {};
console.log(name);
if (
!(
typeof name === "string" &&
@@ -36,7 +38,6 @@ export const register = async (req: Request, res: Response) => {
createDefaultError("Request body does not match required parameters", {
name: "string",
password: "string",
role: "USER | ADMIN",
organization: "int",
})
);
@@ -48,12 +49,19 @@ export const register = async (req: Request, res: Response) => {
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: {
@@ -63,5 +71,39 @@ export const register = async (req: Request, res: Response) => {
},
});
(await emailClient).set(name, "salty");
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");
const user = await prisma.user.findUnique({ where: { email: name } });
if (!user) {
return res.status(403).json(createDefaultError("Username or Password wrong", {}));
}
if (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);
};
+17
View File
@@ -0,0 +1,17 @@
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",
});
export const emailClient = createAsyncClient(email);
+44 -1
View File
@@ -1,8 +1,11 @@
/// <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);
@@ -10,6 +13,46 @@ 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;
@@ -43,7 +86,7 @@ export const requireAuthentication = async (req: Request, res: Response, next: N
req.auth = {
isAuthenthicated: true,
id,
role: user?.role || "user",
role: user?.role || "USER",
};
next();
+2 -1
View File
@@ -1,8 +1,9 @@
import { Router } from "express";
import { register } from "../controller/auth.controller";
import { getAuthenthication } from "../middleware/auth.middle";
const router = Router();
router.post("/register", register);
router.post("/register", getAuthenthication, register);
export default router;
View File