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

Delete users #693

Merged
merged 6 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
76 changes: 76 additions & 0 deletions administration/src/components/users/DeleteUserDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { Button, Callout, Checkbox, Classes, Dialog } from '@blueprintjs/core'
import { useContext } from 'react'
import { Administrator, useDeleteAdministratorMutation } from '../../generated/graphql'
import { useAppToaster } from '../AppToaster'
import { ProjectConfigContext } from '../../project-configs/ProjectConfigContext'
import { AuthContext } from '../../AuthProvider'
import getMessageFromApolloError from '../getMessageFromApolloError'

const DeleteUserDialog = ({
selectedUser,
onClose,
onSuccess,
}: {
onClose: () => void
selectedUser: Administrator | null
onSuccess: () => void
}) => {
const appToaster = useAppToaster()
const authContext = useContext(AuthContext)
const actingAdminId = authContext.data?.administrator.id
const { projectId: project } = useContext(ProjectConfigContext)

const [deleteAdministrator, { loading }] = useDeleteAdministratorMutation({
onError: error => {
console.error(error)
appToaster?.show({ intent: 'danger', message: 'Fehler: ' + getMessageFromApolloError(error) })
},
onCompleted: () => {
appToaster?.show({ intent: 'success', message: 'Benutzer erfolgreich gelöscht.' })
if (selectedUser?.id === actingAdminId) {
authContext.signOut()
} else {
onClose()
onSuccess()
}
},
})

return (
<Dialog title={`Benutzer '${selectedUser?.email}' löschen?`} isOpen={selectedUser !== null} onClose={onClose}>
<form
onSubmit={e => {
e.preventDefault()

if (selectedUser === null) {
console.error('Form submitted in an unexpected state.')
return
}

deleteAdministrator({
variables: {
project,
adminId: selectedUser.id,
},
})
}}>
<div className={Classes.DIALOG_BODY}>
Möchten Sie den Benutzer '{selectedUser?.email}' unwiderruflich löschen?
{selectedUser?.id !== actingAdminId ? null : (
<Callout intent='danger' style={{ marginTop: '16px' }}>
<b>Sie löschen Ihr eigenes Konto.</b> Sie werden ausgeloggt und können sich nicht mehr einloggen.
<Checkbox required>Ich bestätige, dass ich diesen Warnhinweis gelesen habe.</Checkbox>
</Callout>
)}
</div>
<div className={Classes.DIALOG_FOOTER}>
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
<Button type='submit' intent='danger' text='Benutzer löschen' icon='trash' loading={loading} />
</div>
</div>
</form>
</Dialog>
)
}

export default DeleteUserDialog
23 changes: 14 additions & 9 deletions administration/src/components/users/UsersTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { Button } from '@blueprintjs/core'
import { useState } from 'react'
import styled from 'styled-components'
import { Administrator, Region, Role } from '../../generated/graphql'
import { useAppToaster } from '../AppToaster'
import CreateUserDialog from './CreateUserDialog'
import RoleHelpButton from './RoleHelpButton'
import EditUserDialog from './EditUserDialog'
import DeleteUserDialog from './DeleteUserDialog'

const StyledTable = styled.table`
border-spacing: 0;
Expand Down Expand Up @@ -42,15 +42,9 @@ const UsersTable = ({
selectedRegionId?: number | null
refetch: () => void
}) => {
const appToaster = useAppToaster()
const [createUserDialogOpen, setCreateUserDialogOpen] = useState(false)
const [userInEditDialog, setUserInEditDialog] = useState<Administrator | null>(null)

const showNotImplementedToast = () =>
appToaster?.show({
message: 'Diese Funktion ist noch nicht verfügbar!',
intent: 'danger',
})
const [userInDeleteDialog, setUserInDeleteDialog] = useState<Administrator | null>(null)

return (
<>
Expand Down Expand Up @@ -82,7 +76,13 @@ const UsersTable = ({
minimal
onClick={() => setUserInEditDialog(user)}
/>
<Button icon='trash' intent='danger' text='Entfernen' minimal onClick={showNotImplementedToast} />
<Button
icon='trash'
intent='danger'
text='Entfernen'
michael-markl marked this conversation as resolved.
Show resolved Hide resolved
minimal
onClick={() => setUserInDeleteDialog(user)}
/>
</td>
</tr>
)
Expand All @@ -104,6 +104,11 @@ const UsersTable = ({
onSuccess={refetch}
regionIdOverride={selectedRegionId}
/>
<DeleteUserDialog
selectedUser={userInDeleteDialog}
onClose={() => setUserInDeleteDialog(null)}
onSuccess={refetch}
/>
</>
)
}
Expand Down
3 changes: 3 additions & 0 deletions administration/src/graphql/users/deleteAdministrator.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mutation deleteAdministrator($project: String!, $adminId: Int!) {
result: deleteAdministrator(project: $project, adminId: $adminId)
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.Op
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.javatime.datetime
import org.jetbrains.exposed.sql.or
Expand All @@ -19,6 +20,7 @@ object Administrators : IntIdTable() {
val passwordHash = binary("passwordHash").nullable()
val passwordResetKey = varchar("passwordResetKey", 100).nullable()
val passwordResetKeyExpiry = datetime("passwordResetKeyExpiry").nullable()
val deleted = bool("deleted")

init {
val noRegionCompatibleRoles = listOf(Role.PROJECT_ADMIN, Role.NO_RIGHTS)
Expand All @@ -27,6 +29,10 @@ object Administrators : IntIdTable() {
regionId.isNull().and(role.inList(noRegionCompatibleRoles.map { it.db_value })) or
regionId.isNotNull().and(role.inList(regionCompatibleRoles.map { it.db_value }))
}
check("deletedIffNoRights") {
michael-markl marked this conversation as resolved.
Show resolved Hide resolved
(deleted eq Op.TRUE and (role eq Role.NO_RIGHTS.db_value)) or
(deleted eq Op.FALSE and (role neq Role.NO_RIGHTS.db_value))
}
}
}

Expand All @@ -40,4 +46,5 @@ class AdministratorEntity(id: EntityID<Int>) : IntEntity(id) {
var passwordHash by Administrators.passwordHash
var passwordResetKey by Administrators.passwordResetKey
var passwordResetKeyExpiry by Administrators.passwordResetKeyExpiry
var deleted by Administrators.deleted
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import org.jetbrains.exposed.sql.select
import java.security.SecureRandom
import java.time.LocalDateTime
import java.util.Base64
import java.util.UUID

object AdministratorsRepository {

Expand Down Expand Up @@ -77,6 +78,7 @@ object AdministratorsRepository {
this.regionId = region?.id
this.passwordHash = passwordHash
this.role = role.db_value
this.deleted = false
}
}

Expand All @@ -91,6 +93,12 @@ object AdministratorsRepository {
administrator.passwordResetKeyExpiry = null
}

fun deleteAdministrator(administrator: AdministratorEntity) {
administrator.deleted = true
administrator.email = UUID.randomUUID().toString()
michael-markl marked this conversation as resolved.
Show resolved Hide resolved
administrator.role = Role.NO_RIGHTS.db_value
}

fun setNewPasswordResetKey(administrator: AdministratorEntity): String {
val byteArray = ByteArray(64)
SecureRandom.getInstanceStrong().nextBytes(byteArray)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,20 @@ object Authorizer {
}
return false
}

fun mayDeleteUser(
actingAdmin: AdministratorEntity,
existingAdmin: AdministratorEntity
): Boolean {
if (actingAdmin.projectId.value != existingAdmin.projectId.value && existingAdmin.role != Role.NO_RIGHTS.db_value) {
return false
}

if (actingAdmin.role == Role.PROJECT_ADMIN.db_value) {
return true
} else if (actingAdmin.role == Role.REGION_ADMIN.db_value && existingAdmin.regionId == actingAdmin.regionId) {
return true
}
return false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,31 @@ class ManageUsersMutationService {
return true
}

@GraphQLDescription("Deletes an existing administrator")
fun deleteAdministrator(
project: String,
adminId: Int,
dfe: DataFetchingEnvironment
): Boolean {
val context = dfe.getContext<GraphQLContext>()
val jwtPayload = context.enforceSignedIn()

transaction {
val actingAdmin = AdministratorEntity.findById(jwtPayload.userId) ?: throw UnauthorizedException()
val existingAdmin = AdministratorEntity.findById(adminId) ?: throw UnauthorizedException()
val projectEntity = ProjectEntity.find { Projects.project eq project }.first()

if (existingAdmin.projectId != projectEntity.id) throw UnauthorizedException()

if (!Authorizer.mayDeleteUser(actingAdmin, existingAdmin)) {
throw UnauthorizedException()
}

AdministratorsRepository.deleteAdministrator(existingAdmin)
}
return true
}

private fun generateWelcomeMailMessage(
key: String,
administrationName: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import app.ehrenamtskarte.backend.projects.database.Projects
import app.ehrenamtskarte.backend.regions.database.RegionEntity
import com.expediagroup.graphql.generator.annotations.GraphQLDescription
import graphql.schema.DataFetchingEnvironment
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.not
import org.jetbrains.exposed.sql.transactions.transaction

@Suppress("unused")
Expand All @@ -30,7 +32,8 @@ class ViewAdministratorsQueryService {
if (!Authorizer.mayViewUsersInProject(admin, projectId)) {
throw UnauthorizedException()
}
val administrators = AdministratorEntity.find { Administrators.projectId eq projectId }
val administrators =
AdministratorEntity.find { Administrators.projectId eq projectId and not(Administrators.deleted) }

administrators.map { Administrator.fromDbEntity(it) }
}
Expand All @@ -50,7 +53,8 @@ class ViewAdministratorsQueryService {
if (!Authorizer.mayViewUsersInRegion(admin, region)) {
throw UnauthorizedException()
}
val administrators = AdministratorEntity.find { Administrators.regionId eq regionId }
val administrators =
AdministratorEntity.find { Administrators.regionId eq regionId and not(Administrators.deleted) }

administrators.map { Administrator.fromDbEntity(it) }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import org.jetbrains.exposed.sql.transactions.TransactionManager
import org.jetbrains.exposed.sql.transactions.transaction
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.IllegalArgumentException
import java.util.stream.Collectors
import app.ehrenamtskarte.backend.application.database.setupDatabase as setupDatabaseForApplication
import app.ehrenamtskarte.backend.auth.database.setupDatabase as setupDatabaseForAuth
Expand Down Expand Up @@ -41,7 +40,7 @@ class Database {
roleDbValue: String,
projectId: Int? = null
) {
val role = Role.fromDbValue(roleDbValue) ?: throw IllegalArgumentException("Invalid role '$roleDbValue'.")
val role = Role.fromDbValue(roleDbValue)
transaction {
AdministratorsRepository.insert(project, email, password, role, projectId)
}
Expand Down
2 changes: 2 additions & 0 deletions specs/backend-api.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ type Mutation {
changePassword(currentPassword: String!, email: String!, newPassword: String!, project: String!): Boolean!
"Creates a new administrator"
createAdministrator(email: String!, project: String!, regionId: Int, role: Role!, sendWelcomeMail: Boolean!): Boolean!
"Deletes an existing administrator"
deleteAdministrator(adminId: Int!, project: String!): Boolean!
"Deletes the application with specified id"
deleteApplication(applicationId: Int!): Boolean!
"Edits an existing administrator"
Expand Down