Skip to content

Commit

Permalink
fix some issues with credentialsLogin
Browse files Browse the repository at this point in the history
  • Loading branch information
craigrbarnes committed Mar 20, 2024
1 parent de5f140 commit c7f5dd6
Show file tree
Hide file tree
Showing 17 changed files with 2,742 additions and 33 deletions.
3 changes: 2 additions & 1 deletion packages/core/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ export const GUID_PREFIX_PATTERN = /^dg.[a-zA-Z0-9]+\//;
export const GEN3_GUPPY_API = process.env.NEXT_PUBLIC_GEN3_GUPPY_API || `${GEN3_API}/guppy`;
export const GEN3_MDS_API = process.env.NEXT_PUBLIC_GEN3_MDS_API || `${GEN3_API}/mds`;
export const GEN3_DOWNLOADS_ENDPOINT = process.env.NEXT_PUBLIC_GEN3_DOWNLOADS_ENDPOINT || 'downloads';
export const GEN3_FENCE_ENDPOINT = process.env.NEXT_PUBLIC_GEN3_FENCE_ENDPOINT || GEN3_API;
export const GEN3_FENCE_API = process.env.NEXT_PUBLIC_GEN3_FENCE_API || GEN3_API;
export const GEN3_AI_SEARCH_API = process.env.NEXT_PUBLIC_GEN3_AI_SEARCH_API || `${GEN3_API}/ai-search`;
export const GEN3_AUTHZ_API = process.env.NEXT_PUBLIC_GEN3_AUTHZ_API || `${GEN3_API}/authz`;

export enum Accessibility {
ACCESSIBLE = 'accessible',
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/features/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { setAccessToken, setCSRF, selectAccessToken, selectAuthCSRF } from './authStateSlice';

export { setAccessToken, setCSRF, selectAccessToken, selectAuthCSRF };
3 changes: 2 additions & 1 deletion packages/core/src/features/authz/authzMappingSlice.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { gen3Api } from '../gen3';
import { type AuthzMapping } from './types';
import { GEN3_AUTHZ_API } from '../../constants';

/**
* Creates the authzApi for checking arborist permissions for a selected user
Expand All @@ -10,7 +11,7 @@ import { type AuthzMapping } from './types';
export const authzApi = gen3Api.injectEndpoints({
endpoints: (builder) => ({
getAuthzMappings: builder.query<AuthzMapping, void>({
query: () => 'authz/mapping',
query: () => `${GEN3_AUTHZ_API}/mapping`,
}),
}),
});
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/features/authz/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { type AuthzMapping, type ServiceAndMethod } from './types';
import { useGetAuthzMappingsQuery } from './authzMappingSlice';
import { setAccessToken, setCSRF, selectAccessToken, selectAuthCSRF } from './authStateSlice';

export { useGetAuthzMappingsQuery, type AuthzMapping, type ServiceAndMethod, setCSRF, setAccessToken, selectAccessToken, selectAuthCSRF};
export { useGetAuthzMappingsQuery, type AuthzMapping, type ServiceAndMethod, };
10 changes: 5 additions & 5 deletions packages/core/src/features/fence/credentialsApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { gen3Api } from '../gen3';
import { GEN3_FENCE_ENDPOINT } from '../../constants';
import { GEN3_FENCE_API } from '../../constants';

export interface APIKey {
readonly jti: string;
Expand Down Expand Up @@ -39,7 +39,7 @@ export interface AuthTokenResponse {
export const credentialsApi = credentialsWithTags.injectEndpoints({
endpoints: (builder) => ({
getCredentials: builder.query<ReadonlyArray<APIKey>, void>({
query: () => 'user/credentials/api',
query: () => `${GEN3_FENCE_API}/user/credentials/api`,
transformResponse: (
response: Gen3FenceCredentials,
): ReadonlyArray<APIKey> => response['jtis'], // the response is a JSON object with a single key,
Expand All @@ -49,7 +49,7 @@ export const credentialsApi = credentialsWithTags.injectEndpoints({
}),
addNewCredential: builder.mutation({
query: (csrfToken: string) => ({
url: `${GEN3_FENCE_ENDPOINT}/user/credentials/api`,
url: `${GEN3_FENCE_API}/user/credentials/api`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand All @@ -63,7 +63,7 @@ export const credentialsApi = credentialsWithTags.injectEndpoints({
}),
removeCredential: builder.mutation<void, DeleteCredentialParams>({
query: ({ csrfToken, id }) => ({
url: `${GEN3_FENCE_ENDPOINT}/user/credentials/api/${id}`,
url: `${GEN3_FENCE_API}/user/credentials/api/${id}`,
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Expand All @@ -74,7 +74,7 @@ export const credentialsApi = credentialsWithTags.injectEndpoints({
}),
authorizeFromCredentials: builder.mutation<AuthTokenResponse, AuthorizeFromCredentialsParams>({
query: (params) => ({
url: '/user/credentials/api/access_token',
url: `${GEN3_FENCE_API}/user/credentials/api/access_token`,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/features/fence/fenceApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { gen3Api } from '../gen3';
import { Gen3Response } from '../../dataAccess';
import { GEN3_FENCE_ENDPOINT } from '../../constants';
import { GEN3_FENCE_API } from '../../constants';

export interface NameUrl {
readonly name: string;
Expand Down Expand Up @@ -30,7 +30,7 @@ export interface Gen3FenceLoginProviders {
export const loginProvidersApi = gen3Api.injectEndpoints({
endpoints: (builder) => ({
getLoginProviders: builder.query<Gen3FenceLoginProviders, void>({
query: () => `${GEN3_FENCE_ENDPOINT}/user/login`,
query: () => `${GEN3_FENCE_API}/user/login`,
}),
}),
});
Expand Down Expand Up @@ -86,7 +86,7 @@ const buildFetchError = async <T>(
export const fetchFence = async <T>(
request: FetchRequest,
): Promise<Gen3FenceResponse<T>> => {
const res = await fetch(`${GEN3_FENCE_ENDPOINT}${request.endpoint}`, {
const res = await fetch(`${GEN3_FENCE_API}${request.endpoint}`, {
method: request.method,
headers: request.headers,
body: 'POST' === request.method ? JSON.stringify(request.body) : null,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/features/gen3/gen3Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const gen3Api = coreCreateApi({
const state = getState() as CoreState;
const csrfToken = selectCSRFToken(getState() as CoreState);
const {accessToken} = state.auth;
console.log("accessToken", accessToken, "csrfToken", csrfToken);
if (csrfToken) {
headers.set('X-CSRFToken', csrfToken);
}
Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/features/user/userSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
import { useCoreDispatch, useCoreSelector } from '../../hooks';
import { useEffect } from 'react';
import { UserProfile } from './types';
import { GEN3_FENCE_API } from '../../constants';
import { selectAccessToken} from '../auth';

export type Gen3User = Partial<UserProfile>;

Expand All @@ -32,14 +34,17 @@ export const fetchUserState = createAsyncThunk<
Gen3FenceResponse<Gen3User>,
void,
{ dispatch: CoreDispatch; state: CoreState }
>('fence/user', async () => {
>('fence/user/user', async (_, api ) => {
const accessToken = selectAccessToken(api.getState());

return await fetchFence({
endpoint: '/user/user',
endpoint: `${GEN3_FENCE_API}/user/user`,
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
credentials: 'include',
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
},
});
});
Expand Down
24 changes: 22 additions & 2 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { GEN3_API, GEN3_DOMAIN, GEN3_COMMONS_NAME, GEN3_DOWNLOADS_ENDPOINT, GEN3_GUPPY_API, Accessibility } from './constants';
import {
GEN3_API,
GEN3_DOMAIN,
GEN3_COMMONS_NAME,
GEN3_DOWNLOADS_ENDPOINT,
GEN3_GUPPY_API,
GEN3_FENCE_API,
GEN3_AUTHZ_API,
Accessibility,
} from './constants';
import { type CoreState } from './reducers';

export * from './features/user';
Expand All @@ -7,6 +16,7 @@ export * from './store';
export * from './hooks';
export * from './dataAccess';
export * from './provider';
export * from './features/auth';
export * from './features/authz';
export * from './features/metadata/metadataSlice';
export * from './features/fence';
Expand All @@ -20,4 +30,14 @@ export * from './features/filters';
export * from './features/guppy';
export * from './features/aiSearch';

export { type CoreState, GEN3_COMMONS_NAME, GEN3_DOMAIN, GEN3_API, GEN3_DOWNLOADS_ENDPOINT, GEN3_GUPPY_API, Accessibility };
export {
type CoreState,
GEN3_COMMONS_NAME,
GEN3_DOMAIN,
GEN3_API,
GEN3_DOWNLOADS_ENDPOINT,
GEN3_GUPPY_API,
GEN3_FENCE_API,
GEN3_AUTHZ_API,
Accessibility,
};
2 changes: 1 addition & 1 deletion packages/core/src/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { gen3AppReducer } from './features/gen3Apps/gen3AppsSlice';
import { drsHostnamesReducer } from './features/drsResolver';
import { modalReducer } from './features/modals/modalsSlice';
import { cohortReducer } from './features/cohort';
import { authReducer } from './features/authz/authStateSlice';
import { authReducer } from './features/auth/authStateSlice';

import {
guppyApiReducer,
Expand Down
17 changes: 9 additions & 8 deletions packages/frontend/src/components/Login/CredentialsLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Textarea,
} from '@mantine/core';
import {
fetchUserState,
setAccessToken,
useAuthorizeFromCredentialsMutation,
useCoreDispatch,
Expand Down Expand Up @@ -41,16 +42,16 @@ const CredentialsLogin = ({

useDeepCompareEffect(() => {
if (isSuccess && data?.access_token) {
fetch('/api/auth/setSessionToken', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ access_token: data.access_token }),
});
// fetch('/api/auth/setSessionToken', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ access_token: data.access_token }),
// });

// store the access token in the redux store
dispatch(setAccessToken({ accessToken: data?.access_token }));
handleLoginSelected('/', redirectURL);

} else {
if (isError) {
Expand Down
8 changes: 4 additions & 4 deletions packages/frontend/src/lib/session/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
fetchUserState,
CoreDispatch,
useCoreDispatch,
GEN3_API,
GEN3_FENCE_API,
} from '@gen3/core';

const SecondsToMilliseconds = (seconds: number) => seconds * 1000;
Expand Down Expand Up @@ -36,6 +36,7 @@ function useOnline() {
const SessionContext = React.createContext<Session | undefined>(undefined);

const getSession = async () => {

try {
const res = await fetch('/api/auth/sessionToken');
if (res.status === 200) {
Expand Down Expand Up @@ -74,8 +75,7 @@ export const useSession = (

const logoutUser = (router: NextRouter) => {
if (typeof window === 'undefined') return; // skip if this pages is on the server
console.log('logging out user', GEN3_API);
router.push(`${GEN3_API}/user/logout?next=/`);
router.push(`${GEN3_FENCE_API}/user/logout?next=/`);
};

const refreshSession = (dispatch: CoreDispatch,
Expand Down Expand Up @@ -122,7 +122,7 @@ const useInterval = ( callback: IntervalFunction, delay: number | null ) => {
const UPDATE_SESSION_LIMIT = MinutesToMilliseconds(5);

/**
* SessionProvider creates a react context which keeps track of wether the user is authenticated
* SessionProvider creates a React context which keeps track of wether the user is authenticated
* and if their session is stale and logs them out if they do not preform an action in an alotted amount of time
* @param children - Pass in a child session if one exists
* @param session - Pass in a cached session if one exists
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/src/pages/api/auth/sessionToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export interface JWTPayloadAndUser extends JWTPayload {
export default async function (req: NextApiRequest, res: NextApiResponse) {
const access_token = getCookie('access_token', { req, res });
if (access_token && typeof access_token === 'string') {
const decodedAccessToken = (await decodeJwt(
const decodedAccessToken = decodeJwt(
access_token,
)) as unknown as JWTPayloadAndUser;
) as unknown as JWTPayloadAndUser;
return res.status(200).json({
issued: decodedAccessToken.iat,
expires: decodedAccessToken.exp,
Expand Down
4 changes: 3 additions & 1 deletion packages/sampleCommons/.env.development
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
GEN3_COMMONS_NAME=brh
NEXT_PUBLIC_GEN3_API=https://brh.data-commons.org
NEXT_PUBLIC_GEN3_API=https://localhost:3010
NEXT_PUBLIC_GEN3_DOMAIN=https://localhost:3010
#NEXT_PUBLIC_GEN3_MDS_API=https://brh.data-commons.org/mds
#NEXT_PUBLIC_GEN3_AI_SEARCH_API=http://localhost:8089
#NEXT_PUBLIC_GEN3_GUPPY_API=https://localhost:3010/guppy
NEXT_PUBLIC_GEN3_FENCE_API=https://brh.data-commons.org
NEXT_PUBLIC_GEN3_AUTHZ_API=https://brh.data-commons.org/authz
2 changes: 1 addition & 1 deletion packages/sampleCommons/config/brh/login.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"className": "text-center text-sm"
}
],
"image": "images/brh/gene_bgy.png",
"image": "images/brh/gene_bgy.svg",
"email": "[email protected]",
"showCredentialsLogin" : true
}
Loading

0 comments on commit c7f5dd6

Please sign in to comment.