very-express 0.8.3 → 0.9.0-alpha
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.
- package/AGENTS.md +8 -1
- package/dist/index.js +1307 -592
- package/dist/templates/_middlewares/Authentication.ts +49 -32
- package/dist/templates/_projectSettings/env +13 -0
- package/dist/templates/_projectSettings/package.json +2 -1
- package/dist/templates/_routes/ExternalIdentityUI.gen.ts +20 -0
- package/dist/templates/_routes/LoginUI.ts +434 -5
- package/dist/templates/_services/MongooseRepositoryAdapter.ts +67 -5
- package/dist/templates/_services/TypeOrmRepositoryAdapter.ts +70 -4
- package/dist/templates/_services/oauth/OAuthProfileMap.ts +27 -8
- package/dist/templates/_services/oauth/OAuthStrategyService.ts +5 -5
- package/dist/templates/_types/auth.ts +24 -1
- package/dist/templates/_types/vex/VexRepository.ts +21 -0
- package/dist/templates/jsonSchema/User.json +8 -1
- package/dist/templates/jsonSchema/UserAuthProfiles.json +13 -5
- package/dist/templates/root/public/js/deleteaccount.js +134 -0
- package/dist/templates/root/public/js/externallogin.js +133 -0
- package/docs/architecture/authAndRouting.md +8 -1
- package/docs/features/accountDeletion.md +150 -0
- package/docs/features/auditFields.md +0 -30
- package/docs/features/auth.md +34 -0
- package/docs/features/externalIdentity.md +163 -0
- package/docs/releaseNote/v0-8-4.md +131 -0
- package/docs/releaseNote/v0-9-0.md +49 -0
- package/docs/vexJsonSchema.md +11 -1
- package/package.json +1 -1
- package/vex.config.json +9 -1
- package/docs/appGenerated/auth.md +0 -23
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { Model, Document } from "mongoose";
|
|
3
3
|
import { VexRepository, Select, Filter, Join, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
|
-
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
5
|
+
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
6
|
import utils from "../_utils";
|
|
7
7
|
|
|
8
8
|
/** When a framework-managed field is written. */
|
|
@@ -84,9 +84,34 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
84
84
|
return this.model;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Entity class name — the key used by the generated registries. */
|
|
88
|
+
private getEntityName(): string {
|
|
89
|
+
return this.model.modelName + "Entity";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Soft-delete term for this model, or null when it declares no marker.
|
|
94
|
+
*
|
|
95
|
+
* `$ne: true` (not `$eq: false`) so documents written before the field existed still count as
|
|
96
|
+
* live — the same leniency the SQL side gets from NOT NULL DEFAULT false.
|
|
97
|
+
*/
|
|
98
|
+
private getSoftDeleteFilter(): Record<string, unknown> | null {
|
|
99
|
+
if (showSoftDeleted) return null;
|
|
100
|
+
|
|
101
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
102
|
+
if (!field) return null;
|
|
103
|
+
|
|
104
|
+
return { [field]: { $ne: true } };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private mergeFilter(filter: Filter, options?: { includeSoftDeleted?: boolean }): Record<string, unknown> {
|
|
108
|
+
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
109
|
+
return { ...((filter || {}) as Record<string, unknown>), ...softDelete };
|
|
110
|
+
}
|
|
111
|
+
|
|
87
112
|
find(filter: Filter, join?: Join, select?: Select, pagination?: VexPagination): Promise<T[]> {
|
|
88
113
|
// TODO: complete mongoose support, handle join, select, and pagination
|
|
89
|
-
return this.model.find((filter
|
|
114
|
+
return this.model.find(this.mergeFilter(filter) as any).exec();
|
|
90
115
|
}
|
|
91
116
|
|
|
92
117
|
async count(filter: Filter): Promise<number> {
|
|
@@ -96,12 +121,12 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
96
121
|
|
|
97
122
|
findOne(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
98
123
|
// TODO: complete mongoose support, handle join and select
|
|
99
|
-
return this.model.findOne(filter as any).exec();
|
|
124
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
100
125
|
}
|
|
101
126
|
|
|
102
127
|
findOneWhere(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
103
128
|
// TODO: complete mongoose support, handle join and select
|
|
104
|
-
return this.model.findOne(filter as any).exec();
|
|
129
|
+
return this.model.findOne(this.mergeFilter(filter) as any).exec();
|
|
105
130
|
}
|
|
106
131
|
|
|
107
132
|
async create(data: Partial<T>): Promise<T> {
|
|
@@ -140,6 +165,43 @@ export class MongooseRepositoryAdapter<T extends Document> implements VexReposit
|
|
|
140
165
|
}
|
|
141
166
|
|
|
142
167
|
async deleteWhere(filter: Record<string, unknown>): Promise<void> {
|
|
143
|
-
await this.model.deleteOne(filter as any).exec();
|
|
168
|
+
await this.model.deleteOne(this.mergeFilter(filter as Filter) as any).exec();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Tombstone the document: run the normal update-phase field machinery (so `updatedAt` /
|
|
173
|
+
* `updatedBy` record who deleted it and when), then write the marker plus any redaction
|
|
174
|
+
* the caller merged in.
|
|
175
|
+
*/
|
|
176
|
+
async softDelete(id: string | undefined, data?: Partial<T>): Promise<T | null> {
|
|
177
|
+
if (!id) {
|
|
178
|
+
utils.log.error("MongooseRepositoryAdapter.softDelete called without id — refuse update document");
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
183
|
+
if (!field) {
|
|
184
|
+
utils.log.error(
|
|
185
|
+
`MongooseRepositoryAdapter.softDelete on ${this.getEntityName()} — entity declares no ` +
|
|
186
|
+
`x-vexData "softDelete" field, refuse update document`
|
|
187
|
+
);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const enriched: Record<string, unknown> = { ...((data ?? {}) as Record<string, unknown>) };
|
|
192
|
+
this.applyVexFields(enriched as Partial<T>, "update");
|
|
193
|
+
enriched[field] = true;
|
|
194
|
+
|
|
195
|
+
const filter = this.mergeFilter({ _id: id } as Filter);
|
|
196
|
+
return this.model.findOneAndUpdate(filter as any, { $set: enriched }, { new: true }).exec();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Read a document that may be soft-deleted: skips the soft-delete term only.
|
|
201
|
+
* Framework-internal — see VexRepository.
|
|
202
|
+
*/
|
|
203
|
+
findOneWithDeleted(filter: Filter, join?: Join, select?: Select): Promise<T | null> {
|
|
204
|
+
// TODO: complete mongoose support, handle join and select
|
|
205
|
+
return this.model.findOne(this.mergeFilter(filter, { includeSoftDeleted: true }) as any).exec();
|
|
144
206
|
}
|
|
145
207
|
}
|
|
@@ -3,7 +3,7 @@ import { Repository, ObjectLiteral, FindOptionsWhere, DeepPartial, In, Not, Like
|
|
|
3
3
|
import { VexRepository, Select, Filter, Join, FieldOperators, VexPagination, VexResErr } from "../_types/vex";
|
|
4
4
|
import UserContext from "../_middlewares/UserContext.gen";
|
|
5
5
|
import { entityIsolation } from "../_middlewares/DataIsolationRegistry.gen";
|
|
6
|
-
import { entityVexFields, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
6
|
+
import { entityVexFields, entitySoftDeleteFields, showSoftDeleted, VexFieldEntry } from "../_middlewares/VexFieldRegistry.gen";
|
|
7
7
|
import utils from "../_utils";
|
|
8
8
|
|
|
9
9
|
/** When a framework-managed field is written. */
|
|
@@ -98,16 +98,36 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
98
98
|
return { [config.field]: userId };
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Soft-delete term for this entity, or null when it declares no marker.
|
|
103
|
+
*
|
|
104
|
+
* `Not(true)` rather than `deleted: false`: the generated column is NOT NULL DEFAULT false, so
|
|
105
|
+
* the two are equivalent for rows written by this schema, and `Not(true)` stays correct for a
|
|
106
|
+
* row that predates the column (NULL) on a target where that can happen.
|
|
107
|
+
*/
|
|
108
|
+
private getSoftDeleteFilter(): Record<string, unknown> | null {
|
|
109
|
+
if (showSoftDeleted) return null;
|
|
110
|
+
|
|
111
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
112
|
+
if (!field) return null;
|
|
113
|
+
|
|
114
|
+
return { [field]: Not(true) };
|
|
115
|
+
}
|
|
116
|
+
|
|
101
117
|
/** Merge caller filter with ownership filter. Ownership always wins. */
|
|
102
|
-
private mergeFilter(
|
|
118
|
+
private mergeFilter(
|
|
119
|
+
callerFilter: Filter<T>,
|
|
120
|
+
options?: { includeSoftDeleted?: boolean },
|
|
121
|
+
): Record<string, unknown> | Array<Record<string, unknown>> {
|
|
103
122
|
const mapped = this.mapOperators(callerFilter);
|
|
104
123
|
const ownership = this.getOwnershipFilter();
|
|
124
|
+
const softDelete = options?.includeSoftDeleted ? null : this.getSoftDeleteFilter();
|
|
105
125
|
|
|
106
126
|
if (mapped instanceof Array) {
|
|
107
|
-
return mapped.map(branch => ({ ...branch, ...ownership }));
|
|
127
|
+
return mapped.map(branch => ({ ...branch, ...softDelete, ...ownership }));
|
|
108
128
|
}
|
|
109
129
|
else {
|
|
110
|
-
return { ...mapped, ...ownership };
|
|
130
|
+
return { ...mapped, ...softDelete, ...ownership };
|
|
111
131
|
}
|
|
112
132
|
}
|
|
113
133
|
|
|
@@ -263,4 +283,50 @@ export class TypeOrmRepositoryAdapter<T extends ObjectLiteral> implements VexRep
|
|
|
263
283
|
const where = this.mergeFilter(filter as unknown as Filter<T>);
|
|
264
284
|
await this.repo.delete(where as FindOptionsWhere<T>);
|
|
265
285
|
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Tombstone the row: run the normal update-phase field machinery (so `updatedAt` /
|
|
289
|
+
* `updatedBy` record who deleted it and when), then write the marker plus any redaction
|
|
290
|
+
* the caller merged in.
|
|
291
|
+
*/
|
|
292
|
+
async softDelete(id: string | undefined, data?: Partial<T>): Promise<T | null> {
|
|
293
|
+
if (!id) {
|
|
294
|
+
utils.log.error("TypeOrmRepositoryAdapter.softDelete called without id — refuse update entity");
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const field = entitySoftDeleteFields[this.getEntityName()];
|
|
299
|
+
if (!field) {
|
|
300
|
+
utils.log.error(
|
|
301
|
+
`TypeOrmRepositoryAdapter.softDelete on ${this.getEntityName()} — entity declares no ` +
|
|
302
|
+
`x-vexData "softDelete" field, refuse update entity`
|
|
303
|
+
);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const enriched = { ...(data ?? {}) } as Record<string, unknown>;
|
|
308
|
+
this.applyVexFields(enriched as Partial<T>, "update");
|
|
309
|
+
enriched[field] = true;
|
|
310
|
+
|
|
311
|
+
const where = this.mergeFilter({ _id: id } as unknown as Filter<T>);
|
|
312
|
+
// the generic ObjectLiteral constraint makes TypeORM's own _QueryDeepPartialEntity
|
|
313
|
+
// unresolvable here; `update` already accepts the same shape on the ordinary path
|
|
314
|
+
await this.repo.update(where as FindOptionsWhere<T>, enriched as never);
|
|
315
|
+
return this.repo.findOne({
|
|
316
|
+
where: { _id: id } as unknown as T
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Read a row that may be soft-deleted: skips the soft-delete term only, so the ownership
|
|
322
|
+
* filter still applies. Framework-internal — see VexRepository.
|
|
323
|
+
*/
|
|
324
|
+
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<T | null> {
|
|
325
|
+
const where = this.mergeFilter(filter, { includeSoftDeleted: true }) as FindOptionsWhere<T>;
|
|
326
|
+
return this.repo.findOne({
|
|
327
|
+
select,
|
|
328
|
+
where,
|
|
329
|
+
relations: join
|
|
330
|
+
});
|
|
331
|
+
}
|
|
266
332
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// {{headerComment}}
|
|
2
2
|
import { Profile } from "passport";
|
|
3
3
|
import { UserWithRelations } from "./../../_types/User.gen";
|
|
4
|
+
import { entitySoftDeleteFields } from "./../../_middlewares/VexFieldRegistry.gen";
|
|
4
5
|
|
|
5
6
|
export interface IProfile extends Profile {
|
|
6
7
|
[key: string]: any;
|
|
@@ -24,28 +25,46 @@ export default class OAuthProfileMap {
|
|
|
24
25
|
return authProfile;
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Seed the soft-delete marker on a brand-new OAuth user.
|
|
30
|
+
*
|
|
31
|
+
* `User` is only soft-deletable in projects that tag a marker, and when they do the field is
|
|
32
|
+
* required — so the profile built here must carry it. Reusing the registry keeps this template
|
|
33
|
+
* correct for both kinds of project, including one whose marker is not named "deleted".
|
|
34
|
+
*
|
|
35
|
+
* The marker is assigned onto the finished profile rather than spread into its literal: the
|
|
36
|
+
* field name is only known at runtime, and a spread of a `Record<string, boolean>` widens the
|
|
37
|
+
* property to `boolean | undefined`, which the required `User` field rejects.
|
|
38
|
+
*/
|
|
39
|
+
private applyNewUserMarker(user: UserWithRelations): UserWithRelations {
|
|
40
|
+
const field = entitySoftDeleteFields["UserEntity"];
|
|
41
|
+
if (field) (user as unknown as Record<string, unknown>)[field] = false;
|
|
42
|
+
|
|
43
|
+
return user;
|
|
44
|
+
}
|
|
45
|
+
|
|
27
46
|
private GithubProfileMapping(oauthProfile: IProfile): UserWithRelations {
|
|
28
|
-
const user
|
|
47
|
+
const user = {
|
|
29
48
|
active: true,
|
|
30
49
|
userAuthProfiles: [{
|
|
31
50
|
provider: oauthProfile.provider,
|
|
32
|
-
|
|
51
|
+
providerUserId: oauthProfile.id,
|
|
33
52
|
username: oauthProfile.username || oauthProfile.displayName
|
|
34
53
|
}],
|
|
35
54
|
name: oauthProfile.username || oauthProfile.displayName,
|
|
36
55
|
email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
|
|
37
56
|
locale: undefined,
|
|
38
57
|
profileErrors: ""
|
|
39
|
-
};
|
|
58
|
+
} as unknown as UserWithRelations;
|
|
40
59
|
|
|
41
|
-
return user;
|
|
60
|
+
return this.applyNewUserMarker(user);
|
|
42
61
|
}
|
|
43
62
|
private GoogleProfileMapping(oauthProfile: IProfile): UserWithRelations {
|
|
44
|
-
const user
|
|
63
|
+
const user = {
|
|
45
64
|
active: true,
|
|
46
65
|
userAuthProfiles: [{
|
|
47
66
|
provider: oauthProfile.provider,
|
|
48
|
-
|
|
67
|
+
providerUserId: oauthProfile.id,
|
|
49
68
|
username: oauthProfile.username || oauthProfile.displayName
|
|
50
69
|
}],
|
|
51
70
|
name: oauthProfile.username || oauthProfile.displayName,
|
|
@@ -53,9 +72,9 @@ export default class OAuthProfileMap {
|
|
|
53
72
|
email: oauthProfile._json.email || oauthProfile._json.notification_email || undefined,
|
|
54
73
|
locale: oauthProfile._json.locale || undefined,
|
|
55
74
|
profileErrors: ""
|
|
56
|
-
};
|
|
75
|
+
} as unknown as UserWithRelations;
|
|
57
76
|
|
|
58
|
-
return user;
|
|
77
|
+
return this.applyNewUserMarker(user);
|
|
59
78
|
}
|
|
60
79
|
|
|
61
80
|
}
|
|
@@ -26,11 +26,11 @@ export default class OAuthStrategyService {
|
|
|
26
26
|
const authUser = new OAuthProfileMap().map(profile);
|
|
27
27
|
const authProfile = authUser.userAuthProfiles?.[0];
|
|
28
28
|
|
|
29
|
-
// find user by
|
|
29
|
+
// find user by providerUserId + provider, or fall back to email
|
|
30
30
|
let existingUser: UserWithRelations | null = null;
|
|
31
|
-
if (authProfile?.
|
|
31
|
+
if (authProfile?.providerUserId && authProfile?.provider) {
|
|
32
32
|
const matchedProfile = await this.uapRepo.findOneWhere(
|
|
33
|
-
{
|
|
33
|
+
{ providerUserId: authProfile.providerUserId, provider: authProfile.provider },
|
|
34
34
|
);
|
|
35
35
|
if (matchedProfile?.userId) {
|
|
36
36
|
existingUser = await this.userRepo.findOne({ _id: matchedProfile.userId });
|
|
@@ -84,9 +84,9 @@ export default class OAuthStrategyService {
|
|
|
84
84
|
throw new Error("Invalid OAuth Callback \"authProfile\"");
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
-
// check if this provider/
|
|
87
|
+
// check if this provider/providerUserId already tracked
|
|
88
88
|
const existing = await this.uapRepo.findOneWhere(
|
|
89
|
-
{ userId: existingUser._id, provider: incomingProfile.provider,
|
|
89
|
+
{ userId: existingUser._id, provider: incomingProfile.provider, providerUserId: incomingProfile.providerUserId },
|
|
90
90
|
);
|
|
91
91
|
|
|
92
92
|
if (!existing) {
|
|
@@ -14,6 +14,29 @@ export interface registerResponse {
|
|
|
14
14
|
message: string
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* A redirect back to the client carrying a single-use `sessionCode`, which the client exchanges at
|
|
19
|
+
* `POST /auth/token` for the token pair.
|
|
20
|
+
*
|
|
21
|
+
* Neutral name on purpose: `/auth/local` and `/auth/external` both answer with this shape, and the two
|
|
22
|
+
* are independently enabled (`localAuth` vs `auth.externalIdentity`), so the type cannot live behind
|
|
23
|
+
* either flag.
|
|
24
|
+
*/
|
|
25
|
+
export interface loginRedirectResponse {
|
|
18
26
|
url: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Row counts removed alongside the tombstone, so the caller can log and retry. */
|
|
30
|
+
export interface deleteAccountCounts {
|
|
31
|
+
authProfiles: number;
|
|
32
|
+
userRoles: number;
|
|
33
|
+
sessions: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Result of a self-service account deletion. */
|
|
37
|
+
export interface deleteAccountResponse {
|
|
38
|
+
userId: string;
|
|
39
|
+
/** When the tombstone was written (the row's updatedAt). Empty on a repeat call. */
|
|
40
|
+
tombstonedAt: string;
|
|
41
|
+
deleted: deleteAccountCounts;
|
|
19
42
|
}
|
|
@@ -20,5 +20,26 @@ export interface VexRepository<T, U=undefined> {
|
|
|
20
20
|
update(id: string | undefined, data: Partial<T>): Promise<T | null>;
|
|
21
21
|
delete(id: string | undefined): Promise<void>;
|
|
22
22
|
deleteWhere(filter: Filter<T>): Promise<void>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Mark an entity soft-deleted, optionally merging app-level redaction into the same write.
|
|
26
|
+
*
|
|
27
|
+
* Runs the normal update-phase machinery, so `updatedAt` / `updatedBy` record who tombstoned
|
|
28
|
+
* the row and when. No-op returning null when the entity declares no marker.
|
|
29
|
+
*
|
|
30
|
+
* Only for framework-internal callers: the marker is deliberately not part of `Filter`, and
|
|
31
|
+
* it is stripped from every generated request body, so no client can reach this through the API.
|
|
32
|
+
*/
|
|
33
|
+
softDelete(id: string | undefined, data?: Partial<T>): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Read a row that may be soft-deleted.
|
|
37
|
+
*
|
|
38
|
+
* Skips ONLY the adapter's soft-delete term — the ownership filter still applies, so this is
|
|
39
|
+
* not a way around `dataIsolation`. Exists for internal state checks (account-deletion
|
|
40
|
+
* idempotency, the account-state guard); a `Filter`-level escape hatch would have been part of
|
|
41
|
+
* every HTTP filter body, which is exactly what must not be possible.
|
|
42
|
+
*/
|
|
43
|
+
findOneWithDeleted(filter: Filter<T>, join?: Join, select?: Select): Promise<[U] extends [undefined] ? T | null : U | null>;
|
|
23
44
|
}
|
|
24
45
|
|
|
@@ -65,10 +65,17 @@
|
|
|
65
65
|
"type": "string",
|
|
66
66
|
"x-format": "UUID",
|
|
67
67
|
"default": "onUpdateUserId"
|
|
68
|
+
},
|
|
69
|
+
"deleted": {
|
|
70
|
+
"type": "boolean",
|
|
71
|
+
"default": false,
|
|
72
|
+
"x-vexData": "softDelete",
|
|
73
|
+
"description": "Soft-delete marker. Framework-managed; never client-writable. Hides the row from every ordinary query unless app.showSoftDeleted is on."
|
|
68
74
|
}
|
|
69
75
|
},
|
|
70
76
|
"required": [
|
|
71
77
|
"name",
|
|
72
|
-
"active"
|
|
78
|
+
"active",
|
|
79
|
+
"deleted"
|
|
73
80
|
]
|
|
74
81
|
}
|
|
@@ -5,7 +5,13 @@
|
|
|
5
5
|
"methods": [],
|
|
6
6
|
"joinWhitelist": []
|
|
7
7
|
},
|
|
8
|
-
"documentName": "UserAuthProfiles"
|
|
8
|
+
"documentName": "UserAuthProfiles",
|
|
9
|
+
"uniqueIndex": [
|
|
10
|
+
[
|
|
11
|
+
"provider",
|
|
12
|
+
"providerUserId"
|
|
13
|
+
]
|
|
14
|
+
]
|
|
9
15
|
},
|
|
10
16
|
"properties": {
|
|
11
17
|
"_id": {
|
|
@@ -25,11 +31,13 @@
|
|
|
25
31
|
},
|
|
26
32
|
"provider": {
|
|
27
33
|
"type": "string",
|
|
28
|
-
"index": true
|
|
34
|
+
"index": true,
|
|
35
|
+
"description": "Namespace label of the identity source: an upstream IdP (\"google\"), a broker (\"firebase\"), or vex's own password path (\"local\"). The value \"local\" is reserved."
|
|
29
36
|
},
|
|
30
|
-
"
|
|
37
|
+
"providerUserId": {
|
|
31
38
|
"type": "string",
|
|
32
|
-
"index": true
|
|
39
|
+
"index": true,
|
|
40
|
+
"description": "External subject within `provider`'s namespace. With `provider` it forms the account-linking key and the composite unique index. NULL for provider=\"local\". This is the subject (an OIDC `sub` or a broker user id), never a token."
|
|
33
41
|
},
|
|
34
42
|
"email": {
|
|
35
43
|
"type": "string"
|
|
@@ -42,4 +50,4 @@
|
|
|
42
50
|
"x-hidden": true
|
|
43
51
|
}
|
|
44
52
|
}
|
|
45
|
-
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Self-service account deletion page.
|
|
2
|
+
//
|
|
3
|
+
// Sends the access token the same way the rest of the app does — Authorization + X-Auth-Index —
|
|
4
|
+
// and clears the stored tokens on success, because the account is gone the moment the tombstone
|
|
5
|
+
// is written: keeping a token the server will now reject only produces confusing 401s.
|
|
6
|
+
|
|
7
|
+
// The page loads this script from <head>, so it must wait for the DOM: at parse time the
|
|
8
|
+
// button does not exist yet and getElementById would return null.
|
|
9
|
+
document.addEventListener("DOMContentLoaded", function () {
|
|
10
|
+
var button = document.getElementById("deleteAccountBtn");
|
|
11
|
+
var input = document.getElementById("confirmInput");
|
|
12
|
+
var result = document.getElementById("deleteResult");
|
|
13
|
+
|
|
14
|
+
if (!button || !input || !result) return;
|
|
15
|
+
|
|
16
|
+
function clearTokens() {
|
|
17
|
+
localStorage.removeItem("accessToken");
|
|
18
|
+
localStorage.removeItem("accessTokenIndex");
|
|
19
|
+
localStorage.removeItem("refreshToken");
|
|
20
|
+
localStorage.removeItem("refreshTokenIndex");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function render(data) {
|
|
24
|
+
result.textContent = JSON.stringify(data, null, 2);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Deletion is self-service and the server resolves the account from the token alone, so with no
|
|
29
|
+
* token there is nothing to delete: sending an empty `Bearer ` would only earn a bare 401 that
|
|
30
|
+
* reads like a server fault. Point at the login page instead.
|
|
31
|
+
*
|
|
32
|
+
* Both credentials are required — `Authentication.middleware` treats them as one requirement — so
|
|
33
|
+
* a half-populated store counts as "not signed in" rather than as an API call.
|
|
34
|
+
*
|
|
35
|
+
* Note this file is copied into a project once and never overwritten, so a project generated
|
|
36
|
+
* before these checks existed keeps the old behaviour until it is updated by hand.
|
|
37
|
+
*/
|
|
38
|
+
function signedIn() {
|
|
39
|
+
return !!localStorage.getItem("accessToken") && !!localStorage.getItem("accessTokenIndex");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function notSignedIn() {
|
|
43
|
+
render({
|
|
44
|
+
status: 401,
|
|
45
|
+
error: "You are not signed in. Deletion is self-service and the server takes the account " +
|
|
46
|
+
"from your access token, so sign in first.",
|
|
47
|
+
signIn: "/login",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A 401 from the server means the stored credential was not accepted — expired, or already
|
|
53
|
+
* tombstoned. Deliberately does NOT clear it: the request may equally have failed for a reason
|
|
54
|
+
* that has nothing to do with the token, and dropping the session on any failure would sign the
|
|
55
|
+
* user out of a working account. Sign in again and retry; the login flow overwrites both tokens.
|
|
56
|
+
*/
|
|
57
|
+
function sessionRejected(outcome) {
|
|
58
|
+
render({
|
|
59
|
+
status: outcome.status,
|
|
60
|
+
error: "Your session was not accepted, so nothing was deleted. It may have expired — " +
|
|
61
|
+
"sign in again and retry.",
|
|
62
|
+
detail: outcome.body,
|
|
63
|
+
signIn: "/login",
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
button.addEventListener("click", function () {
|
|
68
|
+
if (!signedIn()) {
|
|
69
|
+
notSignedIn();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (input.value !== "DELETE") {
|
|
74
|
+
render({ error: 'Type DELETE in the box to confirm.' });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
button.disabled = true;
|
|
79
|
+
render({ status: "Deleting…" });
|
|
80
|
+
|
|
81
|
+
fetch("/api/auth/delete-account", {
|
|
82
|
+
method: "POST",
|
|
83
|
+
credentials: "include",
|
|
84
|
+
headers: {
|
|
85
|
+
"Content-Type": "application/json",
|
|
86
|
+
"Authorization": "Bearer " + (localStorage.getItem("accessToken") || ""),
|
|
87
|
+
"X-Auth-Index": localStorage.getItem("accessTokenIndex") || "",
|
|
88
|
+
},
|
|
89
|
+
})
|
|
90
|
+
.then(function (response) {
|
|
91
|
+
// read as text first: an error response may not be JSON (a proxy or the
|
|
92
|
+
// express error handler can return HTML), and response.json() would then
|
|
93
|
+
// reject and hide the real status behind a parse error
|
|
94
|
+
return response.text().then(function (text) {
|
|
95
|
+
var body;
|
|
96
|
+
try {
|
|
97
|
+
body = text ? JSON.parse(text) : {};
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
body = { raw: text };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return { ok: response.ok, status: response.status, body: body };
|
|
104
|
+
});
|
|
105
|
+
})
|
|
106
|
+
.then(function (outcome) {
|
|
107
|
+
if (!outcome.ok) {
|
|
108
|
+
// 401 means the credential was not accepted. Say what to do about it rather than
|
|
109
|
+
// printing a raw error body the user cannot act on — see sessionRejected for why
|
|
110
|
+
// the stored tokens are left alone.
|
|
111
|
+
if (outcome.status === 401) {
|
|
112
|
+
sessionRejected(outcome);
|
|
113
|
+
button.disabled = false;
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
render({ status: outcome.status, error: outcome.body });
|
|
118
|
+
button.disabled = false;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
clearTokens();
|
|
123
|
+
render({
|
|
124
|
+
status: "Account deleted. You have been signed out.",
|
|
125
|
+
result: outcome.body,
|
|
126
|
+
});
|
|
127
|
+
input.value = "";
|
|
128
|
+
})
|
|
129
|
+
.catch(function (err) {
|
|
130
|
+
render({ error: String(err) });
|
|
131
|
+
button.disabled = false;
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
});
|