Skip to content

Commit

Permalink
Fixed events key being wrong size (#45)
Browse files Browse the repository at this point in the history
* Fixed events key being wrong size
* Removed arrow functions
  • Loading branch information
AydanPirani committed Sep 27, 2023
1 parent b682ddb commit 18bcaf0
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 150 deletions.
3 changes: 2 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ abstract class Constants {

// Constants for general usage
static readonly ZERO: number = 0;
static readonly EVENT_ID_LENGTH: number = 16;
static readonly EVENT_ID_BYTES: number = 16;
static readonly EVENT_ID_LENGTH: number = 32;
static readonly MILLISECONDS_PER_SECOND:number = 1000;

// Constants for database names
Expand Down
45 changes: 19 additions & 26 deletions src/services/auth/auth-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,16 @@ export async function getJwtPayloadFromProfile(provider: string, data: ProfileDa
};

// Get roles, and assign those to payload.roles if they exist
await getRoles(userId).then((userRoles: Role[]) => {
if (userRoles.length) {
payload.roles = userRoles;
try {
let roles: Role[] = await getRoles(userId);

// If roles don't exist already - initialize them for the user, and return the new set of roles
if (!roles.length) {
roles = await initializeRoles(userId, provider.toUpperCase() as Provider, email);
}
}).catch((error: string) => {
payload.roles = roles;
} catch (error) {
console.error(error);
});

// No roles found for user -> initialize them
if (!payload.roles.length) {
await initializeRoles(userId, provider.toUpperCase() as Provider, email).then((newRoles: Role[]) => {
payload.roles = newRoles;
}).catch((error: string) => {
console.error(error);
});
}

return payload;
Expand All @@ -91,23 +86,23 @@ export async function getJwtPayloadFromProfile(provider: string, data: ProfileDa
* @returns Promise, containing either JWT payload or reason for failure
*/
export async function getJwtPayloadFromDB(targetUser: string): Promise<JwtPayload> {

let authInfo: RolesSchema | undefined;
let userInfo: UserSchema | undefined;

// Fill in auth info, used for provider and roles
await getAuthInfo(targetUser).then((info: RolesSchema) => {
authInfo = info;
}).catch((error: string) => {
console.error(error);
});

// Fill in user info, used for email
await getUser(targetUser).then((info: UserSchema) => {
userInfo = info;
}).catch((error: string) => {
console.error(error);
});


try {
authInfo = await getAuthInfo(targetUser);
userInfo = await getUser(targetUser);


} catch (error) {
console.error(error);
}

// If either one does not exist, the info doesn't exist in the database. Throw error
if (!authInfo || !userInfo) {
return Promise.reject("UserNotFound");
Expand All @@ -120,11 +115,9 @@ export async function getJwtPayloadFromDB(targetUser: string): Promise<JwtPayloa
email: userInfo.email,
provider: authInfo.provider,
};

return newPayload;
}


/**
* Create the token, assign an expiry date, and sign it
* @param payload JWT payload to be included in the token
Expand Down
111 changes: 54 additions & 57 deletions src/services/auth/auth-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,9 @@ authRouter.get("/login/github/", (req: Request, res: Response, next: NextFunctio
const device: string = req.query.device as string | undefined ?? Constants.DEFAULT_DEVICE;

if (device && !Constants.REDIRECT_MAPPINGS.has(device)) {
res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
return;
return res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
}
SelectAuthProvider("github", device)(req, res, next);
return SelectAuthProvider("github", device)(req, res, next);
});

/**
Expand All @@ -99,10 +98,9 @@ authRouter.get("/login/google/", (req: Request, res: Response, next: NextFunctio
const device: string = req.query.device as string | undefined ?? Constants.DEFAULT_DEVICE;

if (device && !Constants.REDIRECT_MAPPINGS.has(device)) {
res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
return;
return res.status(Constants.BAD_REQUEST).send({ error: "BadDevice" });
}
SelectAuthProvider("google", device)(req, res, next);
return SelectAuthProvider("google", device)(req, res, next);
});


Expand All @@ -117,29 +115,29 @@ authRouter.get("/:PROVIDER/callback/:DEVICE", (req: Request, res: Response, next
}
}, async (req: Request, res: Response) => {
if (!req.isAuthenticated()) {
res.status(Constants.UNAUTHORIZED_REQUEST).send({ error: "FailedAuth" });
return res.status(Constants.UNAUTHORIZED_REQUEST).send({ error: "FailedAuth" });
}

const device: string = (res.locals.device ?? Constants.DEFAULT_DEVICE) as string;
const user: GithubProfile | GoogleProfile = req.user as GithubProfile | GoogleProfile;
const data: ProfileData = user._json as ProfileData;
const redirect: string = (Constants.REDIRECT_MAPPINGS.get(device) ?? Constants.DEFAULT_REDIRECT);

data.id = data.id ?? user.id;
let payload: JwtPayload | undefined = undefined;

// Load in the payload with the actual values stored in the database
await getJwtPayloadFromProfile(user.provider, data).then((parsedPayload: JwtPayload) => {
payload = parsedPayload;
}).catch((error: Error) => {
try {
// Load in the payload with the actual values stored in the database
const payload: JwtPayload = await getJwtPayloadFromProfile(user.provider, data);

// Generate the token, and return it
const token: string = generateJwtToken(payload);
const url: string = `${redirect}?token=${token}`;
return res.redirect(url);
} catch (error) {
console.error(error);
res.status(Constants.BAD_REQUEST).send({ error: "InvalidData" });
});
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidData" });
}

// Generate the token, and return it
const token: string = generateJwtToken(payload);
const redirect: string = (Constants.REDIRECT_MAPPINGS.get(device) ?? Constants.DEFAULT_REDIRECT);
const url: string = `${redirect}?token=${token}`;
res.redirect(url);
});


Expand Down Expand Up @@ -168,26 +166,24 @@ authRouter.get("/roles/:USERID", strongJwtVerification, async (req: Request, res

// Check if we have a user to get roles for - if not, get roles for current user
if (!targetUser) {
res.redirect("/auth/roles/");
return;
return res.redirect("/auth/roles/");
}

const payload: JwtPayload = res.locals.payload as JwtPayload;

// Cases: Target user already logged in, auth user is admin
if (payload.id == targetUser) {
res.status(Constants.SUCCESS).send({ id: payload.id, roles: payload.roles });
return res.status(Constants.SUCCESS).send({ id: payload.id, roles: payload.roles });
} else if (hasElevatedPerms(payload)) {
let roles: Role[] = [];
await getRoles(targetUser).then((targetRoles: Role[]) => {
roles = targetRoles;
res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
}).catch((error: Error) => {
try {
const roles: Role[] = await getRoles(targetUser);
return res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
} catch (error) {
console.error(error);
res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
});
return res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
}
} else {
res.status(Constants.FORBIDDEN).send("Forbidden");
return res.status(Constants.FORBIDDEN).send("Forbidden");
}
});

Expand Down Expand Up @@ -218,39 +214,39 @@ authRouter.put("/roles/:OPERATION/", strongJwtVerification, async (req: Request,

// Not authenticated with modify roles perms
if (!hasElevatedPerms(payload)) {
res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
return res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
}

// Parse to get operation type
const op: RoleOperation | undefined = RoleOperation[req.params.operation as keyof typeof RoleOperation];

// No operation - fail out
if (!op) {
res.status(Constants.BAD_REQUEST).send({ error: "InvalidOperation" });
return;
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidOperation" });
}

// Check if role to add/remove actually exists
const data: ModifyRoleRequest = req.body as ModifyRoleRequest;
const role: Role | undefined = Role[data.role.toUpperCase() as keyof typeof Role];
if (!role) {
res.status(Constants.BAD_REQUEST).send({ error: "InvalidRole" });
return;
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidRole" });
}

// Try to update roles, if possible
await updateRoles(data.id, role, op).catch((error: string) => {
try {
await updateRoles(data.id, role, op);
} catch (error) {
console.error(error);
res.status(Constants.INTERNAL_ERROR).send({ error: "InternalError" });
});
return res.status(Constants.INTERNAL_ERROR).send({ error: "InternalError" });
}

// Get new roles for the current user, and return them
await getRoles(data.id).then((roles: Role[]) => {
res.status(Constants.SUCCESS).send({ id: data.id, roles: roles });
}).catch((error: string) => {
try {
const roles: Role[] = await getRoles(data.id);
return res.status(Constants.SUCCESS).send({ id: data.id, roles: roles });
} catch (error) {
console.error(error);
res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
});
return res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
}
});


Expand All @@ -276,16 +272,15 @@ authRouter.get("/list/roles/", strongJwtVerification, (_: Request, res: Response

// Check if current user should be able to access all roles
if (!hasElevatedPerms(payload)) {
res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
return;
return res.status(Constants.FORBIDDEN).send({ error: "Forbidden" });
}

// Filter enum to get all possible string keys
const roles: string[] = Object.keys(Role).filter((item: string) => {
return isNaN(Number(item));
});

res.status(Constants.SUCCESS).send({ roles: roles });
return res.status(Constants.SUCCESS).send({ roles: roles });
});


Expand All @@ -310,10 +305,10 @@ authRouter.get("/roles/", strongJwtVerification, async (_: Request, res: Respons
const targetUser: string = payload.id;

await getRoles(targetUser).then((roles: Role[]) => {
res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
return res.status(Constants.SUCCESS).send({ id: targetUser, roles: roles });
}).catch((error: Error) => {
console.error(error);
res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
return res.status(Constants.BAD_REQUEST).send({ error: "UserNotFound" });
});
});

Expand All @@ -339,15 +334,17 @@ authRouter.get("/token/refresh", strongJwtVerification, async (_: Request, res:
email: oldPayload.email,
};

// Generate a new payload for the token
let newPayload: JwtPayload | undefined;
await getJwtPayloadFromProfile(oldPayload.provider, data).then((payload: JwtPayload) => {
newPayload = payload;
});
try {
// Generate a new payload for the token
const newPayload: JwtPayload = await getJwtPayloadFromProfile(oldPayload.provider, data);

// Create and return a new token with the payload
const newToken: string = generateJwtToken(newPayload);
res.status(Constants.SUCCESS).send({ token: newToken });
// Create and return a new token with the payload
const newToken: string = generateJwtToken(newPayload);
return res.status(Constants.SUCCESS).send({ token: newToken });
} catch (error) {
console.error(error);
return res.status(Constants.INTERNAL_ERROR).send({ error: "InternalError" });
}
});


Expand Down
1 change: 0 additions & 1 deletion src/services/event/event-formats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ export function isEventFormat(obj: EventFormat): boolean {
}
}


if (
typeof obj.sponsor !== "string" ||
typeof obj.eventType !== "string" ||
Expand Down
2 changes: 1 addition & 1 deletion src/services/event/event-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ eventsRouter.post("/", strongJwtVerification, async (req: Request, res: Response

// Verify that the input format is valid to create a new event or update it
const eventFormat: EventFormat = req.body as EventFormat;
eventFormat.id = crypto.randomBytes(Constants.EVENT_ID_LENGTH).toString("hex");
eventFormat.id = crypto.randomBytes(Constants.EVENT_ID_BYTES).toString("hex");
if (!isEventFormat(eventFormat)) {
return res.status(Constants.BAD_REQUEST).send({ error: "InvalidParams" });
}
Expand Down
36 changes: 0 additions & 36 deletions src/services/newsletter/newsletter-lib.ts

This file was deleted.

0 comments on commit 18bcaf0

Please sign in to comment.