Skip to content
New issue

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

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

Already on GitHub? # to your account

CRDCDH-39 #43

Merged
merged 15 commits into from
Jul 14, 2023
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
4 changes: 3 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# NIH IDP
REACT_APP_NIH_AUTHORIZE_URL="https://link.to/nihloginpage"
REACT_APP_NIH_CLIENT_ID="ThisIsASecret"
REACT_APP_NIH_AUTHENTICATION_URL="https://link.to/somewhere"
REACT_APP_NIH_REDIRECT_URL="localhost:3000"
42 changes: 21 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/client": "^3.7.15",
"@apollo/client": "^3.7.16",
"@emotion/react": "^11.11.0",
"@emotion/styled": "^11.11.0",
"@jalik/form-parser": "^3.1.0",
Expand All @@ -16,11 +16,10 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.31",
"@types/react": "^18.2.6",
"@types/react-dom": "^18.2.4",
"dayjs": "^1.11.8",
"graphql": "^16.6.0",
"graphql": "^16.7.1",
"lodash": "^4.17.21",
"nprogress": "^0.2.0",
"react": "^18.2.0",
Expand Down Expand Up @@ -61,6 +60,7 @@
]
},
"devDependencies": {
"@types/node": "^20.4.0",
"@typescript-eslint/eslint-plugin": "^5.59.6",
"@typescript-eslint/parser": "^5.59.6",
"eslint": "^8.40.0",
Expand Down
55 changes: 55 additions & 0 deletions src/api/authn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const AUTH_SERVICE_URL = `${window.origin}/api/authn`;

/**
* Checks login status with AuthN
*/
export const isLoggedIn = () => {
fetch(`${AUTH_SERVICE_URL}/authenticated`, {
method: 'POST',
})
.then((response) => response.json())
.then((result) => {
const {
status,
} = result;

console.log('Is logged in:', status);

return status === true;
})
.catch((error) => console.log('Error', error));

return false;
};

/**
* Logs in to AuthN
*
* @param {string} authCode Authorization code used to verify login
*/
export const logIn = (authCode) => {
const myHeaders = new Headers();
const raw = JSON.stringify({
code: authCode,
IDP: 'nih',
});
const requestRedirect:RequestRedirect = 'follow';
const requestCredentials:RequestCredentials = 'include';

myHeaders.append('Content-Type', 'application/json');

const requestOptions = {
body: raw,
credentials: requestCredentials,
headers: myHeaders,
method: 'POST',
redirect: requestRedirect,
withCredentials: true,
};

fetch(`${AUTH_SERVICE_URL}/#`, requestOptions)
.then((response) => response.json())
.then((result) => console.log('Login results:', result))
.then(() => isLoggedIn())
.catch((error) => console.log('error', error));
};
4 changes: 2 additions & 2 deletions src/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ const defaultOptions:DefaultOptions = {

const BACKEND = env.REACT_APP_BACKEND_API;
const MOCK = 'https://7a242248-52f7-476a-a60f-d64a2db3dd5b.mock.pstmn.io/graphql';
const AUTH_SERVICE = `${env.REACT_APP_AUTH_SERVICE_API}graphql`;
const USER_SERVICE = `${env.REACT_APP_USER_SERVICE_API}graphql`;
const AUTH_SERVICE = `${window.origin}/api/authn`;
const USER_SERVICE = `${window.origin}/api/authz/graphql`;

const backendService = new HttpLink({
uri: BACKEND,
Expand Down
Empty file.
96 changes: 96 additions & 0 deletions src/components/Contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, {
FC,
createContext,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import {
isLoggedIn,
logIn
} from '../../api/authn';
// import env from '../../env';

// console.log('Foo', env);

export type ContextState = {
error?: string;
isLoggedIn: boolean;
status: Status;
user: User;
};

export enum Status {
LOADING = "LOADING", // Retrieving user data
LOADED = "LOADED", // Successfully retrieved user data
ERROR = "ERROR", // Error retrieving user data
}

const initialState: ContextState = {
isLoggedIn: false,
status: Status.LOADING,
user: null,
};

/**
* Auth Context
*
* NOTE: Do NOT use this context directly. Use the useAuthContext hook instead.
* this is exported for testing purposes only.
*
* @see ContextState – Auth context state
* @see useAuthContext – Auth context hook
*/
export const Context = createContext<ContextState>(initialState);
Context.displayName = 'AuthContext';

/**
* Auth Context Hook
*
* @see AuthProvider – Must be wrapped in a AuthProvider component
* @see ContextState – Auth context state returned by the hook
* @returns {ContextState} - Auth context
*/
export const useAuthContext = (): ContextState => {
const context = useContext<ContextState>(Context);

if (!context) {
throw new Error("AuthContext cannot be used outside of the AuthProvider component");
}

return context;
};

type ProviderProps = {
children: React.ReactNode;
};

/**
* Creates an auth context
*
* @see useAuthContext – Auth context hook
* @param {ProviderProps} props - Auth context provider props
* @returns {JSX.Element} - Auth context provider
*/
export const AuthProvider: FC<ProviderProps> = (props) => {
const { children } = props;
const [state, setState] = useState<ContextState>(initialState);

useEffect(() => {
const searchParams = new URLSearchParams(document.location.search);
const authCode = searchParams.get('code');

if (!isLoggedIn()) {
logIn(authCode);
}
}, []);

const value = useMemo(() => ({ ...state }), [state]);

return (
<Context.Provider value={value}>
{children}
</Context.Provider>
);
};
16 changes: 16 additions & 0 deletions src/components/Contexts/graphql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,19 @@ mutation submitApplication($id: ID!) {
}
}
`;

export const GET_USER = gql`
query getMyUser {
getMyUser {
_id
firstName
lastName
userStatus
role
IDP
email
createdAt
updateAt
}
}
`;
21 changes: 12 additions & 9 deletions src/content/#/Controller.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
import env from '../../env';

function loginController() {
const NIH_AUTH_URL = process.env.NIH_AUTHENTICATION_URL || process.env.REACT_APP_NIH_AUTHENTICATION_URL;
/**
* Redirects to NIH login to get an authorization code
*
* @returns null
*/
const loginController = () => {
const NIH_AUTHORIZE_URL = process.env.NIH_AUTHORIZE_URL || process.env.REACT_APP_NIH_AUTHORIZE_URL;
const NIH_CLIENT_ID = process.env.NIH_CLIENT_ID || process.env.REACT_APP_NIH_CLIENT_ID;
const NIH_REDIRECT_URL = process.env.NIH_REDIRECT_URL || process.env.REACT_APP_NIH_REDIRECT_URL;

const originDomain = window.location.origin;
const urlParam = {
client_id: `${NIH_CLIENT_ID}`,
redirect_uri: `${originDomain}`,
redirect_uri: `${NIH_REDIRECT_URL}`,
response_type: 'code',
scope: 'openid email profile'
// state: JSON.stringify(state || {}),
};

const params = new URLSearchParams(urlParam).toString();
const redirectUrl = `${NIH_AUTH_URL}?${params}`;
const redirectUrl = `${NIH_AUTHORIZE_URL}?${params}`;
window.location.href = redirectUrl;

return null;
}
};

export default loginController;
5 changes: 4 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import App from './App';
import client from './client';
import * as serviceWorker from './serviceWorker';
import reportWebVitals from './reportWebVitals';
import { AuthProvider } from './components/Contexts/AuthContext';

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<ApolloProvider client={client}>
<HelmetProvider>
<App />
<AuthProvider>
<App />
</AuthProvider>
</HelmetProvider>
</ApolloProvider>,
);
Expand Down
Loading