Skip to content

Commit

Permalink
Added linting
Browse files Browse the repository at this point in the history
  • Loading branch information
AydanPirani committed Apr 11, 2024
1 parent 5888d71 commit dc4b9c8
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 25 deletions.
2 changes: 1 addition & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@ export const Config = {

export const DeviceRedirects: Record<string, string> = {
web: "https://www.google.com/",
dev: "http://127.0.0.1:3000/auth/dev/"
dev: "http://127.0.0.1:3000/auth/dev/",
};
26 changes: 15 additions & 11 deletions src/middleware/role-checker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { NextFunction, Request, Response } from "express";
import { JwtPayload, Role } from "../services/auth/auth-models";
import {z} from "zod";
import { z } from "zod";
import jsonwebtoken from "jsonwebtoken";
import { Config } from "../config";
import { StatusCodes } from "http-status-codes";


export default function RoleChecker (requiredRoles: z.infer<typeof Role>[], weakVerification: boolean = false){
export default function RoleChecker(
requiredRoles: z.infer<typeof Role>[],
weakVerification: boolean = false
) {
return function (req: Request, res: Response, next: NextFunction) {
const jwt = req.headers.authorization;

Expand All @@ -15,12 +17,15 @@ export default function RoleChecker (requiredRoles: z.infer<typeof Role>[], weak
next();
}

return res.status(StatusCodes.BAD_REQUEST).json({error: "NoJWT"})
return res.status(StatusCodes.BAD_REQUEST).json({ error: "NoJWT" });
}

try {
console.log("in");
const payloadData = jsonwebtoken.verify(jwt, Config.JWT_SIGNING_SECRET);
const payloadData = jsonwebtoken.verify(
jwt,
Config.JWT_SIGNING_SECRET
);
const payload = JwtPayload.parse(payloadData);
res.locals.payload = payload;

Expand All @@ -30,7 +35,7 @@ export default function RoleChecker (requiredRoles: z.infer<typeof Role>[], weak
if (weakVerification) {
next();
}

if (requiredRoles.length == 0) {
next();
}
Expand All @@ -55,9 +60,8 @@ export default function RoleChecker (requiredRoles: z.infer<typeof Role>[], weak
}

throw error;

} catch (error) {
next(error)
next(error);
}
}
}
};
}
4 changes: 2 additions & 2 deletions src/services/auth/auth-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { z } from "zod";

export const Role = z.enum(["USER", "ADMIN", "CORPORATE"]);

export const JwtPayload = z.object({
export const JwtPayload = z.object({
userId: z.string(),
roles: Role.array(),
})
});
19 changes: 13 additions & 6 deletions src/services/auth/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,23 @@ authRouter.get(
async function (req, res, next) {
// Authentication failed - redirect to login
if (req.user == undefined) {
return res.redirect(`/auth/login/${req.params.DEVICE}`)
return res.redirect(`/auth/login/${req.params.DEVICE}`);
}
const userData = req.user as Profile;
const userId = `user${userData.id}`;

// Generate the JWT, and redirect to JWT initialization
try {
const jwtPayload = (await getJwtPayloadFromDatabase(userId)).toObject();
const token = jsonwebtoken.sign(jwtPayload, Config.JWT_SIGNING_SECRET, { expiresIn: Config.JWT_EXPIRATION_TIME });
const redirectUri = DeviceRedirects[req.params.DEVICE] + `?token=${token}`;
const jwtPayload = (
await getJwtPayloadFromDatabase(userId)
).toObject();
const token = jsonwebtoken.sign(
jwtPayload,
Config.JWT_SIGNING_SECRET,
{ expiresIn: Config.JWT_EXPIRATION_TIME }
);
const redirectUri =
DeviceRedirects[req.params.DEVICE] + `?token=${token}`;
return res.redirect(redirectUri);
} catch (error) {
next(error);
Expand All @@ -61,6 +68,6 @@ authRouter.get(

authRouter.get("/dev/", (req, res) => {
return res.status(StatusCodes.OK).json(req.query);
})
});

export default authRouter;
1 change: 0 additions & 1 deletion src/services/auth/auth-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Schema } from "mongoose";
import { z } from "zod";
import { Role } from "./auth-models";


export const RoleValidator = z.object({
userId: z.coerce.string().regex(/user[0-9]*/),
name: z.coerce.string(),
Expand Down
10 changes: 6 additions & 4 deletions src/services/auth/auth-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ export function createGoogleStrategy(device: string) {
);
}


export async function getJwtPayloadFromDatabase(userId: string) {
const payload = await Database.ROLES.findOne({userId: userId}).select(["userId", "roles"]);
const payload = await Database.ROLES.findOne({ userId: userId }).select([
"userId",
"roles",
]);
if (!payload) {
throw new Error("NoUserFound");
}

return payload;
}
}

0 comments on commit dc4b9c8

Please sign in to comment.