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

fix login #12

Merged
merged 7 commits into from
Feb 28, 2024
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
},
"dependencies": {
"@carbon/react": "^1.12.0",
"css-loader": "^6.10.0",
"lodash-es": "^4.17.21"
},
"files": [
Expand All @@ -60,7 +61,6 @@
},
"devDependencies": {
"@openmrs/esm-framework": "next",
"@openmrs/webpack-config": "^5.1.0",
"@swc/cli": "^0.1.62",
"@swc/core": "^1.3.78",
"@swc/jest": "^0.2.29",
Expand Down
21 changes: 21 additions & 0 deletions src/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,24 @@ export const configSchema = {
},
},
};

export interface ConfigSchema {
provider: {
type: string;
loginUrl: string;
logoutUrl: string;
};
chooseLocation: {
enabled: boolean;
numberToShow: number;
locationsPerRequest: number;
useLoginLocationTag: boolean;
};
links: {
loginSuccess: string;
};
logo: {
src: string;
alt: string;
};
}
23 changes: 4 additions & 19 deletions src/login.resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import {
FetchResponse,
fhirBaseUrl,
openmrsFetch,
restBaseUrl,
setSessionLocation,
showNotification,
} from "@openmrs/esm-framework";
import {
hasAttribute,
SessionResponse,
type LocationEntry,
type LocationResponse,
type ProviderResponse,
Expand All @@ -33,30 +33,15 @@ async function logoutIfNoCredentials(
}

export async function performLogin(
uuid: string,
username: string,
password: string
): Promise<void> {
const abortController = new AbortController();
const token = window.btoa(`${username}:${password}`);
const sessionUrl = `/ws/rest/v1/session`;
const sessionUrl = `${restBaseUrl}/session`;

const loginResponse: FetchResponse<SessionResponse> = await openmrsFetch(
sessionUrl,
{
headers: {
Authorization: `Basic ${token}`,
},
signal: abortController.signal,
}
);

if (!loginResponse.data?.user?.uuid) {
throw new Error("Invalid Credentials");
}

// console.log(loginResponse);

const providerUrl = `/ws/rest/v1/provider?user=${loginResponse.data?.user?.uuid}&v=custom:(uuid,attributes:(uuid,attributeType:(uuid,display),value:(uuid,name)))`;
const providerUrl = `${restBaseUrl}/provider?user=${uuid}&v=custom:(uuid,attributes:(uuid,attributeType:(uuid,display),value:(uuid,name)))`;

const providerResponse: FetchResponse<ProviderResponse> = await openmrsFetch(
providerUrl,
Expand Down
91 changes: 45 additions & 46 deletions src/login/login.component.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { type To, useLocation, useNavigate } from "react-router-dom";
import {
Button,
InlineLoading,
Expand All @@ -10,31 +10,41 @@
} from "@carbon/react";
import { ArrowRight } from "@carbon/react/icons";
import { useTranslation } from "react-i18next";

import Logo from "./logo.component";
import styles from "./login.scss";
import { ConfigSchema } from "../config-schema";
import {
clearCurrentUser,
getSessionStore,
interpolateUrl,
navigate,
refetchCurrentUser,
useConfig,
useConnectivity,
useSession,
refetchCurrentUser,
navigate as openmrsNavigate,

Check warning on line 22 in src/login/login.component.tsx

View workflow job for this annotation

GitHub Actions / build

'openmrsNavigate' is defined but never used
clearCurrentUser,
getSessionStore,
} from "@openmrs/esm-framework";
import { performLogin } from "../login.resource";
import Logo from "./logo.component";
import styles from "./login.scss";

export interface LoginReferrer {
referrer?: string;
}

const Login: React.FC<LoginReferrer> = () => {
const config = useConfig();
const { provider: loginProvider, links: loginLinks } =
useConfig<ConfigSchema>();
const isLoginEnabled = useConnectivity();
const { t } = useTranslation();
const { user } = useSession();
const location = useLocation();
const nav = useNavigate();
const location = useLocation() as unknown as Omit<Location, "state"> & {
state: LoginReferrer;
};

const rawNavigate = useNavigate();
const navigate = useCallback(
(to: To) => {
rawNavigate(to, { state: location.state });
},
[rawNavigate, location.state]
);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
Expand All @@ -48,22 +58,18 @@
clearCurrentUser();
refetchCurrentUser().then(() => {
const authenticated =
getSessionStore().getState().session.authenticated;
if (authenticated) {
nav("/home", { state: location.state });
getSessionStore()?.getState()?.session?.authenticated;
if (
authenticated &&
getSessionStore()?.getState()?.session?.sessionLocation?.uuid !== null
) {
navigate("/home");
}
});
} else if (!username && location.pathname === "/login/confirm") {
nav("/login", { state: location.state });
}
}, [username, nav, location, user]);

useEffect(() => {
if (!user && config.provider.type === "oauth2") {
const loginUrl = config.provider.loginUrl;
window.location.href = loginUrl;
} else if (!username && location?.pathname === "/login/confirm") {
navigate("/login");
}
}, [config, user]);
}, [username, navigate, location, user]);

const changeUsername = useCallback(
(evt: React.ChangeEvent<HTMLInputElement>) => setUsername(evt.target.value),
Expand All @@ -87,8 +93,10 @@

try {
setIsLoggingIn(true);
await performLogin(username, password);
navigate({ to: config.links.loginSuccess });
const sessionStore = await refetchCurrentUser(username, password);
const session = sessionStore?.session;
await performLogin(session.user?.uuid, username, password);
navigate(loginLinks.loginSuccess);
} catch (error) {
setErrorMessage(error.message);
resetUserNameAndPassword();
Expand All @@ -99,23 +107,16 @@
return false;
},

[username, password, config.links.loginSuccess, resetUserNameAndPassword]
[
username,
password,
navigate,
loginLinks.loginSuccess,
resetUserNameAndPassword,
]
);

const logo = config.logo.src ? (
<img
src={interpolateUrl(config.logo.src)}
alt={config.logo.alt}
className={styles["logo-img"]}
/>
) : (
<svg role="img" className={styles["logo"]}>
<title>OpenMRS logo</title>
<use xlinkHref="#omrs-logo-full-color"></use>
</svg>
);

if (config.provider.type === "basic") {
if (!loginProvider || loginProvider?.type === "basic") {
return (
<div className={`canvas ${styles["container"]}`}>
<div className={styles.section}>
Expand Down Expand Up @@ -184,7 +185,7 @@
description={t("loggingIn", "Logging in") + "..."}
/>
) : (
<span>{t("login", "Log in")}</span>
<span>Log in</span>
)}
</Button>
</div>
Expand All @@ -207,9 +208,7 @@
support
</span>
<div className={styles.attribution}>
<span className={styles["powered-by-txt"]}>
{t("poweredBy", "Powered by")}
</span>
<span className={styles["powered-by-txt"]}>Powered by</span>
<svg role="img" className={styles["powered-by-logo"]}>
<use xlinkHref="#omrs-logo-partial-mono"></use>
</svg>
Expand Down
Loading
Loading