Skip to content

Commit

Permalink
chore: fixing sonar issues
Browse files Browse the repository at this point in the history
  • Loading branch information
paulushcgcj committed Nov 4, 2024
1 parent cc23d98 commit 06f7012
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 7 deletions.
4 changes: 2 additions & 2 deletions frontend/src/amplifyconfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ const verificationMethods: verificationMethodsType = 'code';
const amplifyconfig = {
Auth: {
Cognito: {
userPoolId: env.VITE_USER_POOLS_ID ?? "ca-central-1_t2HSZBHur",
userPoolClientId: env.VITE_USER_POOLS_WEB_CLIENT_ID ?? "70a2am185rie10r78b0ugcs1mm",
userPoolId: env.VITE_USER_POOLS_ID,
userPoolClientId: env.VITE_USER_POOLS_WEB_CLIENT_ID,
signUpVerificationMethod: verificationMethods, // 'code' | 'link'
loginWith: {
oauth: {
Expand Down
45 changes: 42 additions & 3 deletions frontend/src/contexts/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { createContext, useState, useContext, useEffect, ReactNode } from 'react';
import { fetchAuthSession, signInWithRedirect, signOut } from "aws-amplify/auth";
import { parseToken, FamLoginUser } from "../services/AuthService";
import { extractGroups } from '../utils/famUtils';
import { env } from '../env';
import { JWT } from '../types/amplify';

// 1. Define an interface for the context value
interface AuthContextType {
Expand All @@ -23,7 +25,6 @@ interface AuthProviderProps {
// 3. Create the context with a default value of `undefined`
const AuthContext = createContext<AuthContextType | undefined>(undefined);


// 4. Create the AuthProvider component with explicit typing
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
Expand All @@ -42,6 +43,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
setIsLoading(false);
if(session.tokens){
setUser(parseToken(session.tokens.idToken));
setUserRoles(extractGroups(session.tokens?.idToken?.payload));
}
}catch(error){
setIsLoggedIn(false);
Expand All @@ -54,7 +56,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {


const userDetails = async (): Promise<FamLoginUser | undefined> => {
const { idToken } = (await fetchAuthSession()).tokens ?? {}; //TODO: make a way to set through tests
const idToken = await loadUserToken();

if(idToken){
return Promise.resolve(parseToken(idToken));
Expand All @@ -68,7 +70,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
: `${(appEnv).toLocaleUpperCase()}-BCEIDBUSINESS`;

signInWithRedirect({
provider: { custom: envProvider.toUpperCase() } //TODO: Change environment
provider: { custom: envProvider.toUpperCase() }
});
};

Expand Down Expand Up @@ -101,4 +103,41 @@ export const getAuth = () => {
throw new Error('AuthProvider not found');
}
return context;
};

const loadUserToken = async () : Promise<JWT|undefined> => {
if(env.NODE_ENV !== 'test'){
const {idToken} = (await fetchAuthSession()).tokens ?? {};
return Promise.resolve(idToken);
} else {
// This is for test only
const token = getUserTokenFromCookie();
if (token) {
const jwtBody = token
? JSON.parse(atob(token.split(".")[1]))
: null;
return Promise.resolve({ payload: jwtBody });
} else {
return Promise.resolve(undefined);
}
}
};

const getUserTokenFromCookie = (): string|undefined => {
const baseCookieName = `CognitoIdentityServiceProvider.${env.VITE_USER_POOLS_WEB_CLIENT_ID}`;
const userId = encodeURIComponent(getCookie(`${baseCookieName}.LastAuthUser`));
if (userId) {
const idTokenCookieName = `${baseCookieName}.${userId}.idToken`;
const idToken = getCookie(idTokenCookieName);
return idToken;
} else {
return undefined;
}
};

const getCookie = (name: string): string => {
const cookie = document.cookie
.split(";")
.find((cookieValue) => cookieValue.trim().startsWith(name));
return cookie ? cookie.split("=")[1] : "";
};
21 changes: 19 additions & 2 deletions frontend/src/utils/famUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function formatRolesArray(decodedIdToken: object | undefined): UserClient
}

if ('cognito:groups' in decodedIdToken) {
const cognitoGroups: string[] = decodedIdToken['cognito:groups'] as string[];
const cognitoGroups: string[] = extractGroups(decodedIdToken);
const rolesMap: { [key: string]: string[] } = {};

cognitoGroups.forEach((group: string) => {
Expand All @@ -35,4 +35,21 @@ export function formatRolesArray(decodedIdToken: object | undefined): UserClient

return [];
}


/**
* Extract groups from the decoded token.
*
* @param {object | undefined} decodedIdToken Decoded token with payload.
* @returns {string[]} Array of groups.
*/
export function extractGroups(decodedIdToken: object | undefined): string[] {
if (!decodedIdToken) {
return [];
}

if ('cognito:groups' in decodedIdToken) {
return decodedIdToken['cognito:groups'] as string[];
}

return [];
}

0 comments on commit 06f7012

Please sign in to comment.