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

Feature/manage global user tokens UI #994

Merged
merged 7 commits into from
Jan 5, 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
42 changes: 37 additions & 5 deletions frontend/actions/user.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import qs from 'querystring'
import useSWR from 'swr'
import { EntityObject } from 'types/v2/types'
import { EntityObject, ModelInterface, TokenActionsKeys, TokenInterface, TokenScopeKeys, User } from 'types/v2/types'

import { ErrorInfo, fetcher } from '../utils/fetcher'

Expand Down Expand Up @@ -28,13 +28,11 @@ export function useListUsers(q: string) {
}

interface UserResponse {
user: {
dn: string
}
user: User
}

export function useGetCurrentUser() {
const { data, error, mutate } = useSWR<UserResponse, ErrorInfo>(`/api/v2/entities/me`, fetcher)
const { data, error, mutate } = useSWR<UserResponse, ErrorInfo>('/api/v2/entities/me', fetcher)

return {
mutateCurrentUser: mutate,
Expand All @@ -43,3 +41,37 @@ export function useGetCurrentUser() {
isCurrentUserError: error,
}
}

interface GetUserTokensResponse {
tokens: TokenInterface[]
}

export function useGetUserTokens() {
const { data, error, mutate } = useSWR<GetUserTokensResponse, ErrorInfo>('/api/v2/user/tokens', fetcher)

return {
mutateTokens: mutate,
tokens: data?.tokens || [],
isTokensLoading: !error && !data,
isTokensError: error,
}
}

export function postUserToken(
description: string,
scope: TokenScopeKeys,
modelIds: ModelInterface['id'][],
actions: TokenActionsKeys[],
) {
return fetch('/api/v2/user/tokens', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description, scope, modelIds, actions }),
})
}

export function deleteUserToken(accessKey: TokenInterface['accessKey']) {
return fetch(`/api/v2/user/token/${accessKey}`, {
method: 'delete',
})
}
2 changes: 1 addition & 1 deletion frontend/cypress/e2e/beta/push-image-registry.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('Make and approve an access request', () => {
cy.contains('Pushing an Image for this Model')

cy.log('Fetching the docker login password and running all the docker commands to push an image')
cy.get('[data-test=showTokenButton]').click()
cy.get('[data-test=regenerateTokenButton]').click()
cy.get('[data-test=dockerPassword]').should('not.contain.text', 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx')
cy.get('[data-test=dockerPassword]')
.invoke('text')
Expand Down
35 changes: 35 additions & 0 deletions frontend/pages/beta/settings/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useGetCurrentUser } from 'actions/user'
import { useMemo } from 'react'
import Loading from 'src/common/Loading'
import PageWithTabs from 'src/common/PageWithTabs'
import MultipleErrorWrapper from 'src/errors/MultipleErrorWrapper'
import AuthenticationTab from 'src/settings/beta/authentication/AuthenticationTab'
import ProfileTab from 'src/settings/beta/ProfileTab'
import Wrapper from 'src/Wrapper.beta'

export default function Settings() {
const { currentUser, isCurrentUserLoading, isCurrentUserError } = useGetCurrentUser()

const tabs = useMemo(
() =>
currentUser
? [
{ title: 'Profile', path: 'profile', view: <ProfileTab user={currentUser} /> },
{ title: 'Authentication', path: 'authentication', view: <AuthenticationTab /> },
]
: [],
[currentUser],
)

const error = MultipleErrorWrapper(`Unable to load settings page`, {
isCurrentUserError,
})
if (error) return error

return (
<Wrapper fullWidth title='Settings' page='settings'>
{isCurrentUserLoading && <Loading />}
<PageWithTabs title='Settings' tabs={tabs} />
</Wrapper>
)
}
210 changes: 210 additions & 0 deletions frontend/pages/beta/settings/personal-access-tokens/new.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import { ArrowBack } from '@mui/icons-material'
import { LoadingButton } from '@mui/lab'
import {
Button,
Card,
Checkbox,
Container,
FormControl,
FormControlLabel,
Grid,
Stack,
TextField,
Typography,
} from '@mui/material'
import { useListModels } from 'actions/model'
import { postUserToken } from 'actions/user'
import { ChangeEvent, useCallback, useEffect, useMemo, useState } from 'react'
import Loading from 'src/common/Loading'
import Link from 'src/Link'
import MessageAlert from 'src/MessageAlert'
import TokenDialog from 'src/settings/beta/authentication/TokenDialog'
import Wrapper from 'src/Wrapper.beta'
import { TokenActions, TokenActionsKeys, TokenInterface, TokenScope } from 'types/v2/types'
import { getErrorMessage } from 'utils/fetcher'

export default function NewToken() {
const [description, setDescription] = useState('')
const [isAllModels, setIsAllModels] = useState(false)
const [selectedModels, setSelectedModels] = useState<string[]>([])
const [selectedActions, setSelectedActions] = useState<TokenActionsKeys[]>([])
const [isLoading, setIsLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [token, setToken] = useState<TokenInterface | undefined>()

const { models, isModelsLoading, isModelsError } = useListModels([])

useEffect(() => {
const areAllModelsSelected = selectedModels.length === models.length
if (!isAllModels && areAllModelsSelected) {
setIsAllModels(true)
} else if (isAllModels && !areAllModelsSelected) {
setIsAllModels(false)
}
}, [isAllModels, models.length, selectedModels.length])

const handleSelectedModelsChange = useCallback(
(modelId: string, checked: boolean) => {
if (checked) {
setSelectedModels([...selectedModels, modelId])
} else {
const foundIndex = selectedModels.findIndex((selectedModel) => selectedModel === modelId)
if (foundIndex >= 0) {
const updatedSelectedModels = [...selectedModels]
updatedSelectedModels.splice(foundIndex, 1)
setSelectedModels(updatedSelectedModels)
}
}
},
[selectedModels],
)

const modelCheckboxes = useMemo(
() =>
models.map((model) => (
<Grid item xs={6} key={model.id}>
<FormControl>
<FormControlLabel
control={
<Checkbox
name={model.name}
checked={selectedModels.includes(model.id)}
onChange={(_event, checked) => handleSelectedModelsChange(model.id, checked)}
/>
}
label={model.name}
/>
</FormControl>
</Grid>
)),
[handleSelectedModelsChange, models, selectedModels],
)

const handleSelectedActionsChange = useCallback(
(action: TokenActionsKeys, checked: boolean) => {
if (checked) {
setSelectedActions([...selectedActions, action])
} else {
const foundIndex = selectedActions.findIndex((selectedRepository) => selectedRepository === action)
if (foundIndex >= 0) {
const updatedSelectedActions = [...selectedActions]
updatedSelectedActions.splice(foundIndex, 1)
setSelectedActions(updatedSelectedActions)
}
}
},
[selectedActions],
)

const actionCheckboxes = useMemo(
() =>
Object.values(TokenActions).map((action) => (
<Grid item xs={6} key={action}>
<FormControl>
<FormControlLabel
control={
<Checkbox
name={action}
checked={selectedActions.includes(action)}
onChange={(_event, checked) => handleSelectedActionsChange(action, checked)}
/>
}
label={action}
/>
</FormControl>
</Grid>
)),
[handleSelectedActionsChange, selectedActions],
)

const handleDescriptionChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
setDescription(event.target.value)
}

const handleAllSelectedModelsChange = (_event: ChangeEvent<HTMLInputElement>, checked: boolean) => {
setIsAllModels(checked)
setSelectedModels(checked ? models.map((model) => model.id) : [])
}

const handleSubmit = async () => {
setIsLoading(true)
const scope = isAllModels ? TokenScope.All : TokenScope.Models
const modelIds = isAllModels ? [] : selectedModels
const response = await postUserToken(description, scope, modelIds, selectedActions)

if (!response.ok) {
setErrorMessage(await getErrorMessage(response))
} else {
const { token } = await response.json()
setToken(token)
}

setIsLoading(false)
}

return (
<Wrapper title='Personal Access Token' page='Token'>
<Container maxWidth='md'>
<Card sx={{ my: 4, p: 4 }}>
<Stack spacing={2}>
<Link href={'/beta/settings?tab=authentication&category=personal'}>
<Button startIcon={<ArrowBack />}>Back to settings</Button>
</Link>
<Stack spacing={2}>
<Stack>
<Typography fontWeight='bold'>
Description <span style={{ color: 'red' }}>*</span>
</Typography>
<TextField
required
multiline
size='small'
value={description}
onChange={handleDescriptionChange}
inputProps={{ 'data-test': 'tokenDescriptionTextField' }}
/>
</Stack>
<Stack>
<Typography fontWeight='bold'>
Models <span style={{ color: 'red' }}>*</span>
</Typography>
{isModelsLoading ? (
<Loading />
) : (
<>
<FormControl>
<FormControlLabel
control={<Checkbox name='All' checked={isAllModels} onChange={handleAllSelectedModelsChange} />}
label='All'
/>
</FormControl>
<Grid container>{modelCheckboxes}</Grid>
</>
)}
</Stack>
<Stack>
<Typography fontWeight='bold'>
Actions <span style={{ color: 'red' }}>*</span>
</Typography>
<Grid container>{actionCheckboxes}</Grid>
</Stack>
<Stack alignItems='flex-end'>
<LoadingButton
variant='contained'
loading={isLoading}
disabled={!description || !selectedModels.length || !selectedActions.length}
onClick={handleSubmit}
data-test='generatePersonalAccessTokenButton'
>
Generate Token
</LoadingButton>
<MessageAlert message={isModelsError?.info.message || errorMessage} severity='error' />
</Stack>
</Stack>
</Stack>
</Card>
</Container>
<TokenDialog token={token} />
</Wrapper>
)
}
4 changes: 2 additions & 2 deletions frontend/src/Form/beta/EditableFormHeading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ export default function EditableFormHeading({
return (
<Stack sx={{ pb: 2 }}>
<Stack
direction={{ sx: 'column', sm: 'row' }}
justifyContent={{ sx: 'center', sm: 'space-between' }}
direction={{ xs: 'column', sm: 'row' }}
justifyContent={{ xs: 'center', sm: 'space-between' }}
alignItems='center'
spacing={2}
>
Expand Down
10 changes: 8 additions & 2 deletions frontend/src/common/PageWithTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { grey } from '@mui/material/colors/'
import { useTheme } from '@mui/material/styles'
import { useRouter } from 'next/router'
import { ParsedUrlQuery } from 'querystring'
import { ReactElement, SyntheticEvent, useContext, useState } from 'react'
import { ReactElement, SyntheticEvent, useContext, useEffect, useState } from 'react'
import UnsavedChangesContext from 'src/contexts/unsavedChangesContext'

export interface PageTab {
Expand Down Expand Up @@ -31,7 +31,13 @@ export default function PageWithTabs({
}) {
const router = useRouter()
const { tab } = router.query
const [currentTab, setCurrentTab] = useState(tabs.find((pageTab) => pageTab.path === tab) ? `${tab}` : tabs[0].path)

const [currentTab, setCurrentTab] = useState('')

useEffect(() => {
if (!tabs.length) return
setCurrentTab(tabs.find((pageTab) => pageTab.path === tab) ? `${tab}` : tabs[0].path)
}, [tab, tabs])

const { unsavedChanges, setUnsavedChanges, sendWarning } = useContext(UnsavedChangesContext)

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/model/beta/AccessRequests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default function AccessRequests({ model }: AccessRequestsProps) {
}

return (
<Box sx={{ maxWidth: '900px', mx: 'auto', my: 4 }}>
<Box sx={{ maxWidth: 'md', mx: 'auto', my: 4 }}>
<Stack spacing={4}>
<Box sx={{ textAlign: 'right' }}>
<Link href={`/beta/model/${model.id}/access-request/schema`}>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/model/beta/ModelImages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export default function ModelImages({ model }: AccessRequestsProps) {
return (
<>
{isModelImagesLoading && <Loading />}
<Box sx={{ maxWidth: '900px', mx: 'auto', my: 4 }}>
<Box sx={{ maxWidth: 'md', mx: 'auto', my: 4 }}>
<Stack spacing={4}>
<Box sx={{ textAlign: 'right' }}>
<Button
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/model/beta/Releases.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default function Releases({ model }: { model: ModelInterface }) {
}

return (
<Box sx={{ maxWidth: '900px', mx: 'auto', my: 4 }}>
<Box sx={{ maxWidth: 'md', mx: 'auto', my: 4 }}>
<Stack spacing={4}>
<Box sx={{ textAlign: 'right' }}>
<Button
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/model/beta/overview/FormEditPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ export default function FormEditPage({ model }: FormEditPageProps) {
{isSchemaLoading && <Loading />}
<Box sx={{ py: 1 }}>
<Stack
direction={{ sx: 'column', sm: 'row' }}
justifyContent={{ sx: 'center', sm: 'space-between' }}
direction={{ xs: 'column', sm: 'row' }}
justifyContent={{ xs: 'center', sm: 'space-between' }}
alignItems='center'
sx={{ pb: 2 }}
>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/model/beta/overview/TemplatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type TemplatePageProps = {

export default function TemplatePage({ model }: TemplatePageProps) {
return (
<Box sx={{ maxWidth: '900px', mx: 'auto', my: 4 }}>
<Box sx={{ maxWidth: 'md', mx: 'auto', my: 4 }}>
<Stack spacing={4} justifyContent='center' alignItems='center'>
<Typography component='h2' variant='h6' color='primary' data-test='createModelCardOverview'>
Create a model card
Expand Down
Loading