Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes redirect on login (#6900) #6911

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions cypress/e2e/auth_spec/redirect.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/// <reference types="cypress" />

import { cy, describe, it, beforeEach, Cypress } from "local-cypress";
import LoginPage from "../../pageobject/Login/LoginPage";

Om-Thorat marked this conversation as resolved.
Show resolved Hide resolved
describe("redirect", () => {
const loginPage = new LoginPage();

beforeEach(() => {
cy.log("Logging in the user devdistrictadmin");
});

it("Check if login redirects to the right url", () => {
cy.awaitUrl("/resource/board", true);
loginPage.loginManuallyAsDistrictAdmin();
loginPage.CheckIfLoggedIn();
cy.url().should("include", "/resource/board");
});

it("Check if the redirect param works", () => {
const baseUrl = Cypress.config("baseUrl");
cy.awaitUrl(`login?redirect=${baseUrl}/resource/board`, true);
loginPage.loginManuallyAsDistrictAdmin();
loginPage.CheckIfLoggedIn();
cy.url().should("include", "/resource/board");
});

it("Check to ensure that redirect is the same origin", () => {
cy.awaitUrl("login?redirect=https://google.com", true);
loginPage.loginManuallyAsDistrictAdmin();
loginPage.CheckIfLoggedIn();
cy.url().should("include", "/facility");
});
});
14 changes: 14 additions & 0 deletions cypress/pageobject/Login/LoginPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,23 @@ class LoginPage {
cy.loginByApi("devdoctor", "Coronasafe@123");
}

loginAsStaff(): void {
cy.loginByApi("staffdev", "Coronasafe@123");
}

loginManuallyAsDistrictAdmin(): void {
cy.get("input[id='username']").type("devdistrictadmin");
cy.get("input[id='password']").type("Coronasafe@123");
cy.get("button").contains("Login").click();
}

login(username: string, password: string): void {
cy.loginByApi(username, password);
}

CheckIfLoggedIn(): void {
cy.get("p").contains("Sign Out").should("exist");
}
}

export default LoginPage;
2 changes: 1 addition & 1 deletion src/Common/hooks/useAuthUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ type SignInReturnType = RequestResult<JwtTokenObtainPair>;
type AuthContextType = {
user: UserModel | undefined;
signIn: (creds: LoginCredentials) => Promise<SignInReturnType>;
signOut: () => Promise<void>;
signOut: (noRedirect?: boolean) => Promise<void>;
};

export const AuthUserContext = createContext<AuthContextType | null>(null);
Expand Down
7 changes: 5 additions & 2 deletions src/Components/Common/Sidebar/SidebarUserCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ const SidebarUserCard = ({ shrinked }: { shrinked: boolean }) => {
<Link href="/user/profile" className="flex-none py-3">
<CareIcon className="care-l-user-circle text-3xl text-white" />
</Link>
<div className="flex cursor-pointer justify-center" onClick={signOut}>
<div
className="flex cursor-pointer justify-center"
onClick={() => signOut(true)}
>
<CareIcon
className={`care-l-sign-out-alt text-2xl text-gray-400 ${
shrinked ? "visible" : "hidden"
Expand All @@ -41,7 +44,7 @@ const SidebarUserCard = ({ shrinked }: { shrinked: boolean }) => {
</div>
<div
className="min-h-6 flex cursor-pointer items-center"
onClick={signOut}
onClick={() => signOut(true)}
>
<CareIcon
className={`care-l-sign-out-alt ${
Expand Down
37 changes: 23 additions & 14 deletions src/Providers/AuthUserProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,30 @@ export default function AuthUserProvider({ children, unauthorized }: Props) {
localStorage.setItem(LocalStorageKeys.refreshToken, query.data.refresh);

await refetch();
navigate(getRedirectOr("/"));
navigate(getRedirectOr(location.pathname));
}

return query;
},
[refetch]
);

const signOut = useCallback(async () => {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);

await refetch();

const redirectURL = getRedirectURL();
navigate(redirectURL ? `/?redirect=${redirectURL}` : "/");
}, [refetch]);
const signOut = useCallback(
async (noRedirect = false) => {
localStorage.removeItem(LocalStorageKeys.accessToken);
localStorage.removeItem(LocalStorageKeys.refreshToken);

await refetch();
navigate(
getRedirectOr(
noRedirect
? "/login"
: `/login?redirect=${encodeURIComponent(location.href)}`
)
);
},
[refetch]
);

// Handles signout from current tab, if signed out from another tab.
useEffect(() => {
Expand Down Expand Up @@ -118,18 +125,20 @@ const getRedirectURL = () => {

const getRedirectOr = (fallback: string) => {
const url = getRedirectURL();

const reserverdURLS = ["/login", "/session-expired"];
if (reserverdURLS.includes(fallback)) {
fallback = "/";
}
if (url) {
try {
const redirect = new URL(url);
const redirect = new URL(decodeURIComponent(url));
if (window.location.origin === redirect.origin) {
return redirect.pathname + redirect.search;
return redirect.href;
}
console.error("Redirect does not belong to same origin.");
} catch {
console.error(`Invalid redirect URL: ${url}`);
}
}

return fallback;
};