-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
167 lines (145 loc) · 7.16 KB
/
Copy pathindex.ts
File metadata and controls
167 lines (145 loc) · 7.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { AdminForthPlugin, AdminForthDataTypes, AdminForthResourcePages, Filters} from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthResource, IAdminForthHttpResponse, AdminUser, AdminForthComponentDeclaration } from "adminforth";
import type { PluginOptions } from './types.js';
import { error } from "console";
import { z } from "zod";
const deactivateUserBodySchema = z.object({
record: z.record(z.string(), z.unknown()),
}).strict();
export default class UserSoftDelete extends AdminForthPlugin {
options: PluginOptions;
allowDisableFunc: Function | null | boolean = null;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
if (this.options.canDeactivate) {
this.allowDisableFunc = this.options.canDeactivate;
} else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'function') {
this.allowDisableFunc = resourceConfig.options.allowedActions.delete;
} else if (resourceConfig.options.allowedActions.delete && typeof resourceConfig.options.allowedActions.delete === 'boolean') {
this.allowDisableFunc = async () => resourceConfig.options.allowedActions.delete;
} else {
this.allowDisableFunc = async () => true;
}
resourceConfig.options.allowedActions.delete = false;
const beforeLoginConfirmation = this.adminforth.config.auth.beforeLoginConfirmation;
const beforeLoginConfirmationArray = Array.isArray(beforeLoginConfirmation) ? beforeLoginConfirmation : [beforeLoginConfirmation];
beforeLoginConfirmationArray.unshift(
async({ extra, adminUser }: { adminUser: AdminUser, response: IAdminForthHttpResponse, extra?: any} )=> {
const rejectResult = {
error: 'Your account is deactivated',
body:{
allowedLogin: false,
redirectTo: '/login',
}
};
if (adminUser.dbUser[this.options.activeFieldName] === false) {
return rejectResult;
}
return { body: {allowedLogin: true} };
}
);
const adminUserAuthorize = this.adminforth.config.auth.adminUserAuthorize;
const adminUserAuthorizeArray = Array.isArray(adminUserAuthorize) ? adminUserAuthorize : [adminUserAuthorize];
adminUserAuthorizeArray.unshift(
async({ extra, adminUser }: { adminUser: AdminUser, response: IAdminForthHttpResponse, extra?: any} )=> {
const rejectResult = {
error: 'Your account is deactivated',
allowed: false,
};
if (adminUser.dbUser[this.options.activeFieldName] === false) {
return rejectResult;
}
return { allowed: true };
}
);
this.adminforth.config.auth.beforeLoginConfirmation = beforeLoginConfirmationArray;
if ( !resourceConfig.options.pageInjections ) {
resourceConfig.options.pageInjections = {};
}
if ( !resourceConfig.options.pageInjections.list ) {
resourceConfig.options.pageInjections.list = {};
}
if ( !resourceConfig.options.pageInjections.list.customActionIcons ) {
resourceConfig.options.pageInjections.list.customActionIcons = [];
}
(resourceConfig.options.pageInjections.list.customActionIcons as AdminForthComponentDeclaration[]).push(
{ file: this.componentPath('DisableButton.vue'), meta: { pluginInstanceId: this.pluginInstanceId, field: this.options.activeFieldName } }
);
if ( !resourceConfig.options.pageInjections.list.afterBreadcrumbs ) {
resourceConfig.options.pageInjections.list.afterBreadcrumbs = [];
}
(resourceConfig.options.pageInjections.list.afterBreadcrumbs as AdminForthComponentDeclaration[]).push(
{ file: this.componentPath('UserSoftDeleteFilterSetter.vue'), meta: { pluginInstanceId: this.pluginInstanceId, field: this.options.activeFieldName } }
);
// simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
// optional method where you can safely check field types after database discovery was performed
if (!this.options.activeFieldName) {
throw new Error(`Option activeFieldName is required for UserSoftDelete plugin on resource ${this.resourceConfig.resourceId}`);
}
const column = this.resourceConfig.columns.find(f => f.name === this.options.activeFieldName);
if (!column) {
throw new Error(`Field ${this.options.activeFieldName} not found in resource ${this.resourceConfig.resourceId}`);
}
if (![AdminForthDataTypes.BOOLEAN].includes(column!.type!)) {
throw new Error(`Field ${this.options.activeFieldName} should be boolean, but it is ${column!.type}`);
}
}
instanceUniqueRepresentation(pluginOptions: any) : string {
// optional method to return unique string representation of plugin instance.
// Needed if plugin can have multiple instances on one resource
return `single`;
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/deactivateUser`,
request_schema: deactivateUserBodySchema,
handler: async ({ adminUser, body, response }) => {
console.log(`UserSoftDelete: deactivateUser endpoint called by ${adminUser.dbUser[this.resourceConfig.columns.find((col) => col.primaryKey).name]}`);
const data = body as z.infer<typeof deactivateUserBodySchema>;
let isAllowedToDeactivate = false;
if ( typeof this.allowDisableFunc === "function" ) {
isAllowedToDeactivate = await this.allowDisableFunc(adminUser);
}
if ( isAllowedToDeactivate === false ) {
return {ok: false, error: "Not allowed to deactivate user"}
}
const primaryKeyColumn = this.resourceConfig.columns.find((col) => col.primaryKey);
if (!data.record) {
return { ok: false, error: "No record provided" };
}
const id = data.record[primaryKeyColumn.name];
if (id === undefined || id === null) {
return { ok: false, error: "No record id provided" };
}
const oldUser = await this.adminforth
.resource(this.resourceConfig.resourceId)
.get([Filters.EQ(primaryKeyColumn.name, id)]);
if (!oldUser) {
throw new Error(`User with id ${id} not found`);
}
if (oldUser[this.options.activeFieldName] === false) {
return {ok: false, error: "User is already deactivated"}
}
if (oldUser[primaryKeyColumn.name] === adminUser.dbUser[primaryKeyColumn.name]) {
return {ok: false, error: "You cannot deactivate your own account"}
}
const newUser = { [this.options.activeFieldName]: false };
await this.adminforth.updateResourceRecord({
resource: this.resourceConfig,
recordId: id,
oldRecord: oldUser,
record: newUser,
adminUser: adminUser
})
return {ok: true}
}
});
}
}