Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
126 changes: 126 additions & 0 deletions src/components/DeleteGiteaUsersModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { Alert, Box, Button, Typography } from '@mui/material'
import EnhancedTable, { HeadCell } from 'components/EnhancedTable'
import Modal from 'components/Modal'
import { DeleteGiteaUsersApiResponse, useDeleteGiteaUsersMutation } from 'redux/otomiApi'

type GiteaUserResult = DeleteGiteaUsersApiResponse['results'][number]

const repoList = (result: GiteaUserResult) => result.repos?.join(', ') || '-'

const previewHeadCells: HeadCell[] = [
{ id: 'username', label: 'Username' },
{ id: 'email', label: 'Email' },
{ id: 'repos', label: 'Personal repositories', renderer: repoList },
]
const resultHeadCells: HeadCell[] = [
{ id: 'username', label: 'Username' },
{ id: 'status', label: 'Status' },
{
id: 'repos',
label: 'Repositories / error',
renderer: (result: GiteaUserResult) => result.error ?? repoList(result),
},
]

interface Props {
open: boolean
handleClose: () => void
}

export default function DeleteGiteaUsersModal({ open, handleClose }: Props) {
const [previewUsers, preview] = useDeleteGiteaUsersMutation()
const [deleteUsers, deletion] = useDeleteGiteaUsersMutation()

const close = () => {
preview.reset()
deletion.reset()
handleClose()
}

const closeUnlessBackdropClick = (_event: unknown, reason?: string) => {
if (reason !== 'backdropClick') close()
}

const startPreview = () => {
if (preview.isLoading) return
previewUsers({ dryRun: true }).unwrap().catch(close)
}

const startDeletion = () => {
if (deletion.isLoading) return
deleteUsers({ dryRun: false }).unwrap().catch(close)
}

if (deletion.data) {
return (
<Modal open={open} title='Deleted Gitea users' handleClose={closeUnlessBackdropClick} width={720} noFooter>
<UserTable headCells={resultHeadCells} results={deletion.data.results} />
<DoneButton onClick={close} />
</Modal>
)
}

if (preview.data) {
const users = preview.data.results
if (users.length === 0) {
return (
<Modal open={open} title='Delete Gitea users' handleClose={close} width={720} noFooter>
<Typography>There are no Gitea users to delete.</Typography>
<DoneButton onClick={close} />
</Modal>
)
}
return (
<Modal
open={open}
title='Delete Gitea users'
handleClose={closeUnlessBackdropClick}
width={720}
handleAction={startDeletion}
actionButtonText={deletion.isLoading ? 'Deleting...' : `Delete ${users.length} users`}
actionButtonColor='error'
>
<Alert severity='warning'>
These users and their personal repositories will be permanently deleted. Team organizations and team
repositories are not affected.
</Alert>
<UserTable headCells={previewHeadCells} results={users} />
</Modal>
)
}

return (
<Modal
open={open}
title='Delete Gitea users'
handleClose={close}
handleAction={startPreview}
actionButtonText={preview.isLoading ? 'Loading...' : 'Show users'}
actionButtonColor='primary'
>
<Typography>
Users who used Gitea with Keycloak cannot log in to Gitea with Dex until their old Gitea account is deleted.
This deletes every Gitea user, together with their personal repositories. The built-in admin and otomi-admin
accounts and the organization service accounts are kept. You first see which users will be deleted.
</Typography>
</Modal>
)
}

function UserTable({ headCells, results }: { headCells: HeadCell[]; results: GiteaUserResult[] }) {
return (
<Box sx={{ mt: 2 }}>
<EnhancedTable disableSelect headCells={headCells} rows={results} idKey='username' orderByStart='username' />
</Box>
)
}

function DoneButton({ onClick }: { onClick: () => void }) {
return (
<Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
<Button variant='contained' onClick={onClick}>
Done
</Button>
</Box>
)
}
121 changes: 120 additions & 1 deletion src/pages/Maintenance.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import { ReactNode } from 'react'
import { MemoryRouter, Route } from 'react-router-dom'
import ObjAppModal from 'components/ObjAppModal'
import { useSession } from 'providers/Session'
import { useCreateObjWizardMutation, useGetSettingsQuery, useImportKeycloakUsersMutation } from 'redux/otomiApi'
import {
useCreateObjWizardMutation,
useDeleteGiteaUsersMutation,
useGetSettingsQuery,
useImportKeycloakUsersMutation,
} from 'redux/otomiApi'
import palette from 'theme/palette'
import Maintenance from './Maintenance'

Expand All @@ -16,6 +21,7 @@ jest.mock('redux/otomiApi', () => ({
useCreateObjWizardMutation: jest.fn(),
useGetSettingsQuery: jest.fn(),
useImportKeycloakUsersMutation: jest.fn(),
useDeleteGiteaUsersMutation: jest.fn(),
}))

jest.mock(
Expand Down Expand Up @@ -71,6 +77,7 @@ describe('Maintenance Object Storage wizard', () => {
;(useGetSettingsQuery as jest.Mock).mockReturnValue({ data: { obj: {} } })
;(useCreateObjWizardMutation as jest.Mock).mockReturnValue([create])
;(useImportKeycloakUsersMutation as jest.Mock).mockReturnValue([jest.fn(), { reset: jest.fn() }])
;(useDeleteGiteaUsersMutation as jest.Mock).mockReturnValue([jest.fn(), { reset: jest.fn() }])
})

afterEach(() => {
Expand Down Expand Up @@ -179,6 +186,7 @@ describe('Maintenance Keycloak user import', () => {
;(useCreateObjWizardMutation as jest.Mock).mockReturnValue([jest.fn()])
importKeycloakUsers.mockReturnValue({ unwrap: () => Promise.resolve() })
;(useImportKeycloakUsersMutation as jest.Mock).mockReturnValue([importKeycloakUsers, { reset: jest.fn() }])
;(useDeleteGiteaUsersMutation as jest.Mock).mockReturnValue([jest.fn(), { reset: jest.fn() }])
})

it.each([
Expand Down Expand Up @@ -226,3 +234,114 @@ describe('Maintenance Keycloak user import', () => {
expect(screen.getByText(/will not be shown again/)).toBeInTheDocument()
})
})

describe('Maintenance Gitea user deletion', () => {
const previewUsers = jest.fn()
const deleteUsers = jest.fn()
const previewData = {
dryRun: true,
results: [
{ username: 'alice', email: 'alice@example.com', repos: ['alice/notes'], status: 'dry-run' },
{ username: 'bob', email: 'bob@example.com', repos: [], status: 'dry-run' },
],
}

function mockSession({ authenticationLayer = 'dex', keycloak = true, gitea = true } = {}) {
;(useSession as jest.Mock).mockReturnValue({
user: { isPlatformAdmin: true },
appsEnabled: { keycloak, gitea },
settings: { otomi: { oidc: { authenticationLayer } } },
objectStorage: { showWizard: false, objStorageRegions: [] },
})
}

// The modal calls the hook twice per render: first for the preview, then for the deletion
function mockMutations(previewState = {}, deletionState = {}) {
let calls = 0
;(useDeleteGiteaUsersMutation as jest.Mock).mockImplementation(() => {
calls += 1
return calls % 2 === 1
? [previewUsers, { reset: jest.fn(), ...previewState }]
: [deleteUsers, { reset: jest.fn(), ...deletionState }]
})
}

beforeEach(() => {
jest.clearAllMocks()
;(useGetSettingsQuery as jest.Mock).mockReturnValue({ data: { obj: {} } })
;(useCreateObjWizardMutation as jest.Mock).mockReturnValue([jest.fn()])
;(useImportKeycloakUsersMutation as jest.Mock).mockReturnValue([jest.fn(), { reset: jest.fn() }])
previewUsers.mockReturnValue({ unwrap: () => Promise.resolve() })
deleteUsers.mockReturnValue({ unwrap: () => Promise.resolve() })
;(useDeleteGiteaUsersMutation as jest.Mock).mockReturnValue([jest.fn(), { reset: jest.fn() }])
})

it('hides the action when Gitea is disabled', () => {
mockSession({ gitea: false })

renderMaintenance()

expect(screen.queryByRole('button', { name: 'Delete Gitea users' })).not.toBeInTheDocument()
})

it.each([
['Keycloak is the authentication layer', { authenticationLayer: 'keycloak' }],
['Keycloak is disabled', { keycloak: false }],
])('shows the action when Gitea is enabled, also when %s', (_case, session) => {
mockSession(session)

renderMaintenance()

expect(screen.getByRole('button', { name: 'Delete Gitea users' })).toBeInTheDocument()
})

it('asks for a dry run first', () => {
mockSession()
mockMutations()

renderMaintenance()
fireEvent.click(screen.getByRole('button', { name: 'Delete Gitea users' }))
fireEvent.click(screen.getByRole('button', { name: 'Show users' }))

expect(previewUsers).toHaveBeenCalledWith({ dryRun: true })
expect(deleteUsers).not.toHaveBeenCalled()
})

it('lists the users and their personal repositories, then deletes them after confirming', () => {
mockSession()
mockMutations({ data: previewData })

renderMaintenance()
fireEvent.click(screen.getByRole('button', { name: 'Delete Gitea users' }))

expect(screen.getByText('alice@example.com')).toBeInTheDocument()
expect(screen.getByText('alice/notes')).toBeInTheDocument()

fireEvent.click(screen.getByRole('button', { name: 'Delete 2 users' }))

expect(deleteUsers).toHaveBeenCalledWith({ dryRun: false })
})

it('shows the status of each user and the error of failed users', () => {
mockSession()
mockMutations(
{ data: previewData },
{
data: {
dryRun: false,
results: [
{ username: 'alice', email: 'alice@example.com', repos: ['alice/notes'], status: 'deleted' },
{ username: 'bob', email: 'bob@example.com', status: 'failed', error: 'user is last owner of org' },
],
},
},
)

renderMaintenance()
fireEvent.click(screen.getByRole('button', { name: 'Delete Gitea users' }))

expect(screen.getByText('Deleted Gitea users')).toBeInTheDocument()
expect(screen.getByText('deleted')).toBeInTheDocument()
expect(screen.getByText('user is last owner of org')).toBeInTheDocument()
})
})
14 changes: 14 additions & 0 deletions src/pages/Maintenance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useLocalStorage } from 'react-use'
import { useGetSettingsQuery } from 'redux/otomiApi'
import Section from 'components/Section'
import ImportKeycloakUsersModal from 'components/ImportKeycloakUsersModal'
import DeleteGiteaUsersModal from 'components/DeleteGiteaUsersModal'
import { useSession } from 'providers/Session'

const classes = {
Expand All @@ -26,8 +27,10 @@ const classes = {
export default function (): React.ReactElement {
const [, setShowObjWizard] = useLocalStorage<boolean>('showObjWizard')
const [showImportKeycloakUsers, setShowImportKeycloakUsers] = useState(false)
const [showDeleteGiteaUsers, setShowDeleteGiteaUsers] = useState(false)
const { appsEnabled, settings } = useSession()
const canImportKeycloakUsers = settings?.otomi?.oidc?.authenticationLayer === 'dex' && appsEnabled?.keycloak
const canDeleteGiteaUsers = appsEnabled?.gitea
const { data } = useGetSettingsQuery({ ids: ['obj'] })
const isObjStorageConfigured = (): boolean => {
const linode: any = data?.obj?.provider?.type === 'linode' ? data.obj.provider.linode : {}
Expand Down Expand Up @@ -70,9 +73,20 @@ export default function (): React.ReactElement {
Import Keycloak users into Dex
</Button>
)}
{canDeleteGiteaUsers && (
<Button
variant='text'
color='primary'
sx={{ ...classes.actionButton, display: 'block' }}
onClick={() => setShowDeleteGiteaUsers(true)}
>
Delete Gitea users
</Button>
)}
</Section>
<ObjWizardModal />
<ImportKeycloakUsersModal open={showImportKeycloakUsers} handleClose={() => setShowImportKeycloakUsers(false)} />
<DeleteGiteaUsersModal open={showDeleteGiteaUsers} handleClose={() => setShowDeleteGiteaUsers(false)} />
</Box>
)

Expand Down
24 changes: 24 additions & 0 deletions src/redux/otomiApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,13 @@ const injectedRtkApi = api.injectEndpoints({
importKeycloakUsers: build.mutation<ImportKeycloakUsersApiResponse, ImportKeycloakUsersApiArg>({
query: () => ({ url: `/v1/maintenance/import-keycloak-users`, method: 'POST' }),
}),
deleteGiteaUsers: build.mutation<DeleteGiteaUsersApiResponse, DeleteGiteaUsersApiArg>({
query: (queryArg) => ({
url: `/v1/maintenance/delete-gitea-users`,
method: 'POST',
params: { dryRun: queryArg.dryRun },
}),
}),
getAllUsers: build.query<GetAllUsersApiResponse, GetAllUsersApiArg>({
query: () => ({ url: `/v1/users` }),
}),
Expand Down Expand Up @@ -3034,6 +3041,22 @@ export type ImportKeycloakUsersApiResponse = /** status 200 Per-user import resu
}[]
}
export type ImportKeycloakUsersApiArg = void
export type DeleteGiteaUsersApiResponse = /** status 200 Per-user deletion result */ {
dryRun: boolean
results: {
username: string
email?: string
/** Personal repositories of the user, deleted together with the user. */
repos?: string[]
status: 'deleted' | 'failed' | 'dry-run'
/** Why the user could not be deleted, only present when status is failed. */
error?: string
}[]
}
export type DeleteGiteaUsersApiArg = {
/** Only list the users that would be deleted */
dryRun?: boolean
}
export type GetAllUsersApiResponse = /** status 200 Successfully obtained all users configuration */ {
id?: string
email: string
Expand Down Expand Up @@ -4886,6 +4909,7 @@ export const {
useConnectCloudttyQuery,
useDeleteCloudttyMutation,
useImportKeycloakUsersMutation,
useDeleteGiteaUsersMutation,
useGetAllUsersQuery,
useCreateUserMutation,
useGetUserQuery,
Expand Down
4 changes: 3 additions & 1 deletion src/redux/store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ const interceptMiddleware: Middleware = (api: MiddlewareAPI) => (next) => (actio
// exclude endpoints from dirty state
if (
type === 'mutation' &&
['workloadCatalog', 'createObjWizard', 'importKeycloakUsers'].includes(endpointName as string)
['workloadCatalog', 'createObjWizard', 'importKeycloakUsers', 'deleteGiteaUsers'].includes(
endpointName as string,
)
)
dispatch(setDirty(false))
}
Expand Down
Loading