Skip to content

Commit

Permalink
fix login bug
Browse files Browse the repository at this point in the history
  • Loading branch information
jabahum committed Feb 28, 2024
1 parent 41a871f commit 8f17406
Show file tree
Hide file tree
Showing 5 changed files with 3,994 additions and 2,663 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"main": "src/index.ts",
"source": true,
"scripts": {
"start": "openmrs develop",
"start": "openmrs develop --backend http://194.163.171.253:8282",
"serve": "webpack serve --mode=development",
"debug": "npm run serve",
"test": "cross-env TZ=UTC jest --config jest.config.js --verbose false --passWithNoTests",
Expand Down 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;
};
}
19 changes: 2 additions & 17 deletions src/login.resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 = `/ws/rest/v1/provider?user=${uuid}&v=custom:(uuid,attributes:(uuid,attributeType:(uuid,display),value:(uuid,name)))`;

const providerResponse: FetchResponse<ProviderResponse> = await openmrsFetch(
providerUrl,
Expand Down
87 changes: 43 additions & 44 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 @@ import {
} 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 @@ -49,21 +59,17 @@ const Login: React.FC<LoginReferrer> = () => {
refetchCurrentUser().then(() => {
const authenticated =
getSessionStore().getState().session.authenticated;
if (authenticated) {
nav("/home", { state: location.state });
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;
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 @@ const Login: React.FC<LoginReferrer> = () => {

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 @@ const Login: React.FC<LoginReferrer> = () => {
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 @@ const Login: React.FC<LoginReferrer> = () => {
description={t("loggingIn", "Logging in") + "..."}
/>
) : (
<span>{t("login", "Log in")}</span>
<span>Log in</span>
)}
</Button>
</div>
Expand All @@ -207,9 +208,7 @@ const Login: React.FC<LoginReferrer> = () => {
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

0 comments on commit 8f17406

Please sign in to comment.