diff --git a/common/src/errors.ts b/common/src/errors.ts index 0d60d13..7bdb4c1 100644 --- a/common/src/errors.ts +++ b/common/src/errors.ts @@ -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. @@ -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 || diff --git a/common/src/middleware.ts b/common/src/middleware.ts index 63f2594..e96c162 100644 --- a/common/src/middleware.ts +++ b/common/src/middleware.ts @@ -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"; @@ -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.")); }); /** @@ -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,