Skip to content

Commit

Permalink
created new UnauthorizedError with correct error code
Browse files Browse the repository at this point in the history
  • Loading branch information
reesewang25 committed Apr 15, 2024
1 parent 162dc42 commit 86dca02
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions common/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export class BadRequestError extends Error {}
*/
export class ForbiddenError extends Error {}

/**
* This error is thrown when no user is logged in.
*/
export class UnauthorizedError extends Error {}

/**
* This error is thrown when the server's config is not setup properly. This
* shows that the server config needs to be updated.
Expand Down Expand Up @@ -66,6 +71,7 @@ export const shouldHandleError = (err: any): boolean => {
if (
err instanceof BadRequestError ||
err instanceof ForbiddenError ||
err instanceof UnauthorizedError ||
err instanceof mongoose.Error.CastError ||
err instanceof mongoose.Error.ValidationError ||
err instanceof mongoose.Error.ValidatorError ||
Expand Down
18 changes: 16 additions & 2 deletions common/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ import axios from "axios";
import { Subject } from "@casl/ability";
import { OAuth2Client } from "google-auth-library";

import { ApiCallError, BadRequestError, ConfigError, ForbiddenError, ServerError } from "./errors";
import {
ApiCallError,
BadRequestError,
ConfigError,
ForbiddenError,
ServerError,
UnauthorizedError,
} from "./errors";
import { AbilityAction, DEFAULT_USER_ROLES, User, UserRoles } from "./types";
import { apiCall } from "./apiCall";

Expand Down Expand Up @@ -131,7 +138,7 @@ export const isAuthenticated: RequestHandler = asyncHandler(async (req, res, nex
throw req.userError;
}

next(new ForbiddenError("User is not authenticated. Please authenticate and try again."));
next(new UnauthorizedError("User is not authenticated. Please authenticate and try again."));
});

/**
Expand Down Expand Up @@ -218,6 +225,13 @@ export const handleError: ErrorRequestHandler = (err, req, res, next) => {
message: err.message,
stack: err.stack,
});
} else if (err instanceof UnauthorizedError) {
res.status(StatusCodes.UNAUTHORIZED).json({
status: StatusCodes.UNAUTHORIZED,
type: "user_error",
message: err.message,
stack: err.stack,
});
} else if (err instanceof ConfigError) {
res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
status: StatusCodes.INTERNAL_SERVER_ERROR,
Expand Down

0 comments on commit 86dca02

Please sign in to comment.