@adminforth/user-soft-delete 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+
2
+ #!/bin/bash
3
+
4
+ # write npm run output both to console and to build.log
5
+ npm run build 2>&1 | tee build.log
6
+ build_status=${PIPESTATUS[0]}
7
+
8
+ # if exist status from the npm run build is not 0
9
+ # then exit with the status code from the npm run build
10
+ if [ $build_status -ne 0 ]; then
11
+ echo "Build failed. Exiting with status code $build_status"
12
+ exit $build_status
13
+ fi
@@ -0,0 +1,44 @@
1
+ #!/bin/sh
2
+
3
+ set -x
4
+
5
+ COMMIT_SHORT_SHA=$(echo $CI_COMMIT_SHA | cut -c1-8)
6
+
7
+
8
+ if [ "$CI_PREV_PIPELINE_STATUS" = "success" ]; then
9
+ MESSAGE="Did a build without issues on \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\`. Commit: _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
10
+
11
+ curl -s -X POST -H "Content-Type: application/json" -d '{
12
+ "username": "'"$CI_COMMIT_AUTHOR"'",
13
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
14
+ "attachments": [
15
+ {
16
+ "mrkdwn_in": ["text", "pretext"],
17
+ "color": "#36a64f",
18
+ "text": "'"$MESSAGE"'"
19
+ }
20
+ ]
21
+ }' "$DEVELOPERS_SLACK_WEBHOOK"
22
+ exit 0
23
+ fi
24
+ export BUILD_LOG=$(cat ./build.log)
25
+
26
+ BUILD_LOG=$(echo $BUILD_LOG | sed 's/"/\\"/g')
27
+
28
+ MESSAGE="Broke \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\` with commit _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
29
+ CODE_BLOCK="\`\`\`$BUILD_LOG\n\`\`\`"
30
+
31
+ echo "Sending slack message to developers $MESSAGE"
32
+ # Send the message
33
+ curl -sS -X POST -H "Content-Type: application/json" -d '{
34
+ "username": "'"$CI_COMMIT_AUTHOR"'",
35
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
36
+ "attachments": [
37
+ {
38
+ "mrkdwn_in": ["text", "pretext"],
39
+ "color": "#8A1C12",
40
+ "text": "'"$CODE_BLOCK"'",
41
+ "pretext": "'"$MESSAGE"'"
42
+ }
43
+ ]
44
+ }' "$DEVELOPERS_SLACK_WEBHOOK" 2>&1
@@ -0,0 +1,40 @@
1
+ clone:
2
+ git:
3
+ image: woodpeckerci/plugin-git
4
+ settings:
5
+ partial: false
6
+ depth: 5
7
+
8
+ steps:
9
+ init-secrets:
10
+ when:
11
+ - event: push
12
+ image: infisical/cli
13
+ environment:
14
+ INFISICAL_TOKEN:
15
+ from_secret: VAULT_TOKEN
16
+ commands:
17
+ - infisical export --domain https://vault.devforth.io/api --format=dotenv-export --env="prod" > /woodpecker/deploy.vault.env
18
+
19
+ release:
20
+ image: node:20
21
+ when:
22
+ - event: push
23
+ commands:
24
+ - apt update && apt install -y rsync
25
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
26
+ - npm clean-install
27
+ - /bin/bash ./.woodpecker/buildRelease.sh
28
+ - npm audit signatures
29
+ - npx semantic-release
30
+
31
+ slack-on-failure:
32
+ when:
33
+ - event: push
34
+ status: [failure, success]
35
+ - event: push
36
+ image: curlimages/curl
37
+ commands:
38
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
39
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh
40
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Devforth.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/build.log ADDED
@@ -0,0 +1,11 @@
1
+
2
+ > @adminforth/user-soft-delete@1.0.2 build
3
+ > tsc && rsync -av --exclude 'node_modules' custom dist/
4
+
5
+ sending incremental file list
6
+ custom/
7
+ custom/DisableButton.vue
8
+ custom/tsconfig.json
9
+
10
+ sent 3,102 bytes received 58 bytes 6,320.00 bytes/sec
11
+ total size is 2,885 speedup is 0.91
@@ -0,0 +1,98 @@
1
+ <template>
2
+ <div class="flex items-end justify-start gap-2 cursor-pointer" :class="{'opacity-50': checkboxes.length !== 1}">
3
+ <p class="text-justify max-h-[18px] truncate max-w-[60vw] md:max-w-none">Deactivate user</p>
4
+ </div>
5
+ <Dialog
6
+ ref="confirmDialog"
7
+ class="w-96"
8
+ header="Deactivate user"
9
+ :buttons="[
10
+ { label: 'Confirm', onclick: (dialog) => { deactivateUser(); dialog.hide(); } },
11
+ { label: 'Cancel', onclick: (dialog) => dialog.hide() },
12
+ ]"
13
+ >
14
+ <div class="space-y-4">
15
+ <p>Are you sure you want to deactivate this user?</p>
16
+ </div>
17
+ </Dialog>
18
+ </template>
19
+
20
+ <script lang="ts" setup>
21
+ import { Dialog, Tooltip } from '@/afcl';
22
+ import { ref, onMounted } from 'vue';
23
+ import { AdminUser, type AdminForthResourceCommon } from '@/types';
24
+ import adminforth from "@/adminforth"
25
+ import { callAdminForthApi } from '@/utils';
26
+ import { AdminForthFilterOperators } from '@/types/Common';
27
+
28
+
29
+ const confirmDialog = ref(null);
30
+
31
+
32
+ onMounted(async () => {
33
+ await new Promise((resolve) => setTimeout(resolve, 50));
34
+
35
+ adminforth?.list?.updateFilter?.({
36
+ field: props.meta.field,
37
+ operator: AdminForthFilterOperators.EQ,
38
+ value: true,
39
+ });
40
+ });
41
+
42
+ function openDialog() {
43
+ if ( props.checkboxes.length !== 1 ) {
44
+ if (props.checkboxes.length > 1) {
45
+ adminforth.alert({message: "Select only one account to deactivate", variant: "warning"})
46
+ } else {
47
+ adminforth.alert({message: "Select at least one account to deactivate", variant: "warning"})
48
+ }
49
+ } else {
50
+ confirmDialog.value.open()
51
+ }
52
+ }
53
+
54
+ async function deactivateUser() {
55
+ try {
56
+ const res = await callAdminForthApi({
57
+ path: `/plugin/${props.meta.pluginInstanceId}/deactivateUser`,
58
+ method: 'POST',
59
+ body: {
60
+ record: props.checkboxes[0],
61
+ },
62
+ });
63
+ if (!res || res.ok === false || res.error) {
64
+ if ( res.error ) {
65
+ throw new Error(res.error)
66
+ }
67
+ throw new Error("")
68
+ }
69
+ props.updateList();
70
+ } catch (e) {
71
+ adminforth.alert({message: `Error deactivating user. ${e}`, variant: "warning"});
72
+ }
73
+ }
74
+
75
+ const props = defineProps<{
76
+ checkboxes: any,
77
+ meta: any,
78
+ resource: AdminForthResourceCommon,
79
+ adminUser: AdminUser,
80
+ updateList: {
81
+ type: Function,
82
+ required: true
83
+ },
84
+ clearCheckboxes: {
85
+ type: Function
86
+ }
87
+ }>();
88
+
89
+ defineExpose({
90
+ click
91
+ });
92
+
93
+ function click() {
94
+ openDialog();
95
+ }
96
+
97
+
98
+ </script>
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".", // This should point to your project root
4
+ "paths": {
5
+ "@/*": [
6
+ "../node_modules/adminforth/dist/spa/src/*"
7
+ ],
8
+ "*": [
9
+ "../node_modules/adminforth/dist/spa/node_modules/*"
10
+ ],
11
+ "@@/*": [
12
+ "."
13
+ ]
14
+ }
15
+ }
16
+ }
@@ -0,0 +1,98 @@
1
+ <template>
2
+ <div class="flex items-end justify-start gap-2 cursor-pointer" :class="{'opacity-50': checkboxes.length !== 1}">
3
+ <p class="text-justify max-h-[18px] truncate max-w-[60vw] md:max-w-none">Deactivate user</p>
4
+ </div>
5
+ <Dialog
6
+ ref="confirmDialog"
7
+ class="w-96"
8
+ header="Deactivate user"
9
+ :buttons="[
10
+ { label: 'Confirm', onclick: (dialog) => { deactivateUser(); dialog.hide(); } },
11
+ { label: 'Cancel', onclick: (dialog) => dialog.hide() },
12
+ ]"
13
+ >
14
+ <div class="space-y-4">
15
+ <p>Are you sure you want to deactivate this user?</p>
16
+ </div>
17
+ </Dialog>
18
+ </template>
19
+
20
+ <script lang="ts" setup>
21
+ import { Dialog, Tooltip } from '@/afcl';
22
+ import { ref, onMounted } from 'vue';
23
+ import { AdminUser, type AdminForthResourceCommon } from '@/types';
24
+ import adminforth from "@/adminforth"
25
+ import { callAdminForthApi } from '@/utils';
26
+ import { AdminForthFilterOperators } from '@/types/Common';
27
+
28
+
29
+ const confirmDialog = ref(null);
30
+
31
+
32
+ onMounted(async () => {
33
+ await new Promise((resolve) => setTimeout(resolve, 50));
34
+
35
+ adminforth?.list?.updateFilter?.({
36
+ field: props.meta.field,
37
+ operator: AdminForthFilterOperators.EQ,
38
+ value: true,
39
+ });
40
+ });
41
+
42
+ function openDialog() {
43
+ if ( props.checkboxes.length !== 1 ) {
44
+ if (props.checkboxes.length > 1) {
45
+ adminforth.alert({message: "Select only one account to deactivate", variant: "warning"})
46
+ } else {
47
+ adminforth.alert({message: "Select at least one account to deactivate", variant: "warning"})
48
+ }
49
+ } else {
50
+ confirmDialog.value.open()
51
+ }
52
+ }
53
+
54
+ async function deactivateUser() {
55
+ try {
56
+ const res = await callAdminForthApi({
57
+ path: `/plugin/${props.meta.pluginInstanceId}/deactivateUser`,
58
+ method: 'POST',
59
+ body: {
60
+ record: props.checkboxes[0],
61
+ },
62
+ });
63
+ if (!res || res.ok === false || res.error) {
64
+ if ( res.error ) {
65
+ throw new Error(res.error)
66
+ }
67
+ throw new Error("")
68
+ }
69
+ props.updateList();
70
+ } catch (e) {
71
+ adminforth.alert({message: `Error deactivating user. ${e}`, variant: "warning"});
72
+ }
73
+ }
74
+
75
+ const props = defineProps<{
76
+ checkboxes: any,
77
+ meta: any,
78
+ resource: AdminForthResourceCommon,
79
+ adminUser: AdminUser,
80
+ updateList: {
81
+ type: Function,
82
+ required: true
83
+ },
84
+ clearCheckboxes: {
85
+ type: Function
86
+ }
87
+ }>();
88
+
89
+ defineExpose({
90
+ click
91
+ });
92
+
93
+ function click() {
94
+ openDialog();
95
+ }
96
+
97
+
98
+ </script>
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".", // This should point to your project root
4
+ "paths": {
5
+ "@/*": [
6
+ "../node_modules/adminforth/dist/spa/src/*"
7
+ ],
8
+ "*": [
9
+ "../node_modules/adminforth/dist/spa/node_modules/*"
10
+ ],
11
+ "@@/*": [
12
+ "."
13
+ ]
14
+ }
15
+ }
16
+ }
package/dist/index.js ADDED
@@ -0,0 +1,120 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AdminForthPlugin, AdminForthDataTypes, Filters } from "adminforth";
11
+ export default class UserSoftDelete extends AdminForthPlugin {
12
+ constructor(options) {
13
+ super(options, import.meta.url);
14
+ this.allowDisableFunc = null;
15
+ this.options = options;
16
+ }
17
+ modifyResourceConfig(adminforth, resourceConfig) {
18
+ const _super = Object.create(null, {
19
+ modifyResourceConfig: { get: () => super.modifyResourceConfig }
20
+ });
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
23
+ if (this.options.canDeactivate) {
24
+ this.allowDisableFunc = this.options.canDeactivate;
25
+ }
26
+ else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'function') {
27
+ this.allowDisableFunc = resourceConfig.options.allowedActions.delete;
28
+ }
29
+ else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'boolean') {
30
+ this.allowDisableFunc = () => __awaiter(this, void 0, void 0, function* () { return resourceConfig.options.allowedActions.delete; });
31
+ }
32
+ else {
33
+ this.allowDisableFunc = () => __awaiter(this, void 0, void 0, function* () { return true; });
34
+ }
35
+ resourceConfig.options.allowedActions.delete = false;
36
+ const beforeLoginConfirmation = this.adminforth.config.auth.beforeLoginConfirmation;
37
+ const beforeLoginConfirmationArray = Array.isArray(beforeLoginConfirmation) ? beforeLoginConfirmation : [beforeLoginConfirmation];
38
+ beforeLoginConfirmationArray.unshift((_a) => __awaiter(this, [_a], void 0, function* ({ extra, adminUser }) {
39
+ const rejectResult = {
40
+ error: 'Your account is deactivated',
41
+ body: {
42
+ allowedLogin: false,
43
+ redirectTo: '/login',
44
+ },
45
+ ok: true
46
+ };
47
+ if (adminUser.dbUser[this.options.activeFieldName] === false) {
48
+ return rejectResult;
49
+ }
50
+ }));
51
+ if (!resourceConfig.options.pageInjections) {
52
+ resourceConfig.options.pageInjections = {};
53
+ }
54
+ if (!resourceConfig.options.pageInjections.list) {
55
+ resourceConfig.options.pageInjections.list = {};
56
+ }
57
+ if (!resourceConfig.options.pageInjections.list.threeDotsDropdownItems) {
58
+ resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [];
59
+ }
60
+ resourceConfig.options.pageInjections.list.threeDotsDropdownItems.push({ file: this.componentPath('DisableButton.vue'), meta: { pluginInstanceId: this.pluginInstanceId, field: this.options.activeFieldName } });
61
+ // simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
62
+ });
63
+ }
64
+ validateConfigAfterDiscover(adminforth, resourceConfig) {
65
+ // optional method where you can safely check field types after database discovery was performed
66
+ if (!this.options.activeFieldName) {
67
+ throw new Error(`Option activeFieldName is required for UserSoftDelete plugin on resource ${this.resourceConfig.resourceId}`);
68
+ }
69
+ const column = this.resourceConfig.columns.find(f => f.name === this.options.activeFieldName);
70
+ if (!column) {
71
+ throw new Error(`Field ${this.options.activeFieldName} not found in resource ${this.resourceConfig.resourceId}`);
72
+ }
73
+ if (![AdminForthDataTypes.BOOLEAN].includes(column.type)) {
74
+ throw new Error(`Field ${this.options.activeFieldName} should be boolean, but it is ${column.type}`);
75
+ }
76
+ }
77
+ instanceUniqueRepresentation(pluginOptions) {
78
+ // optional method to return unique string representation of plugin instance.
79
+ // Needed if plugin can have multiple instances on one resource
80
+ return `user-soft-delete`;
81
+ }
82
+ setupEndpoints(server) {
83
+ server.endpoint({
84
+ method: 'POST',
85
+ path: `/plugin/${this.pluginInstanceId}/deactivateUser`,
86
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, body }) {
87
+ let isAllowedToDeactivate = false;
88
+ if (typeof this.allowDisableFunc === "function") {
89
+ isAllowedToDeactivate = yield this.allowDisableFunc(adminUser);
90
+ }
91
+ else if (typeof this.allowDisableFunc === "boolean") {
92
+ isAllowedToDeactivate = this.allowDisableFunc;
93
+ }
94
+ if (isAllowedToDeactivate === false) {
95
+ return { ok: false, error: "Not allowed to deactivate user" };
96
+ }
97
+ const id = body.record;
98
+ const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
99
+ const oldUser = yield this.adminforth
100
+ .resource(this.resourceConfig.resourceId)
101
+ .get([Filters.EQ(primaryKeyColumn.name, id)]);
102
+ if (!oldUser) {
103
+ throw new Error(`User with id ${id} not found`);
104
+ }
105
+ if (oldUser[this.options.activeFieldName] === false) {
106
+ return { ok: false, error: "User is already deactivated" };
107
+ }
108
+ const newUser = Object.assign(Object.assign({}, oldUser), { [this.options.activeFieldName]: false });
109
+ yield this.adminforth.updateResourceRecord({
110
+ resource: this.resourceConfig,
111
+ recordId: id,
112
+ oldRecord: oldUser,
113
+ record: newUser,
114
+ adminUser: adminUser
115
+ });
116
+ return { ok: true };
117
+ })
118
+ });
119
+ }
120
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.ts ADDED
@@ -0,0 +1,126 @@
1
+ import { AdminForthPlugin, AdminForthDataTypes, AdminForthResourcePages, Filters} from "adminforth";
2
+ import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthResource, IAdminForthHttpResponse, AdminUser, AdminForthComponentDeclaration } from "adminforth";
3
+ import type { PluginOptions } from './types.js';
4
+ import { error } from "console";
5
+
6
+ export default class UserSoftDelete extends AdminForthPlugin {
7
+ options: PluginOptions;
8
+ allowDisableFunc: Function | null | boolean = null;
9
+
10
+ constructor(options: PluginOptions) {
11
+ super(options, import.meta.url);
12
+ this.options = options;
13
+ }
14
+
15
+ async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
16
+ super.modifyResourceConfig(adminforth, resourceConfig);
17
+ if (this.options.canDeactivate) {
18
+ this.allowDisableFunc = this.options.canDeactivate;
19
+ } else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'function') {
20
+ this.allowDisableFunc = resourceConfig.options.allowedActions.delete;
21
+ } else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'boolean') {
22
+ this.allowDisableFunc = async () => resourceConfig.options.allowedActions.delete;
23
+ } else {
24
+ this.allowDisableFunc = async () => true;
25
+ }
26
+
27
+ resourceConfig.options.allowedActions.delete = false;
28
+
29
+ const beforeLoginConfirmation = this.adminforth.config.auth.beforeLoginConfirmation;
30
+ const beforeLoginConfirmationArray = Array.isArray(beforeLoginConfirmation) ? beforeLoginConfirmation : [beforeLoginConfirmation];
31
+ beforeLoginConfirmationArray.unshift(
32
+ async({ extra, adminUser }: { adminUser: AdminUser, response: IAdminForthHttpResponse, extra?: any} )=> {
33
+ const rejectResult = {
34
+ error: 'Your account is deactivated',
35
+ body:{
36
+ allowedLogin: false,
37
+ redirectTo: '/login',
38
+ },
39
+ ok: true
40
+ };
41
+ if (adminUser.dbUser[this.options.activeFieldName] === false) {
42
+ return rejectResult;
43
+ }
44
+ }
45
+ );
46
+
47
+ if ( !resourceConfig.options.pageInjections ) {
48
+ resourceConfig.options.pageInjections = {};
49
+ }
50
+ if ( !resourceConfig.options.pageInjections.list ) {
51
+ resourceConfig.options.pageInjections.list = {};
52
+ }
53
+ if ( !resourceConfig.options.pageInjections.list.threeDotsDropdownItems ) {
54
+ resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [];
55
+ }
56
+ (resourceConfig.options.pageInjections.list.threeDotsDropdownItems as AdminForthComponentDeclaration[]).push(
57
+ { file: this.componentPath('DisableButton.vue'), meta: { pluginInstanceId: this.pluginInstanceId, field: this.options.activeFieldName } }
58
+ );
59
+
60
+ // simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
61
+ }
62
+
63
+ validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
64
+ // optional method where you can safely check field types after database discovery was performed
65
+ if (!this.options.activeFieldName) {
66
+ throw new Error(`Option activeFieldName is required for UserSoftDelete plugin on resource ${this.resourceConfig.resourceId}`);
67
+ }
68
+ const column = this.resourceConfig.columns.find(f => f.name === this.options.activeFieldName);
69
+ if (!column) {
70
+ throw new Error(`Field ${this.options.activeFieldName} not found in resource ${this.resourceConfig.resourceId}`);
71
+ }
72
+ if (![AdminForthDataTypes.BOOLEAN].includes(column!.type!)) {
73
+ throw new Error(`Field ${this.options.activeFieldName} should be boolean, but it is ${column!.type}`);
74
+ }
75
+ }
76
+
77
+ instanceUniqueRepresentation(pluginOptions: any) : string {
78
+ // optional method to return unique string representation of plugin instance.
79
+ // Needed if plugin can have multiple instances on one resource
80
+ return `user-soft-delete`;
81
+ }
82
+
83
+ setupEndpoints(server: IHttpServer) {
84
+ server.endpoint({
85
+ method: 'POST',
86
+ path: `/plugin/${this.pluginInstanceId}/deactivateUser`,
87
+ handler: async ({ adminUser,body }) => {
88
+ let isAllowedToDeactivate = false;
89
+ if ( typeof this.allowDisableFunc === "function" ) {
90
+ isAllowedToDeactivate = await this.allowDisableFunc(adminUser);
91
+ } else if (typeof this.allowDisableFunc === "boolean") {
92
+ isAllowedToDeactivate = this.allowDisableFunc;
93
+ }
94
+ if ( isAllowedToDeactivate === false ) {
95
+ return {ok: false, error: "Not allowed to deactivate user"}
96
+ }
97
+ const id = body.record;
98
+ const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
99
+
100
+ const oldUser = await this.adminforth
101
+ .resource(this.resourceConfig.resourceId)
102
+ .get([Filters.EQ(primaryKeyColumn.name, id)]);
103
+
104
+ if (!oldUser) {
105
+ throw new Error(`User with id ${id} not found`);
106
+ }
107
+
108
+ if (oldUser[this.options.activeFieldName] === false) {
109
+ return {ok: false, error: "User is already deactivated"}
110
+ }
111
+
112
+ const newUser = { ...oldUser, [this.options.activeFieldName]: false };
113
+
114
+ await this.adminforth.updateResourceRecord({
115
+ resource: this.resourceConfig,
116
+ recordId: id,
117
+ oldRecord: oldUser,
118
+ record: newUser,
119
+ adminUser: adminUser
120
+ })
121
+ return {ok: true}
122
+ }
123
+ });
124
+ }
125
+
126
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@adminforth/user-soft-delete",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc && rsync -av --exclude 'node_modules' custom dist/"
12
+ },
13
+ "keywords": [],
14
+ "author": "",
15
+ "license": "ISC",
16
+ "description": "",
17
+ "devDependencies": {
18
+ "@types/node": "latest",
19
+ "typescript": "^5.7.3",
20
+ "semantic-release": "^24.2.1",
21
+ "semantic-release-slack-bot": "^4.0.2"
22
+ },
23
+ "dependencies": {
24
+ "adminforth": "^2.4.0-next.191"
25
+ },
26
+ "release": {
27
+ "plugins": [
28
+ "@semantic-release/commit-analyzer",
29
+ "@semantic-release/release-notes-generator",
30
+ "@semantic-release/npm",
31
+ "@semantic-release/github",
32
+ [
33
+ "semantic-release-slack-bot",
34
+ {
35
+ "notifyOnSuccess": true,
36
+ "notifyOnFail": true,
37
+ "slackIcon": ":package:",
38
+ "markdownReleaseNotes": true
39
+ }
40
+ ]
41
+ ]
42
+ },
43
+ "branches": [
44
+ "main",
45
+ {
46
+ "name": "next",
47
+ "prerelease": true
48
+ }
49
+ ]
50
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include*/
4
+ "module": "node16", /* Specify what module code is generated. */
5
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
6
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */
7
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
8
+ "strict": false, /* Enable all strict type-checking options. */
9
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
10
+ },
11
+ "exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
12
+ }
13
+
package/types.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { AdminUser } from "adminforth";
2
+
3
+ export interface PluginOptions {
4
+ activeFieldName: string;
5
+ canDeactivate?: (adminUser: AdminUser) => Promise<boolean>;
6
+ }