-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
334 lines (275 loc) · 11.9 KB
/
index.ts
File metadata and controls
334 lines (275 loc) · 11.9 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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import AdminForth, { AdminForthPlugin, suggestIfTypo, Filters } from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthResourcePages, AdminForthResourceColumn, AdminForthDataTypes, AdminForthResource, AdminUser, HttpExtra } from "adminforth";
import type { PluginOptions } from './types.js';
export default class EmailInvitePlugin extends AdminForthPlugin {
options: PluginOptions;
authResource!: AdminForthResource;
emailField!: AdminForthResourceColumn;
emailConfirmedField?: AdminForthResourceColumn;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
this.shouldHaveSingleInstancePerWholeApp = () => true;
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
if (!this.options.emailField) {
throw new Error(`emailField is required and should be a name of field in auth resource`);
}
if (!this.options.sendFrom) {
throw new Error(`sendFrom is required and should be a valid email address`);
}
if (!this.options.adapter) {
throw new Error('Adapter is required. Please provide a valid email adapter in the plugin options.');
}
if (!adminforth.config.auth) {
throw new Error('Auth configuration is required for email invite plugin');
}
const authResource = adminforth.config.resources.find(r => r.resourceId === adminforth.config.auth!.usersResourceId);
if (!authResource) {
throw new Error(`Resource with id config.auth.usersResourceId=${adminforth.config.auth!.usersResourceId} not found`);
}
this.authResource = authResource;
const emailField = authResource.columns.find(f => f.name === this.options.emailField);
if (!emailField) {
const similar = suggestIfTypo(authResource.columns.map(f => f.name), this.options.emailField);
throw new Error(`Field with name ${this.options.emailField} not found in resource ${authResource.resourceId}.
${similar ? `Did you mean ${similar}?` : ''}
`);
}
this.emailField = emailField;
if (!this.options.passwordField) {
throw new Error(`passwordField is required to get password constraints and should be a name of virtual field in auth resource`);
}
const passwordField = authResource.columns.find(f => f.name === this.options.passwordField);
if (!passwordField) {
const similar = suggestIfTypo(authResource.columns.map(f => f.name), this.options.passwordField);
throw new Error(`Field with name ${this.options.passwordField} not found in resource ${authResource.resourceId}.
${similar ? `Did you mean ${similar}?` : ''}
`);
}
if (this.options.emailConfirmedField) {
const emailConfirmedField = authResource.columns.find(f => f.name === this.options.emailConfirmedField);
if (!emailConfirmedField) {
const similar = suggestIfTypo(authResource.columns.map(f => f.name), this.options.emailConfirmedField);
throw new Error(`Email confirmed field with name ${this.options.emailConfirmedField} not found in resource ${authResource.resourceId}.
${similar ? `Did you mean ${similar}?` : ''}
`);
}
this.emailConfirmedField = emailConfirmedField;
}
if (!authResource.hooks) {
authResource.hooks = {};
}
if (!authResource.hooks.create) {
authResource.hooks.create = {};
}
if (!authResource.hooks.create.beforeSave) {
authResource.hooks.create.beforeSave = [];
}
if (!Array.isArray(authResource.hooks.create.beforeSave)) {
authResource.hooks.create.beforeSave = [authResource.hooks.create.beforeSave];
}
authResource.hooks.create.beforeSave.push(this.handleUserCreation.bind(this));
if (!authResource.hooks.create.afterSave) {
authResource.hooks.create.afterSave = [];
}
if (!Array.isArray(authResource.hooks.create.afterSave)) {
authResource.hooks.create.afterSave = [authResource.hooks.create.afterSave];
}
authResource.hooks.create.afterSave.push(this.sendInviteEmail.bind(this));
adminforth.config.customization.customPages.push({
path: '/set-password',
component: {
file: this.componentPath('SetPassword.vue'),
meta: {
sidebarAndHeader: "none",
pluginInstanceId: this.pluginInstanceId,
passwordField: {
minLength: passwordField.minLength,
maxLength: passwordField.maxLength,
validation: passwordField.validation
}
}
}
});
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
this.options.adapter.validate();
}
instanceUniqueRepresentation(pluginOptions: any): string {
return `single`;
}
async handleUserCreation({ resource, adminUser, record, adminforth, extra }: {
resource: AdminForthResource;
adminUser: AdminUser;
record: any;
adminforth: IAdminForth;
extra?: HttpExtra;
}): Promise<{ok: boolean, error?: string}> {
try {
// Remove any password field from record since users will set it via invite
if ('password' in record) {
delete record.password;
}
const passwordHashFieldName = adminforth.config.auth!.passwordHashField;
record[passwordHashFieldName] = await AdminForth.Utils.generatePasswordHash('TEMP_INVITE_PLACEHOLDER_' + Date.now());
if (this.options.emailConfirmedField && this.emailConfirmedField) {
record[this.emailConfirmedField.name] = false;
}
return { ok: true };
} catch (error) {
console.error('Error in handleUserCreation:', error);
return { ok: false, error: 'Failed to prepare user for creation' };
}
}
async sendInviteEmail({ recordId, resource, record, adminUser, adminforth, extra }: {
recordId: any;
resource: AdminForthResource;
record: any;
adminUser: AdminUser;
adminforth: IAdminForth;
extra?: HttpExtra;
}): Promise<{ok: boolean, error?: string}> {
try {
const email = record[this.options.emailField];
if (!email || !/\S+@\S+\.\S+/.test(email)) {
console.warn('Email invite plugin: Invalid or missing email address');
return { ok: true }; // Don't fail user creation for email issues
}
const brandName = adminforth.config.customization.brandName || 'Admin Panel';
const inviteToken = adminforth.auth.issueJWT(
{ email, recordId, inviteEmail: true },
'inviteUser',
'7d' // 7 days validity
);
console.log('Sending invite email to:', email);
console.log('Generated JWT token payload:', { email, recordId, inviteEmail: true });
const host = extra?.headers?.host || 'localhost';
const protocol = extra?.headers?.['x-forwarded-proto'] || 'http';
const inviteUrl = `${protocol}://${host}/set-password?token=${inviteToken}`;
const emailSubject = `You're invited to ${brandName}`;
const emailText = `
Dear user,
You have been invited to join ${brandName}. To complete your registration and set your password, click the link below:
${inviteUrl}
If you didn't expect this invitation, please ignore this email.
Link is valid for 7 days.
Thanks,
The ${brandName} Team
`;
const emailHtml = `
<html>
<head></head>
<body>
<p>Dear user,</p>
<p>You have been invited to join ${brandName}. To complete your registration and set your password, click the link below:</p>
<p><a href="${inviteUrl}">Set your password</a></p>
<p>If you didn't expect this invitation, please ignore this email.</p>
<p>Link is valid for 7 days.</p>
<p>Thanks,</p>
<p>The ${brandName} Team</p>
</body>
</html>
`;
// Send email
const result = await this.options.adapter.sendEmail(
this.options.sendFrom,
email,
emailText,
emailHtml,
emailSubject
);
if (result && result.error) {
console.error('Failed to send invite email:', result.error);
} else {
console.log('Invite email sent successfully to:', email);
}
return { ok: true };
} catch (error) {
console.error('Error sending invite email:', error);
return { ok: true };
}
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/set-password`,
noAuth: true,
handler: async ({ body }) => {
const { token, password } = body;
try {
const decoded = await this.adminforth.auth.verify(token, 'inviteUser', false);
if (!decoded || !decoded.inviteEmail) {
return { error: 'Invalid or expired invitation token', ok: false };
}
const { email, recordId } = decoded;
let userRecord;
if (recordId) {
userRecord = await this.adminforth.resource(this.authResource.resourceId).get(Filters.EQ(this.authResource.columns.find(c => c.primaryKey).name, recordId));
}
if (!userRecord && email) {
const records = await this.adminforth.resource(this.authResource.resourceId).list(
Filters.EQ(this.options.emailField, email),
1
);
userRecord = records.length > 0 ? records[0] : null;
}
if (!userRecord) {
return { error: 'User not found', ok: false };
}
if ( userRecord[this.options.emailConfirmedField] ) {
return { error: 'Password already set. Invitation link cannot be reused.', ok: false };
}
const userEmail = userRecord[this.options.emailField];
const tokenEmail = email;
if (!userEmail || userEmail.toLowerCase() !== tokenEmail.toLowerCase()) {
return { error: 'Email mismatch', ok: false };
}
const passwordHashFieldName = this.adminforth.config.auth.passwordHashField;
const newPasswordHash = await AdminForth.Utils.generatePasswordHash(password);
const primaryKeyField = this.authResource.columns.find(c => c.primaryKey);
const userRecordId = userRecord[primaryKeyField!.name];
const updateData: any = {
[passwordHashFieldName]: newPasswordHash
};
if (this.options.emailConfirmedField && this.emailConfirmedField) {
updateData[this.emailConfirmedField.name] = true;
}
await this.adminforth.resource(this.authResource.resourceId).update(userRecordId, updateData);
console.log('Password set successfully for user:', email);
return { ok: true };
} catch (error) {
console.error('Error setting password:', error);
return { error: 'Failed to set password', ok: false };
}
}
});
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/resend-invite`,
handler: async ({ body, adminUser }) => {
const { recordId } = body;
try {
// Get the user record
const userRecord = await this.adminforth.resource(this.authResource.resourceId).get(recordId);
if (!userRecord) {
return { error: 'User not found', ok: false };
}
// Simulate the afterSave hook call to resend invite
await this.sendInviteEmail({
recordId,
resource: this.authResource,
record: userRecord,
adminUser,
adminforth: this.adminforth,
});
return { ok: true };
} catch (error) {
console.error('Error resending invite:', error);
return { error: 'Failed to resend invitation', ok: false };
}
}
});
}
}