diff --git a/.env.example b/.env.example index d3a5dd837..ec4328a2c 100644 --- a/.env.example +++ b/.env.example @@ -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" diff --git a/package-lock.json b/package-lock.json index 5b58b66e8..d2601368a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "CRDC DataHub", "version": "0.1.0", "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", @@ -21,11 +21,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", @@ -37,6 +36,7 @@ "web-vitals": "^2.1.4" }, "devDependencies": { + "@types/node": "^20.4.0", "@typescript-eslint/eslint-plugin": "^5.59.6", "@typescript-eslint/parser": "^5.59.6", "eslint": "^8.40.0", @@ -90,9 +90,9 @@ } }, "node_modules/@apollo/client": { - "version": "3.7.15", - "resolved": "https://registry.npmjs.org/@apollo/client/-/client-3.7.15.tgz", - "integrity": "sha512-pLScjo4GAQRWKWyEg2J3FlQr9fbUAuADT0EI2+JlLf2BjaU9I7WUaZVD9w+0qNPE8BZqs53MRQq0OCm1QCW+eg==", + "version": "3.7.16", + "resolved": "https://registry.npmjs.org/@apollo/client/-/client-3.7.16.tgz", + "integrity": "sha512-rdhoc7baSD7ZzcjavEpYN8gZJle1KhjEKj4SJeMgBpcnO4as7oXUVU4LtFpotzZdFlo57qaLrNzfvppSTsKvZQ==", "dependencies": { "@graphql-typed-document-node/core": "^3.1.1", "@wry/context": "^0.7.0", @@ -4408,9 +4408,9 @@ "integrity": "sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==" }, "node_modules/@types/node": { - "version": "16.18.34", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.34.tgz", - "integrity": "sha512-VmVm7gXwhkUimRfBwVI1CHhwp86jDWR04B5FGebMMyxV90SlCmFujwUHrxTD4oO+SOYU86SoxvhgeRQJY7iXFg==" + "version": "20.4.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.0.tgz", + "integrity": "sha512-jfT7iTf/4kOQ9S7CHV9BIyRaQqHu67mOjsIQBC3BKZvzvUB6zLxEwJ6sBE3ozcvP8kF6Uk5PXN0Q+c0dfhGX0g==" }, "node_modules/@types/parse-json": { "version": "4.0.0", @@ -8952,9 +8952,9 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==" }, "node_modules/graphql": { - "version": "16.6.0", - "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.6.0.tgz", - "integrity": "sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw==", + "version": "16.7.1", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.7.1.tgz", + "integrity": "sha512-DRYR9tf+UGU0KOsMcKAlXeFfX89UiiIZ0dRU3mR0yJfu6OjZqUcp68NnFLnqQU5RexygFoDy1EW+ccOYcPfmHg==", "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -17081,9 +17081,9 @@ } }, "@apollo/client": { - "version": "3.7.15", - "resolved": "https://registry.npmjs.org/@apollo/client/-/client-3.7.15.tgz", - "integrity": "sha512-pLScjo4GAQRWKWyEg2J3FlQr9fbUAuADT0EI2+JlLf2BjaU9I7WUaZVD9w+0qNPE8BZqs53MRQq0OCm1QCW+eg==", + "version": "3.7.16", + "resolved": "https://registry.npmjs.org/@apollo/client/-/client-3.7.16.tgz", + "integrity": "sha512-rdhoc7baSD7ZzcjavEpYN8gZJle1KhjEKj4SJeMgBpcnO4as7oXUVU4LtFpotzZdFlo57qaLrNzfvppSTsKvZQ==", "requires": { "@graphql-typed-document-node/core": "^3.1.1", "@wry/context": "^0.7.0", @@ -19917,9 +19917,9 @@ "integrity": "sha512-YATxVxgRqNH6nHEIsvg6k2Boc1JHI9ZbH5iWFFv/MTkchz3b1ieGDa5T0a9RznNdI0KhVbdbWSN+KWWrQZRxTw==" }, "@types/node": { - "version": "16.18.34", - "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.34.tgz", - "integrity": "sha512-VmVm7gXwhkUimRfBwVI1CHhwp86jDWR04B5FGebMMyxV90SlCmFujwUHrxTD4oO+SOYU86SoxvhgeRQJY7iXFg==" + "version": "20.4.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.4.0.tgz", + "integrity": "sha512-jfT7iTf/4kOQ9S7CHV9BIyRaQqHu67mOjsIQBC3BKZvzvUB6zLxEwJ6sBE3ozcvP8kF6Uk5PXN0Q+c0dfhGX0g==" }, "@types/parse-json": { "version": "4.0.0", @@ -23260,9 +23260,9 @@ "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==" }, "graphql": { - "version": "16.6.0", - "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.6.0.tgz", - "integrity": "sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw==" + "version": "16.7.1", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.7.1.tgz", + "integrity": "sha512-DRYR9tf+UGU0KOsMcKAlXeFfX89UiiIZ0dRU3mR0yJfu6OjZqUcp68NnFLnqQU5RexygFoDy1EW+ccOYcPfmHg==" }, "graphql-tag": { "version": "2.12.6", diff --git a/package.json b/package.json index bce42c8c9..c7146255d 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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", @@ -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", diff --git a/src/api/authn.ts b/src/api/authn.ts new file mode 100644 index 000000000..168e44ea9 --- /dev/null +++ b/src/api/authn.ts @@ -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}/login`, requestOptions) + .then((response) => response.json()) + .then((result) => console.log('Login results:', result)) + .then(() => isLoggedIn()) + .catch((error) => console.log('error', error)); +}; diff --git a/src/client.tsx b/src/client.tsx index 2820e4351..2429424d5 100644 --- a/src/client.tsx +++ b/src/client.tsx @@ -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, diff --git a/src/components/Contexts/AuthContext.test.tsx b/src/components/Contexts/AuthContext.test.tsx new file mode 100644 index 000000000..e69de29bb diff --git a/src/components/Contexts/AuthContext.tsx b/src/components/Contexts/AuthContext.tsx new file mode 100644 index 000000000..f154ba15c --- /dev/null +++ b/src/components/Contexts/AuthContext.tsx @@ -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(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(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 = (props) => { + const { children } = props; + const [state, setState] = useState(initialState); + + useEffect(() => { + const searchParams = new URLSearchParams(document.location.search); + const authCode = searchParams.get('code'); + + if (!isLoggedIn()) { + logIn(authCode); + } + }, []); + + const value = useMemo(() => ({ ...state }), [state]); + + return ( + + {children} + + ); +}; diff --git a/src/components/Contexts/graphql.tsx b/src/components/Contexts/graphql.tsx index bb18b9772..6e6fcd646 100644 --- a/src/components/Contexts/graphql.tsx +++ b/src/components/Contexts/graphql.tsx @@ -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 + } + } +`; diff --git a/src/content/login/Controller.tsx b/src/content/login/Controller.tsx index 882cfd9a6..8505f0d21 100644 --- a/src/content/login/Controller.tsx +++ b/src/content/login/Controller.tsx @@ -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; diff --git a/src/index.tsx b/src/index.tsx index 786b9dcb1..2f44267a9 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -6,6 +6,7 @@ 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 @@ -13,7 +14,9 @@ const root = ReactDOM.createRoot( root.render( - + + + , ); diff --git a/src/layouts/index.tsx b/src/layouts/index.tsx index c403fb2a9..9eeb2dde8 100644 --- a/src/layouts/index.tsx +++ b/src/layouts/index.tsx @@ -1,8 +1,8 @@ import { FC, ReactNode } from 'react'; -import PropTypes from 'prop-types'; +import { Helmet } from 'react-helmet-async'; import { Outlet } from 'react-router-dom'; import { styled } from '@mui/material'; -import { Helmet } from 'react-helmet-async'; +import PropTypes from 'prop-types'; import Footer from '../components/Footer'; import Header from '../components/Header'; import ScrollButton from '../components/ScrollButton/ScrollButtonView'; @@ -41,7 +41,7 @@ const Layout: FC = ({ children }) => (