Skip to content

Commit

Permalink
Updating the auth logic
Browse files Browse the repository at this point in the history
  • Loading branch information
walisc committed Nov 17, 2023
1 parent ac1cc2a commit b593d13
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 232 deletions.
9 changes: 5 additions & 4 deletions JeMPI_Apps/JeMPI_UI/src/hooks/useAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ export const AuthChecker = ({ children }: AuthProviderProps): JSX.Element => {
const oauthRef = useRef<OAuthParams | null>(null)

const { mutate: validateOAuth } = useMutation({
mutationFn: apiClient.validateOAuth,
mutationFn: apiClient.validateOAuth.bind(apiClient),
onSuccess(response) {
enqueueSnackbar(`Successfully logged in using KeyCloak`, {
variant: 'success'
})
authContext.setUser(response)
authContext.setUser(response as User)
navigate({ pathname: '/' })
},
onError() {
Expand Down Expand Up @@ -117,6 +117,7 @@ const currentUserOueryClientKey = 'auth-user'

export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
const { apiClient, config } = useConfig()
const keycloack = getKeycloak(config)
const queryClient = useQueryClient()
const { enqueueSnackbar } = useSnackbar()

Expand All @@ -136,7 +137,7 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
})

const { mutate: logout } = useMutation({
mutationFn: apiClient.logout,
mutationFn: apiClient.logout.bind(apiClient),
onSuccess(data: any, navigate: NavigateFunction) {
queryClient.clear()
navigate({ pathname: '/login' })
Expand All @@ -153,7 +154,7 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
}

const signInWithKeyCloak = () => {
getKeycloak(config).init({
keycloack.init({
onLoad: 'login-required',
redirectUri: window.location.href,
checkLoginIframe: false
Expand Down
5 changes: 1 addition & 4 deletions JeMPI_Apps/JeMPI_UI/src/services/ApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ export class ApiClient {
if (['post', 'patch', 'put', 'delete'].indexOf(method || '') !== -1) {
const csrfToken = getCookie('XSRF-TOKEN')
if (csrfToken) {
request.headers = {
...request.headers,
'X-XSRF-TOKEN': csrfToken
}
request.headers['X-XSRF-TOKEN'] = csrfToken
}
}
return request
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Docker from 'dockerode'
import { getTestEnvConfig } from './Utils'

export abstract class DockerBase{

Expand All @@ -15,22 +16,9 @@ export abstract class DockerBase{
abstract HasLoadedFunc(): () => Promise<any>;

GetEnvConfig(){
return {
isDev: process.env.NODE_ENV !== 'production',
apiUrl: process.env.REACT_APP_JEMPI_BASE_API_HOST
? `${process.env.REACT_APP_JEMPI_BASE_API_HOST}:${process.env.REACT_APP_JEMPI_BASE_API_PORT}`
: `${window.location.protocol}//${window.location.hostname}:${process.env.REACT_APP_JEMPI_BASE_API_PORT}`,
shouldMockBackend: process.env.REACT_APP_MOCK_BACKEND === 'true',
KeyCloakUrl: process.env.KC_FRONTEND_URL || 'http://localhost:9088',
KeyCloakRealm: process.env.KC_REALM_NAME || 'platform-realm',
KeyCloakClientId: process.env.KC_JEMPI_CLIENT_ID || 'jempi-oauth',
useSso: process.env.REACT_APP_ENABLE_SSO === 'true',
maxUploadCsvSize: +(
process.env.REACT_APP_MAX_UPLOAD_CSV_SIZE_IN_MEGABYTES || 128
),
showBrandLogo: process.env.REACT_APP_SHOW_BRAND_LOGO === 'true'
}
return getTestEnvConfig()
}

async Start(){
await this.CreateService()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { constants as httpsStatusCodes } from 'http2';
import path from 'path';
import fs from 'fs';
import moxios from '../../../../../src/services/mockBackend'
import { config } from '../../../../../src/config'
import { getTestEnvConfig } from '../Utils'

type methods = 'POST' | 'GET' | 'PUT' | string
export type IMockEndpointConfig = { [urlPath:string] : {
Expand All @@ -23,6 +23,7 @@ class MockJeMPIAPIServer {
appUrl:string

constructor(extendingConfig:IMockEndpointConfig, appPort:number){
const config = getTestEnvConfig();
this.server =this.CreateMockServer(extendingConfig)
const parsedUrl = new URL(config.apiUrl);
this.serverPort = parseInt(parsedUrl.port)
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ import axios from 'axios'
import Docker from 'dockerode'
import path from 'path';
import fs from 'fs';
import { config } from '../../../../../src/config'
import { DockerBase } from '../DockerBase';

class MockKeyCloack extends DockerBase{

class MockKeyCloack {
docker:Docker
serviceName:string
keyClockUrl:string
keyClockUrlPort:string
keyClockRealm:string
keyClockClient:string
addtionalUser:any[]

constructor(userConfig:any[]=[]){
super()
const config = this.GetEnvConfig();
const parsedUrl = new URL(config.KeyCloakUrl);

this.keyClockUrl = config.KeyCloakUrl
Expand All @@ -23,7 +24,6 @@ class MockKeyCloack {
this.keyClockClient = config.KeyCloakClientId

this.docker = new Docker()
this.serviceName = "JeMPIMockKeyCloak"
this.addtionalUser = userConfig
}

Expand Down Expand Up @@ -121,56 +121,14 @@ class MockKeyCloack {
}
}

async CreateService(){
const waitToLoad = (checkPromise:() => Promise<any>, waitFor: 'resolve' | 'reject') => {
return new Promise( (resolve:any, reject:any) => {
let time= 0
const addTime = () =>{
if (time > 60000){
reject("Timeout starting keycloak")
}
time += 1000
}

const interval = setInterval(() => checkPromise().then(() => {
if (waitFor === 'resolve'){
clearInterval(interval)
resolve()
}else{
addTime()
}

}).catch(() => {
if (waitFor === 'reject'){
clearInterval(interval)
resolve()
}else{
addTime()
}
}), 1000)
})
}

const containers = await this.docker.listContainers()
const targetContainerInfo = containers.find(container => container.Names.includes("/"+this.serviceName));
if (targetContainerInfo){
const targetContainer = await this.docker.getContainer(targetContainerInfo.Id)
await targetContainer.stop()
const stream = await targetContainer.attach({ stream: true, stdout: true, stderr: true })
stream.pipe(process.stdout)
await waitToLoad(() => this.docker.getContainer(targetContainerInfo.Id).inspect(), 'reject')


}

const container = await this.docker.createContainer(this.GetConfig())
await container.start()
const stream = await container.attach({ stream: true, stdout: true, stderr: true })
stream.pipe(process.stdout)
await waitToLoad(() => axios.get(this.keyClockUrl), 'resolve')

GetServiceName(): string {
return "JeMPIMockKeyCloak"
}

HasLoadedFunc(): () => Promise<any> {
return () => axios.get(this.keyClockUrl)
}

}

let fullPath:string = ""
Expand Down
17 changes: 17 additions & 0 deletions JeMPI_Apps/JeMPI_UI/tests/test.utils/mocks/enviroments/Utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const getTestEnvConfig = () => {
return {
isDev: process.env.NODE_ENV !== 'production',
apiUrl: process.env.REACT_APP_JEMPI_BASE_API_HOST
? `${process.env.REACT_APP_JEMPI_BASE_API_HOST}:${process.env.REACT_APP_JEMPI_BASE_API_PORT}`
: `http://localhost:50000/JeMPI`,
shouldMockBackend: process.env.REACT_APP_MOCK_BACKEND === 'true',
KeyCloakUrl: process.env.KC_FRONTEND_URL || 'http://localhost:9088',
KeyCloakRealm: process.env.KC_REALM_NAME || 'platform-realm',
KeyCloakClientId: process.env.KC_JEMPI_CLIENT_ID || 'jempi-oauth',
useSso: process.env.REACT_APP_ENABLE_SSO === 'true',
maxUploadCsvSize: +(
process.env.REACT_APP_MAX_UPLOAD_CSV_SIZE_IN_MEGABYTES || 128
),
showBrandLogo: process.env.REACT_APP_SHOW_BRAND_LOGO === 'true'
}
}

0 comments on commit b593d13

Please sign in to comment.