Skip to content

Commit

Permalink
Merge pull request #10 from bcgov/fix-page-loading
Browse files Browse the repository at this point in the history
Fix page refreshing & protected routes
  • Loading branch information
mgtennant authored Jun 11, 2024
2 parents 94d62eb + bd4581a commit eaacc55
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 57 deletions.
3 changes: 2 additions & 1 deletion frontend/.prettierrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ singleQuote: true

# Use 2 spaces for indentation
tabWidth: 2
printWidth: 120

# Use spaces instead of tabs
useTabs: false
Expand All @@ -19,4 +20,4 @@ semi: false
proseWrap: 'always'

# Format files with Unix-style line endings
endOfLine: 'lf'
endOfLine: 'lf'
42 changes: 22 additions & 20 deletions frontend/src/pages/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,29 +39,31 @@ const columns = [
},
]
export default function Dashboard() {
const [data, setData] = useState<any>([])
const [data, setData] = useState<any>([
{ id: 1, name: 'Michael', email: 'michael@email.com' },
])

useEffect(() => {
apiService
.getAxiosInstance()
.get('/v1/users')
.then((response: AxiosResponse) => {
const users = []
for (const user of response.data) {
const userDto = {
id: user.id,
name: user.name,
email: user.email,
}
users.push(userDto)
}
setData(users)
})
.catch((error) => {
console.error(error)
})
// apiService
// .getAxiosInstance()
// .get('/v1/users')
// .then((response: AxiosResponse) => {
// const users = []
// for (const user of response.data) {
// const userDto = {
// id: user.id,
// name: user.name,
// email: user.email,
// }
// users.push(userDto)
// }
// setData(users)
// })
// .catch((error) => {
// console.error(error)
// })
}, [])
const [selectedRow, setSelectedRow] = useState(null)
const [selectedRow, setSelectedRow] = useState<null | any[]>(null)

const handleClose = () => {
setSelectedRow(null)
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ export default function AppRoutes() {
<>
<Routes>
<Route element={<ProtectedRoutes roles={[Roles.ENMODS_ADMIN]} />}>
<Route path="/" element={<Dashboard />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/admin" element={<AdminPage />} />
<Route path="/submit" element={<FileUpload />} />
</Route>

<Route element={<ProtectedRoutes roles={[Roles.ENMODS_USER]} />}>
<Route path="/" element={<Dashboard />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/submit" element={<FileUpload />} />
</Route>

Expand Down
10 changes: 5 additions & 5 deletions frontend/src/routes/protected-routes.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { FC } from 'react'
import { Navigate } from 'react-router-dom'
import { Navigate, Outlet } from 'react-router-dom'
import Roles from '../roles'
import Dashboard from '@/pages/Dashboard'

export const ProtectedRoutes: FC<{ roles: Array<Roles> }> = () => {
let auth = { token: true }
return auth.token ? <Dashboard /> : <Navigate to="/not-authorized" />
export const ProtectedRoutes: FC<{ roles: Array<Roles> }> = ({ roles }) => {
let auth = { token: true } // Replace this with your actual authentication logic

return auth.token ? <Outlet /> : <Navigate to="/not-authorized" />
}
54 changes: 27 additions & 27 deletions frontend/src/service/user-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import _kc from "../keycloak";
import _kc from '../keycloak'

export const AUTH_TOKEN = "__auth_token";
export const AUTH_TOKEN = '__auth_token'

/**
* Initializes Keycloak instance and calls the provided callback function if successfully authenticated.
Expand All @@ -10,60 +10,60 @@ export const AUTH_TOKEN = "__auth_token";
const initKeycloak = (onAuthenticatedCallback: () => void) => {
_kc
.init({
onLoad: "login-required",
pkceMethod: "S256",
// checkLoginIframe: false,
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
})
.then((authenticated) => {
if (!authenticated) {
console.log("User is not authenticated.");
console.log('User is not authenticated.')
} else {
localStorage.setItem(AUTH_TOKEN, `${_kc.token}`);
localStorage.setItem(AUTH_TOKEN, `${_kc.token}`)
}
onAuthenticatedCallback();
onAuthenticatedCallback()
})
.catch(console.error);
.catch(console.error)

_kc.onTokenExpired = () => {
_kc.updateToken(5).then((refreshed) => {
if (refreshed) {
localStorage.setItem(AUTH_TOKEN, `${_kc.token}`);
localStorage.setItem(AUTH_TOKEN, `${_kc.token}`)
}
});
};
};
})
}
}

const doLogin = _kc.login;
const doLogin = _kc.login

const doLogout = _kc.logout;
const doLogout = _kc.logout

const getToken = () => _kc.token;
const getToken = () => _kc.token

const isLoggedIn = () => !!_kc.token;
const isLoggedIn = () => !!_kc.token

const updateToken = (
successCallback:
| ((value: boolean) => boolean | PromiseLike<boolean>)
| null
| undefined,
) => _kc.updateToken(5).then(successCallback).catch(doLogin);
) => _kc.updateToken(5).then(successCallback).catch(doLogin)

const getUsername = () => _kc.tokenParsed?.display_name;
const getUsername = () => _kc.tokenParsed?.display_name

/**
* Determines if a user's role(s) overlap with the role on the private route. The user's role is determined via jwt.client_roles
* @param roles
* @returns True or false, inidicating if the user has the role or not.
*/
const hasRole = (roles: any) => {
const jwt = _kc.tokenParsed;
const userroles = jwt?.client_roles;
const jwt = _kc.tokenParsed
const userroles = jwt?.client_roles
const includesRoles =
typeof roles === "string"
typeof roles === 'string'
? userroles?.includes(roles)
: roles.some((r: any) => userroles?.includes(r));
return includesRoles;
};
: roles.some((r: any) => userroles?.includes(r))
return includesRoles
}

const UserService = {
initKeycloak,
Expand All @@ -74,6 +74,6 @@ const UserService = {
updateToken,
getUsername,
hasRole,
};
}

export default UserService;
export default UserService
10 changes: 8 additions & 2 deletions frontend/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
"strictNullChecks": true,
"noEmit": true,
"jsx": "react-jsx",
"types": ["vitest/globals","cypress", "node", "cypress-file-upload","@testing-library/cypress"],
"types": [
"vitest/globals",
"cypress",
"node",
"cypress-file-upload",
"@testing-library/cypress"
],
"baseUrl": "./",
"paths": {
"@": ["src"],
Expand All @@ -26,6 +32,6 @@
"~/*": ["node_modules/*"]
}
},
"include": ["src","src/**/*", "src/**/*.tsx"],
"include": ["src", "src/**/*", "src/**/*.tsx"],
"references": [{ "path": "./tsconfig.node.json" }]
}

0 comments on commit eaacc55

Please sign in to comment.