Skip to content

Commit

Permalink
feat: back to using authenticated user data from dataverse
Browse files Browse the repository at this point in the history
  • Loading branch information
g-saracca committed Oct 14, 2024
1 parent 819196c commit 78828e8
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 103 deletions.
8 changes: 4 additions & 4 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ const authConfig: TAuthConfig = {
}

const userRepository = new UserJSDataverseRepository()

function App() {
console.log({ authConfig })
return (
<AuthProvider authConfig={authConfig}>
<SessionProvider repository={userRepository}>
Expand Down
31 changes: 12 additions & 19 deletions src/sections/layout/header/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { useContext } from 'react'
import { AuthContext } from 'react-oauth2-code-pkce'
import dataverse_logo from '../../../assets/dataverse_brand_icon.svg'
import { useLocation } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Button, Navbar } from '@iqss/dataverse-design-system'
import { Route } from '../../Route.enum'
// import { DATAVERSE_BACKEND_URL } from '../../../config'
import dataverse_logo from '@/assets/dataverse_brand_icon.svg'
import { Route } from '@/sections/Route.enum'
import { useSession } from '@/sections/session/SessionContext'
import { LoggedInHeaderActions } from './LoggedInHeaderActions'
import { CollectionJSDataverseRepository } from '../../../collection/infrastructure/repositories/CollectionJSDataverseRepository'
import { CollectionJSDataverseRepository } from '@/collection/infrastructure/repositories/CollectionJSDataverseRepository'
import styles from './Header.module.scss'
import { useLocation } from 'react-router-dom'

const collectionRepository = new CollectionJSDataverseRepository()

export function Header() {
const { t } = useTranslation('header')
const { user } = useSession()
const { pathname } = useLocation()

// TODO:ME tokenData is originally typed as Record<string, any> but we know it has a name property (this will need a double check in future iterations)
const { token, tokenData, logIn: oidcLogin } = useContext(AuthContext)
const { logIn: oidcLogin } = useContext(AuthContext)

const handleOidcLogIn = () => {
oidcLogin(encodeURIComponent(pathname))
Expand All @@ -31,19 +31,12 @@ export function Header() {
logoImgSrc: dataverse_logo
}}
className={styles.navbar}>
{token && tokenData ? (
<LoggedInHeaderActions
userName={tokenData?.name as string}
collectionRepository={collectionRepository}
/>
{user ? (
<LoggedInHeaderActions user={user} collectionRepository={collectionRepository} />
) : (
<>
<Button onClick={handleOidcLogIn} variant="link" className={styles['login-btn']}>
OIDC {t('logIn')}
</Button>
{/* <Navbar.Link href={`${DATAVERSE_BACKEND_URL}${Route.LOG_IN}`}>{t('logIn')}</Navbar.Link> */}
{/* <Navbar.Link href={`${DATAVERSE_BACKEND_URL}${Route.SIGN_UP}`}>{t('signUp')}</Navbar.Link> */}
</>
<Button onClick={handleOidcLogIn} variant="link" className={styles['login-btn']}>
OIDC {t('logIn')}
</Button>
)}
</Navbar>
)
Expand Down
34 changes: 10 additions & 24 deletions src/sections/layout/header/LoggedInHeaderActions.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
import { useContext } from 'react'
import { AuthContext } from 'react-oauth2-code-pkce'
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from 'react-router-dom'
import { Link } from 'react-router-dom'
import { Navbar } from '@iqss/dataverse-design-system'
import { useGetCollectionUserPermissions } from '../../../shared/hooks/useGetCollectionUserPermissions'
import { useSession } from '../../session/SessionContext'
import { RouteWithParams, Route } from '../../Route.enum'
import { CollectionRepository } from '../../../collection/domain/repositories/CollectionRepository'
import { ROOT_COLLECTION_ALIAS } from '../../../collection/domain/models/Collection'
import { AccountHelper } from '../../account/AccountHelper'

const currentPage = 0
import { User } from '@/users/domain/models/User'
import { useGetCollectionUserPermissions } from '@/shared/hooks/useGetCollectionUserPermissions'
import { RouteWithParams, Route } from '@/sections//Route.enum'
import { CollectionRepository } from '@/collection/domain/repositories/CollectionRepository'
import { ROOT_COLLECTION_ALIAS } from '@/collection/domain/models/Collection'
import { AccountHelper } from '@/sections/account/AccountHelper'

interface LoggedInHeaderActionsProps {
userName: string
user: User
collectionRepository: CollectionRepository
}

export const LoggedInHeaderActions = ({
userName,
user,
collectionRepository
}: LoggedInHeaderActionsProps) => {
const { t } = useTranslation('header')
const { logout } = useSession()
const navigate = useNavigate()

const { logOut: oidcLogout } = useContext(AuthContext)

Expand All @@ -32,17 +28,10 @@ export const LoggedInHeaderActions = ({
collectionRepository: collectionRepository
})

// Just keeping logOut in a handler function because we might want to add more logic here (e.g: logOut can receive up to 3 parameters)
const handleOidcLogout = () => {
oidcLogout()
}

const _handleSessionLogout = () => {
void logout().then(() => {
navigate(currentPage)
})
}

const createCollectionRoute = RouteWithParams.CREATE_COLLECTION()
const createDatasetRoute = RouteWithParams.CREATE_DATASET()

Expand All @@ -62,7 +51,7 @@ export const LoggedInHeaderActions = ({
{t('navigation.newDataset')}
</Navbar.Dropdown.Item>
</Navbar.Dropdown>
<Navbar.Dropdown title={userName} id="dropdown-user">
<Navbar.Dropdown title={user.displayName} id="dropdown-user">
<Navbar.Dropdown.Item
as={Link}
to={`${Route.ACCOUNT}?${AccountHelper.ACCOUNT_PANEL_TAB_QUERY_KEY}=${AccountHelper.ACCOUNT_PANEL_TABS_KEYS.apiToken}`}>
Expand All @@ -71,9 +60,6 @@ export const LoggedInHeaderActions = ({
<Navbar.Dropdown.Item href="#" onClick={handleOidcLogout}>
OIDC {t('logOut')}
</Navbar.Dropdown.Item>
{/* <Navbar.Dropdown.Item href="#" onClick={handleSessionLogout}>
{t('logOut')}
</Navbar.Dropdown.Item> */}
</Navbar.Dropdown>
</>
)
Expand Down
60 changes: 5 additions & 55 deletions src/sections/session/SessionProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,66 +6,14 @@ import { getUser } from '../../users/domain/useCases/getUser'
import { UserRepository } from '../../users/domain/repositories/UserRepository'
import { logOut } from '../../users/domain/useCases/logOut'

const BACKEND_URL = import.meta.env.VITE_DATAVERSE_BACKEND_URL as string

interface SessionProviderProps {
repository: UserRepository
}
export function SessionProvider({ repository, children }: PropsWithChildren<SessionProviderProps>) {
const { token, tokenData } = useContext(AuthContext)
const { token, loginInProgress } = useContext(AuthContext)
const [user, setUser] = useState<User | null>(null)
const [isLoadingUser, setIsLoadingUser] = useState<boolean>(true)

useEffect(() => {
// Just to log some data from the AuthContext
console.log(
'%cToken from AuthContext: ',
'background: green; color: white; padding: 2px; border-radius: 2px;',
{
token
}
)

console.log(
'%cTokenData from AuthContext: ',
'background: green; color: white; padding: 2px; border-radius: 2px;',
tokenData
)
}, [token, tokenData])

useEffect(() => {
if (token) {
fetch(`${BACKEND_URL}/api/v1/users/:me`, {
method: 'GET',
credentials: 'omit', // to avoid sending the cookie
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
// 👇 And this throws BAD API key because its a token not an api key of course
// 'X-Dataverse-key': token
}
})
.then((response) => {
if (!response.ok) {
return response.json().then((errData: Error) => {
throw new Error(`Error ${response.status}: ${errData.message || response.statusText}`)
})
}
return response.json()
})
.then((data) => {
console.log('User data:', data)
})
.catch((error) => {
console.error(
'%cError getting user data with users/:me endpoint',
'background: #eb5656; color: white; padding: 2px',
error
)
})
}
}, [token])

useEffect(() => {
const handleGetUser = async () => {
setIsLoadingUser(true)
Expand All @@ -80,8 +28,10 @@ export function SessionProvider({ repository, children }: PropsWithChildren<Sess
}
}

void handleGetUser()
}, [repository])
if (token && !loginInProgress) {
void handleGetUser()
}
}, [repository, token, loginInProgress])

const submitLogOut = () => {
return logOut(repository)
Expand Down

0 comments on commit 78828e8

Please sign in to comment.