diff --git a/src/components/DeleteGiteaUsersModal.tsx b/src/components/DeleteGiteaUsersModal.tsx
new file mode 100644
index 00000000..07118605
--- /dev/null
+++ b/src/components/DeleteGiteaUsersModal.tsx
@@ -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 (
+
+
+
+
+ )
+ }
+
+ if (preview.data) {
+ const users = preview.data.results
+ if (users.length === 0) {
+ return (
+
+ There are no Gitea users to delete.
+
+
+ )
+ }
+ return (
+
+
+ These users and their personal repositories will be permanently deleted. Team organizations and team
+ repositories are not affected.
+
+
+
+ )
+ }
+
+ return (
+
+
+ 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.
+
+
+ )
+}
+
+function UserTable({ headCells, results }: { headCells: HeadCell[]; results: GiteaUserResult[] }) {
+ return (
+
+
+
+ )
+}
+
+function DoneButton({ onClick }: { onClick: () => void }) {
+ return (
+
+
+
+ )
+}
diff --git a/src/pages/Maintenance.test.tsx b/src/pages/Maintenance.test.tsx
index fb160dc6..9a2acde3 100644
--- a/src/pages/Maintenance.test.tsx
+++ b/src/pages/Maintenance.test.tsx
@@ -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'
@@ -16,6 +21,7 @@ jest.mock('redux/otomiApi', () => ({
useCreateObjWizardMutation: jest.fn(),
useGetSettingsQuery: jest.fn(),
useImportKeycloakUsersMutation: jest.fn(),
+ useDeleteGiteaUsersMutation: jest.fn(),
}))
jest.mock(
@@ -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(() => {
@@ -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([
@@ -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()
+ })
+})
diff --git a/src/pages/Maintenance.tsx b/src/pages/Maintenance.tsx
index 46b5870d..8c0708fa 100644
--- a/src/pages/Maintenance.tsx
+++ b/src/pages/Maintenance.tsx
@@ -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 = {
@@ -26,8 +27,10 @@ const classes = {
export default function (): React.ReactElement {
const [, setShowObjWizard] = useLocalStorage('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 : {}
@@ -70,9 +73,20 @@ export default function (): React.ReactElement {
Import Keycloak users into Dex
)}
+ {canDeleteGiteaUsers && (
+
+ )}
setShowImportKeycloakUsers(false)} />
+ setShowDeleteGiteaUsers(false)} />
)
diff --git a/src/redux/otomiApi.ts b/src/redux/otomiApi.ts
index dc8568d3..8fa9ee53 100644
--- a/src/redux/otomiApi.ts
+++ b/src/redux/otomiApi.ts
@@ -226,6 +226,13 @@ const injectedRtkApi = api.injectEndpoints({
importKeycloakUsers: build.mutation({
query: () => ({ url: `/v1/maintenance/import-keycloak-users`, method: 'POST' }),
}),
+ deleteGiteaUsers: build.mutation({
+ query: (queryArg) => ({
+ url: `/v1/maintenance/delete-gitea-users`,
+ method: 'POST',
+ params: { dryRun: queryArg.dryRun },
+ }),
+ }),
getAllUsers: build.query({
query: () => ({ url: `/v1/users` }),
}),
@@ -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
@@ -4886,6 +4909,7 @@ export const {
useConnectCloudttyQuery,
useDeleteCloudttyMutation,
useImportKeycloakUsersMutation,
+ useDeleteGiteaUsersMutation,
useGetAllUsersQuery,
useCreateUserMutation,
useGetUserQuery,
diff --git a/src/redux/store.tsx b/src/redux/store.tsx
index 6aa4a472..c4591dc1 100644
--- a/src/redux/store.tsx
+++ b/src/redux/store.tsx
@@ -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))
}