Skip to main content

User soft delete

Allows to deactivate users accound without deleting it.

Instalation​

To install the plugin:

pnpm add @adminforth/user-soft-delete --save

Setting up​

First of all you need to add extra row in your users table:

model adminuser {
id String @id
email String @unique
password_hash String
role String
created_at DateTime
is_active Boolean
@@index([is_active])
}

and make migration:

pnpm makemigration --name add-active-field-to-users ; pnpm migrate:local

To setup the plugin in users resource add:

./adminuser
import UserSoftDelete from "@adminforth/user-soft-delete";

...

columns[

...
{
name: "is_active",
type: AdminForthDataTypes.BOOLEAN,
label: "Is Active",
fillOnCreate: () => true,
filterOptions: {
multiselect: false,
},
showIn: {
list: true,
filter: true,
show: true,
create: false,
edit: true,
},
},

...

]

...

plugins: [

...
new UserSoftDelete({
activeFieldName: "is_active",
//in canDeactivate we pass a function, that specify adminusers roles, which can seactivate other adminusers
canDeactivate: async (adminUser: AdminUser) => {
if (adminUser.dbUser.role === "superadmin") {
return true;
}
return false;
}
}),

...

]

☝️Note that by default deactivated users hidden by filters, so if you want to see them, you'll have to change filters

Deactivating users from custom code​

To deactivate a user from your own API, call deactivateUser of the plugin instance:

./index.ts
import UserSoftDelete from '@adminforth/user-soft-delete';

app.post(`${ADMIN_BASE_URL}/api/deactivate-user/`,
admin.express.authorize(
async (req: IAdminUserExpressRequest, res: express.Response) => {
const { ok, error } = await admin
.getPluginByClassName<UserSoftDelete>('UserSoftDelete')
.deactivateUser(req.body.userId, req.adminUser);
res.json({ ok, error });
}
)
);

It runs the same checks as the deactivate button on behalf of the passed admin user: canDeactivate (or the delete permission of the resource when canDeactivate is not set), the user must be visible to the admin user, and nobody can deactivate their own account. When a check fails, the method returns { ok: false, error } and changes nothing.

To deactivate a user without any checks, e.g. from a background job, set the active field directly:

await admin.resource('adminuser').update(userId, { is_active: false });