Skip to content

Commit

Permalink
Keep original error in AuthorizationError#cause (#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiodxa committed Nov 25, 2022
1 parent c36ea94 commit 311f892
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
6 changes: 5 additions & 1 deletion src/error.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export class AuthorizationError extends Error {}
export class AuthorizationError extends Error {
constructor(message?: string, public cause?: Error) {
super(message);
}
}
5 changes: 3 additions & 2 deletions src/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,12 @@ export abstract class Strategy<User, VerifyOptions> {
message: string,
request: Request,
sessionStorage: SessionStorage,
options: AuthenticateOptions
options: AuthenticateOptions,
cause?: Error
): Promise<never> {
// if a failureRedirect is not set, we throw a 401 Response or an error
if (!options.failureRedirect) {
if (options.throwOnError) throw new AuthorizationError(message);
if (options.throwOnError) throw new AuthorizationError(message, cause);
throw json<{ message: string }>({ message }, 401);
}

Expand Down
32 changes: 30 additions & 2 deletions test/authenticator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import {
redirect,
SessionStorage,
} from "@remix-run/server-runtime";
import { AuthenticateOptions, Authenticator, Strategy } from "../src";
import {
AuthenticateOptions,
Authenticator,
AuthorizationError,
Strategy,
} from "../src";

class MockStrategy<User> extends Strategy<User, Record<string, never>> {
name = "mock";
Expand All @@ -19,7 +24,8 @@ class MockStrategy<User> extends Strategy<User, Record<string, never>> {
"Invalid credentials",
request,
sessionStorage,
options
options,
new Error("Invalid credentials")
);
}
}
Expand Down Expand Up @@ -90,6 +96,7 @@ describe(Authenticator, () => {
expect(strategy).toBe("mock");
}
});

test("should store the provided strategy name in the session", async () => {
let user = { id: "123" };
let session = await sessionStorage.getSession();
Expand Down Expand Up @@ -190,4 +197,25 @@ describe(Authenticator, () => {
).rejects.toEqual(response);
});
});

describe("authenticate", () => {
test("should throw an error if throwOnError is enabled", async () => {
let request = new Request("/");
let authenticator = new Authenticator(sessionStorage);

authenticator.use(new MockStrategy(async () => null));

let error = await authenticator
.authenticate("mock", request, {
throwOnError: true,
})
.catch((error) => error);

expect(error).toEqual(new AuthorizationError("Invalid credentials"));

expect((error as AuthorizationError).cause).toEqual(
new TypeError("Invalid credentials")
);
});
});
});

0 comments on commit 311f892

Please sign in to comment.