Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix bug in protected routes components #377

Merged
merged 8 commits into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"react-feather": "^2.0.10",
"react-responsive": "^10.0.0",
"react-router-dom": "^6.26.2",
"vite-express": "0.16.0"
"vite-express": "0.16.0",
"zustand": "^5.0.2"
},
"devDependencies": {
"@types/react": "^18.3.2",
Expand Down
16 changes: 10 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@ const App = () => {
<Routes>
<Route element={<ProtectedRoute />}>
<Route path='/' element={<TeamOverview />} />
<Route path='/teammedlemmer' element={<TeamMembers />} />
<Route path='/teammedlemmer/:principalName' element={<UserProfile />} />
<Route path='/:teamId' element={<TeamDetail />} />
<Route path='/:teamId/:shortName' element={<SharedBucketDetail />} />
<Route path='/opprett-team' element={<ProtectedAuthorizedUserRoute component={<CreateTeamForm />} />} />
<Route path='/opprett-team/kvittering' element={<ProtectedAuthorizedUserRoute component={<TeamCreated />} />} />
<Route path='teammedlemmer' element={<TeamMembers />}>
<Route path=':principalName' element={<UserProfile />} />
</Route>
<Route path='opprett-team' element={<ProtectedAuthorizedUserRoute />}>
<Route path='' element={<CreateTeamForm />} />
<Route path='kvittering' element={<TeamCreated />} />
</Route>
<Route path=':teamId' element={<TeamDetail />}>
<Route path=':shortName' element={<SharedBucketDetail />} />
</Route>
<Route path='/not-found' element={<NotFound />} />
</Route>
</Routes>
Expand Down
46 changes: 30 additions & 16 deletions src/components/ProtectedAuthorizedUserRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,43 @@
import React, { useEffect, useState } from 'react'
import { useEffect, useState } from 'react'
import NotFound from '../pages/NotFound/NotFound.tsx'
import { User } from '../services/userProfile'
import { isAuthorizedToCreateTeam } from '../services/createTeam'
import { Effect } from 'effect'
import { Effect, Option as O } from 'effect'
import { isDaplaAdmin } from '../utils/services'
import { option } from '../utils/utils'
import { Skeleton } from '@mui/material'
import PageLayout from './PageLayout/PageLayout.tsx'
import { Outlet } from 'react-router-dom'
import { useUserProfileStore } from '../services/store.ts'

export interface Props {
component: React.ReactElement
}
const ProtectedAuthorizedUserRoute = () => {
// O.none() here represents the loading state
const [oIsAuthorized, setIsAuthorized] = useState<O.Option<boolean>>(O.none())
const maybeUser: O.Option<User> = useUserProfileStore((state) => state.loggedInUser)

const ProtectedAuthorizedUserRoute = ({ component }: Props) => {
const [isAuthorized, setIsAuthorized] = useState(false)
useEffect(() => {
const userProfileItem = localStorage.getItem('userProfile')
if (!userProfileItem) return
Effect.gen(function* () {
const user: User = yield* O.match(maybeUser, {
onNone: () => Effect.fail(new Error('User not logged in!')),
onSome: (user) => Effect.succeed(user),
})

const user = JSON.parse(userProfileItem) as User
if (!user) return
const daplaAdmin: boolean = yield* Effect.promise(() => isDaplaAdmin(user.principal_name))

Effect.promise(() => isDaplaAdmin(user.principal_name))
.pipe(Effect.runPromise)
.then((isDaplaAdmin: boolean) => setIsAuthorized(isAuthorizedToCreateTeam(isDaplaAdmin, user.job_title)))
}, [])
yield* Effect.sync(() => setIsAuthorized(O.some(isAuthorizedToCreateTeam(daplaAdmin, user.job_title))))
}).pipe(Effect.runPromise)
})

return isAuthorized ? component : <NotFound />
return option(
oIsAuthorized,
() => (
<PageLayout
title='Opprett Team'
content={<Skeleton variant='rectangular' animation='wave' width={800} height={600} />}
/>
),
(isAuthorized) => (isAuthorized ? <Outlet /> : <NotFound />)
)
}

export default ProtectedAuthorizedUserRoute
32 changes: 18 additions & 14 deletions src/components/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,28 @@ import { fetchUserInformationFromAuthToken } from '../utils/services'
import { Cause, Effect, Option as O } from 'effect'
import { customLogger } from '../utils/logger.ts'
import { ApiError } from '../utils/services.ts'
import { useUserProfileStore } from '../services/store.ts'

import { User } from '../services/userProfile.ts'

const ProtectedRoute = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const setUser = useUserProfileStore((state) => state.setUser)
const navigate = useNavigate()
const from = location.pathname

const fetchUserProfile = (): Effect.Effect<void, Cause.UnknownException | ApiError> =>
Effect.gen(function* () {
const userProfileData = yield* Effect.promise(fetchUserInformationFromAuthToken)
const userProfile = yield* Effect.tryPromise(() => getUserProfile(userProfileData.email)).pipe(
Effect.flatMap((x) => (x instanceof ApiError ? Effect.fail(x) : Effect.succeed(x))),
Effect.map(JSON.stringify)
)
yield* Effect.logInfo(`UserProfile set in localStorage: ${userProfile}`)
yield* Effect.sync(() => localStorage.setItem('userProfile', userProfile))
yield* Effect.sync(() => setIsAuthenticated(true))
}).pipe(Effect.provide(customLogger))

useEffect(() => {
const fetchUserProfile = (): Effect.Effect<void, Cause.UnknownException | ApiError> =>
Effect.gen(function* () {
const userProfileData = yield* Effect.promise(fetchUserInformationFromAuthToken)
const userProfile = yield* Effect.tryPromise(() => getUserProfile(userProfileData.email)).pipe(
Effect.flatMap((x) => (x instanceof ApiError ? Effect.fail(x) : Effect.succeed(x)))
)
yield* Effect.sync(() => localStorage.setItem('userProfile', JSON.stringify(userProfile)))
yield* Effect.sync(() => setUser(userProfile))
yield* Effect.sync(() => setIsAuthenticated(true))
}).pipe(Effect.provide(customLogger))

const cachedUserProfile: O.Option<User> = O.fromNullable(localStorage.getItem('userProfile')).pipe(
O.flatMap(O.liftThrowable(JSON.parse))
)
Expand All @@ -34,13 +35,16 @@ const ProtectedRoute = () => {
onSome: (userProfile) =>
// invalidate cached user profile if 'job_title' field is missing
userProfile.job_title
? Effect.sync(() => setIsAuthenticated(true))
? Effect.zip(
Effect.sync(() => setIsAuthenticated(true)),
Effect.sync(() => setUser(userProfile))
)
: Effect.zipRight(
Effect.logInfo("'job_title' field missing, invalidating UserProfile cache"),
fetchUserProfile()
).pipe(Effect.provide(customLogger)),
}).pipe(Effect.runPromise)
}, [from, navigate])
}, [from, navigate, setUser])

return isAuthenticated ? <Outlet /> : null
}
Expand Down
28 changes: 28 additions & 0 deletions src/services/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import { User } from '../services/userProfile.ts'
import { Effect, Option as O } from 'effect'

import { customLogger } from '../utils/logger.ts'

type UserProfileStoreState = {
loggedInUser: O.Option<User>
}

type UserProfileStoreActions = {
setUser: (user: User) => void
}

export type UserProfileStore = UserProfileStoreState & UserProfileStoreActions

export const useUserProfileStore = create<UserProfileStore>()(
subscribeWithSelector((set) => ({
loggedInUser: O.none(),
setUser: (user: User) => set(() => ({ loggedInUser: O.some(user) })),
}))
)

useUserProfileStore.subscribe(
(state) => state.loggedInUser,
(user) => Effect.log('USER LOGGED IN:', O.getOrNull(user)).pipe(Effect.provide(customLogger), Effect.runPromise)
)
Loading