@aneuhold/be-ts-db-lib 4.2.19 → 4.2.20

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/CHANGELOG.md CHANGED
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## 🔖 [4.2.20] (2026-03-19)
9
+
10
+ ### ✅ Added
11
+
12
+ - Added `GoogleAuthService.verifyAndFindUser` method that returns `null` when no matching user exists (does not create one).
13
+
14
+ ### 🏗️ Changed
15
+
16
+ - Refactored `GoogleAuthService`: extracted private `verifyToken` helper and restructured `verifyAndFindOrCreateUser` to delegate to `verifyAndFindUser`.
17
+ - Refactored `MigrationService` to fill in missing `projectAccess` fields with safe defaults instead of patching `refreshTokenHashes`.
18
+ - Updated dependencies on `@aneuhold/be-ts-lib` to `^3.1.7` and `@aneuhold/core-ts-db-lib` to `^5.0.2`.
19
+
8
20
  ## 🔖 [4.2.19] (2026-03-18)
9
21
 
10
22
  ### ✅ Added
@@ -348,6 +360,7 @@ Updated dependencies: now requires `@aneuhold/core-ts-db-lib@^3.0.0`, `@aneuhold
348
360
 
349
361
  <!-- Link References -->
350
362
 
363
+ [4.2.20]: https://github.com/aneuhold/ts-libs/compare/be-ts-db-lib-v4.2.19...be-ts-db-lib-v4.2.20
351
364
  [4.2.19]: https://github.com/aneuhold/ts-libs/compare/be-ts-db-lib-v4.2.18...be-ts-db-lib-v4.2.19
352
365
  [4.2.18]: https://github.com/aneuhold/ts-libs/compare/be-ts-db-lib-v4.2.17...be-ts-db-lib-v4.2.18
353
366
  [4.2.17]: https://github.com/aneuhold/ts-libs/compare/be-ts-db-lib-v4.2.16...be-ts-db-lib-v4.2.17
@@ -6,6 +6,16 @@ import type { ApiKey, User } from '@aneuhold/core-ts-db-lib';
6
6
  */
7
7
  export default class GoogleAuthService {
8
8
  private static readonly client;
9
+ /**
10
+ * Verifies a Google ID token and finds the associated user. Returns
11
+ * `null` if no matching user exists (does **not** create one).
12
+ *
13
+ * @param googleCredentialToken - The Google ID token string from the client.
14
+ */
15
+ static verifyAndFindUser(googleCredentialToken: string): Promise<{
16
+ user: User;
17
+ apiKey: ApiKey;
18
+ } | null>;
9
19
  /**
10
20
  * Verifies a Google ID token and finds or creates the associated user.
11
21
  *
@@ -15,5 +25,11 @@ export default class GoogleAuthService {
15
25
  user: User;
16
26
  apiKey: ApiKey;
17
27
  }>;
28
+ /**
29
+ * Verifies a Google ID token and returns the Google ID and email.
30
+ *
31
+ * @param googleCredentialToken - The Google ID token string from the client.
32
+ */
33
+ private static verifyToken;
18
34
  }
19
35
  //# sourceMappingURL=GoogleAuthService.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"GoogleAuthService.d.ts","sourceRoot":"","sources":["../../src/services/GoogleAuthService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAM7D;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,iBAAiB;IACpC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAsC;IAEpE;;;;OAIG;WACU,yBAAyB,CACpC,qBAAqB,EAAE,MAAM,GAC5B,OAAO,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CAsD3C"}
1
+ {"version":3,"file":"GoogleAuthService.d.ts","sourceRoot":"","sources":["../../src/services/GoogleAuthService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAM7D;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,iBAAiB;IACpC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAsC;IAEpE;;;;;OAKG;WACU,iBAAiB,CAC5B,qBAAqB,EAAE,MAAM,GAC5B,OAAO,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IA+BjD;;;;OAIG;WACU,yBAAyB,CACpC,qBAAqB,EAAE,MAAM,GAC5B,OAAO,CAAC;QAAE,IAAI,EAAE,IAAI,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IA+B1C;;;;OAIG;mBACkB,WAAW;CAmBjC"}
@@ -1,4 +1,4 @@
1
- import { GOOGLE_CLIENT_ID, UserSchema } from '@aneuhold/core-ts-db-lib';
1
+ import { GOOGLE_CLIENT_ID, ProjectName, UserSchema } from '@aneuhold/core-ts-db-lib';
2
2
  import { OAuth2Client } from 'google-auth-library';
3
3
  import ApiKeyRepository from '../repositories/common/ApiKeyRepository.js';
4
4
  import UserRepository from '../repositories/common/UserRepository.js';
@@ -10,23 +10,13 @@ import UserRepository from '../repositories/common/UserRepository.js';
10
10
  export default class GoogleAuthService {
11
11
  static client = new OAuth2Client(GOOGLE_CLIENT_ID);
12
12
  /**
13
- * Verifies a Google ID token and finds or creates the associated user.
13
+ * Verifies a Google ID token and finds the associated user. Returns
14
+ * `null` if no matching user exists (does **not** create one).
14
15
  *
15
16
  * @param googleCredentialToken - The Google ID token string from the client.
16
17
  */
17
- static async verifyAndFindOrCreateUser(googleCredentialToken) {
18
- const ticket = await this.client.verifyIdToken({
19
- idToken: googleCredentialToken,
20
- audience: GOOGLE_CLIENT_ID
21
- });
22
- const payload = ticket.getPayload();
23
- if (!payload) {
24
- throw new Error('Invalid Google token payload');
25
- }
26
- const { sub: googleId, email } = payload;
27
- if (!email) {
28
- throw new Error('Google account has no email');
29
- }
18
+ static async verifyAndFindUser(googleCredentialToken) {
19
+ const { googleId, email } = await this.verifyToken(googleCredentialToken);
30
20
  const userRepo = UserRepository.getRepo();
31
21
  const apiKeyRepo = ApiKeyRepository.getRepo();
32
22
  // 1. Look up by googleId
@@ -40,20 +30,8 @@ export default class GoogleAuthService {
40
30
  user.auth.googleId = googleId;
41
31
  }
42
32
  }
43
- // 3. Create new user if neither match. The ApiKey subscriber on
44
- // UserRepository automatically creates an API key on user insertion.
45
33
  if (!user) {
46
- const newUser = UserSchema.parse({
47
- userName: email,
48
- email,
49
- auth: { googleId },
50
- projectAccess: { dashboard: false, workout: true }
51
- });
52
- const insertedUser = await userRepo.insertNew(newUser);
53
- if (!insertedUser) {
54
- throw new Error('Failed to create user');
55
- }
56
- user = insertedUser;
34
+ return null;
57
35
  }
58
36
  const apiKey = await apiKeyRepo.get({ userId: user._id });
59
37
  if (!apiKey) {
@@ -61,5 +39,56 @@ export default class GoogleAuthService {
61
39
  }
62
40
  return { user, apiKey };
63
41
  }
42
+ /**
43
+ * Verifies a Google ID token and finds or creates the associated user.
44
+ *
45
+ * @param googleCredentialToken - The Google ID token string from the client.
46
+ */
47
+ static async verifyAndFindOrCreateUser(googleCredentialToken) {
48
+ const result = await this.verifyAndFindUser(googleCredentialToken);
49
+ if (result) {
50
+ return result;
51
+ }
52
+ // Create new user. The ApiKey subscriber on UserRepository automatically
53
+ // creates an API key on user insertion.
54
+ const { googleId, email } = await this.verifyToken(googleCredentialToken);
55
+ const userRepo = UserRepository.getRepo();
56
+ const apiKeyRepo = ApiKeyRepository.getRepo();
57
+ const newUser = UserSchema.parse({
58
+ userName: email,
59
+ email,
60
+ auth: { googleId },
61
+ projectAccess: { [ProjectName.Dashboard]: false, [ProjectName.Workout]: true }
62
+ });
63
+ const insertedUser = await userRepo.insertNew(newUser);
64
+ if (!insertedUser) {
65
+ throw new Error('Failed to create user');
66
+ }
67
+ const apiKey = await apiKeyRepo.get({ userId: insertedUser._id });
68
+ if (!apiKey) {
69
+ throw new Error(`No API key found for user ${insertedUser._id}`);
70
+ }
71
+ return { user: insertedUser, apiKey };
72
+ }
73
+ /**
74
+ * Verifies a Google ID token and returns the Google ID and email.
75
+ *
76
+ * @param googleCredentialToken - The Google ID token string from the client.
77
+ */
78
+ static async verifyToken(googleCredentialToken) {
79
+ const ticket = await this.client.verifyIdToken({
80
+ idToken: googleCredentialToken,
81
+ audience: GOOGLE_CLIENT_ID
82
+ });
83
+ const payload = ticket.getPayload();
84
+ if (!payload) {
85
+ throw new Error('Invalid Google token payload');
86
+ }
87
+ const { sub: googleId, email } = payload;
88
+ if (!email) {
89
+ throw new Error('Google account has no email');
90
+ }
91
+ return { googleId, email };
92
+ }
64
93
  }
65
94
  //# sourceMappingURL=GoogleAuthService.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GoogleAuthService.js","sourceRoot":"","sources":["../../src/services/GoogleAuthService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,gBAAgB,MAAM,4CAA4C,CAAC;AAC1E,OAAO,cAAc,MAAM,0CAA0C,CAAC;AAEtE;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,iBAAiB;IAC5B,MAAM,CAAU,MAAM,GAAG,IAAI,YAAY,CAAC,gBAAgB,CAAC,CAAC;IAEpE;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,yBAAyB,CACpC,qBAA6B;QAE7B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC;YAC7C,OAAO,EAAE,qBAAqB;YAC9B,QAAQ,EAAE,gBAAgB;SAC3B,CAAC,CAAC;QACH,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;QACpC,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;QAClD,CAAC;QAED,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;QACzC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM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ts-db-lib';
2
- import { GOOGLE_CLIENT_ID, UserSchema } from '@aneuhold/core-ts-db-lib';
2
+ import { GOOGLE_CLIENT_ID, ProjectName, UserSchema } from '@aneuhold/core-ts-db-lib';
3
3
  import { OAuth2Client } from 'google-auth-library';
4
4
  import ApiKeyRepository from '../repositories/common/ApiKeyRepository.js';
5
5
  import UserRepository from '../repositories/common/UserRepository.js';
@@ -13,26 +13,15 @@ export default class GoogleAuthService {
13
13
  private static readonly client = new OAuth2Client(GOOGLE_CLIENT_ID);
14
14
 
15
15
  /**
16
- * Verifies a Google ID token and finds or creates the associated user.
16
+ * Verifies a Google ID token and finds the associated user. Returns
17
+ * `null` if no matching user exists (does **not** create one).
17
18
  *
18
19
  * @param googleCredentialToken - The Google ID token string from the client.
19
20
  */
20
- static async verifyAndFindOrCreateUser(
21
+ static async verifyAndFindUser(
21
22
  googleCredentialToken: string
22
- ): Promise<{ user: User; apiKey: ApiKey }> {
23
- const ticket = await this.client.verifyIdToken({
24
- idToken: googleCredentialToken,
25
- audience: GOOGLE_CLIENT_ID
26
- });
27
- const payload = ticket.getPayload();
28
- if (!payload) {
29
- throw new Error('Invalid Google token payload');
30
- }
31
-
32
- const { sub: googleId, email } = payload;
33
- if (!email) {
34
- throw new Error('Google account has no email');
35
- }
23
+ ): Promise<{ user: User; apiKey: ApiKey } | null> {
24
+ const { googleId, email } = await this.verifyToken(googleCredentialToken);
36
25
 
37
26
  const userRepo = UserRepository.getRepo();
38
27
  const apiKeyRepo = ApiKeyRepository.getRepo();
@@ -50,20 +39,8 @@ export default class GoogleAuthService {
50
39
  }
51
40
  }
52
41
 
53
- // 3. Create new user if neither match. The ApiKey subscriber on
54
- // UserRepository automatically creates an API key on user insertion.
55
42
  if (!user) {
56
- const newUser = UserSchema.parse({
57
- userName: email,
58
- email,
59
- auth: { googleId },
60
- projectAccess: { dashboard: false, workout: true }
61
- });
62
- const insertedUser = await userRepo.insertNew(newUser);
63
- if (!insertedUser) {
64
- throw new Error('Failed to create user');
65
- }
66
- user = insertedUser;
43
+ return null;
67
44
  }
68
45
 
69
46
  const apiKey = await apiKeyRepo.get({ userId: user._id });
@@ -73,4 +50,67 @@ export default class GoogleAuthService {
73
50
 
74
51
  return { user, apiKey };
75
52
  }
53
+
54
+ /**
55
+ * Verifies a Google ID token and finds or creates the associated user.
56
+ *
57
+ * @param googleCredentialToken - The Google ID token string from the client.
58
+ */
59
+ static async verifyAndFindOrCreateUser(
60
+ googleCredentialToken: string
61
+ ): Promise<{ user: User; apiKey: ApiKey }> {
62
+ const result = await this.verifyAndFindUser(googleCredentialToken);
63
+ if (result) {
64
+ return result;
65
+ }
66
+
67
+ // Create new user. The ApiKey subscriber on UserRepository automatically
68
+ // creates an API key on user insertion.
69
+ const { googleId, email } = await this.verifyToken(googleCredentialToken);
70
+ const userRepo = UserRepository.getRepo();
71
+ const apiKeyRepo = ApiKeyRepository.getRepo();
72
+
73
+ const newUser = UserSchema.parse({
74
+ userName: email,
75
+ email,
76
+ auth: { googleId },
77
+ projectAccess: { [ProjectName.Dashboard]: false, [ProjectName.Workout]: true }
78
+ });
79
+ const insertedUser = await userRepo.insertNew(newUser);
80
+ if (!insertedUser) {
81
+ throw new Error('Failed to create user');
82
+ }
83
+
84
+ const apiKey = await apiKeyRepo.get({ userId: insertedUser._id });
85
+ if (!apiKey) {
86
+ throw new Error(`No API key found for user ${insertedUser._id}`);
87
+ }
88
+
89
+ return { user: insertedUser, apiKey };
90
+ }
91
+
92
+ /**
93
+ * Verifies a Google ID token and returns the Google ID and email.
94
+ *
95
+ * @param googleCredentialToken - The Google ID token string from the client.
96
+ */
97
+ private static async verifyToken(
98
+ googleCredentialToken: string
99
+ ): Promise<{ googleId: string; email: string }> {
100
+ const ticket = await this.client.verifyIdToken({
101
+ idToken: googleCredentialToken,
102
+ audience: GOOGLE_CLIENT_ID
103
+ });
104
+ const payload = ticket.getPayload();
105
+ if (!payload) {
106
+ throw new Error('Invalid Google token payload');
107
+ }
108
+
109
+ const { sub: googleId, email } = payload;
110
+ if (!email) {
111
+ throw new Error('Google account has no email');
112
+ }
113
+
114
+ return { googleId, email };
115
+ }
76
116
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MigrationService.d.ts","sourceRoot":"","sources":["../../src/services/MigrationService.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC;;;;;;;;OAQG;WACU,SAAS,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAoCtD"}
1
+ {"version":3,"file":"MigrationService.d.ts","sourceRoot":"","sources":["../../src/services/MigrationService.ts"],"names":[],"mappings":"AAeA;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC;;;;;;;;OAQG;WACU,SAAS,CAAC,MAAM,UAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CAkDtD"}
@@ -2,6 +2,15 @@
2
2
  // @ts-nocheck
3
3
  import { DR } from '@aneuhold/core-ts-lib';
4
4
  import UserRepository from '../repositories/common/UserRepository.js';
5
+ /**
6
+ * The default values for each project access field. New fields should be
7
+ * added here and defaulted to `false` so existing users don't gain access
8
+ * automatically.
9
+ */
10
+ const PROJECT_ACCESS_DEFAULTS = {
11
+ dashboard: false,
12
+ workout: false
13
+ };
5
14
  /**
6
15
  * A service for migrating the DB to a new state after an existing document
7
16
  * change.
@@ -23,9 +32,14 @@ export default class MigrationService {
23
32
  DR.logger.info('Starting migration...');
24
33
  const userRepo = UserRepository.getRepo();
25
34
  const users = await userRepo.getAll();
26
- // Add refreshTokenHashes to users that don't have it yet
27
- const usersToUpdate = users.filter((user) => !user.auth.refreshTokenHashes);
28
- DR.logger.info(`Found ${usersToUpdate.length} of ${users.length} users missing auth.refreshTokenHashes.`);
35
+ // Find users that are missing projectAccess entirely or are missing
36
+ // any of the expected fields.
37
+ const usersToUpdate = users.filter((user) => {
38
+ if (!user.projectAccess)
39
+ return true;
40
+ return Object.keys(PROJECT_ACCESS_DEFAULTS).some((key) => user.projectAccess[key] === undefined);
41
+ });
42
+ DR.logger.info(`Found ${usersToUpdate.length} of ${users.length} users with missing projectAccess fields.`);
29
43
  if (usersToUpdate.length === 0) {
30
44
  DR.logger.success('No migration needed.');
31
45
  return;
@@ -33,16 +47,20 @@ export default class MigrationService {
33
47
  if (dryRun) {
34
48
  DR.logger.info('Dry run: Would update the following users:');
35
49
  usersToUpdate.forEach((user) => {
36
- DR.logger.info(` - ${user.userName} (${user._id})`);
50
+ const existing = user.projectAccess ?? {};
51
+ const merged = { ...PROJECT_ACCESS_DEFAULTS, ...existing };
52
+ DR.logger.info(` - ${user.userName} (${user._id}): ${JSON.stringify(existing)} → ${JSON.stringify(merged)}`);
37
53
  });
38
54
  return;
39
55
  }
40
56
  for (const user of usersToUpdate) {
57
+ const existing = user.projectAccess ?? {};
58
+ const merged = { ...PROJECT_ACCESS_DEFAULTS, ...existing };
41
59
  await userRepo.update({
42
60
  _id: user._id,
43
- auth: { ...user.auth, refreshTokenHashes: [] }
61
+ projectAccess: merged
44
62
  });
45
- DR.logger.info(`Updated user ${user.userName} (${user._id})`);
63
+ DR.logger.info(`Updated user ${user.userName} (${user._id}): ${JSON.stringify(existing)} → ${JSON.stringify(merged)}`);
46
64
  }
47
65
  DR.logger.success(`Migration complete. Updated ${usersToUpdate.length} users.`);
48
66
  }
@@ -1 +1 @@
1
- {"version":3,"file":"MigrationService.js","sourceRoot":"","sources":["../../src/services/MigrationService.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,cAAc;AACd,OAAO,EAAE,EAAE,EAAE,MAAM,uBAAuB,CAAC;AAC3C,OAAO,cAAc,MAAM,0CAA0C,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,OAAO,gBAAgB;IACnC;;;;;;;;OAQG;IACH,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,KAAK;QACnC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,uBAAuB,CAAC,C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serRepository from '../repositories/common/UserRepository.js';
5
5
 
6
+ /**
7
+ * The default values for each project access field. New fields should be
8
+ * added here and defaulted to `false` so existing users don't gain access
9
+ * automatically.
10
+ */
11
+ const PROJECT_ACCESS_DEFAULTS = {
12
+ dashboard: false,
13
+ workout: false
14
+ };
15
+
6
16
  /**
7
17
  * A service for migrating the DB to a new state after an existing document
8
18
  * change.
@@ -26,11 +36,17 @@ export default class MigrationService {
26
36
  const userRepo = UserRepository.getRepo();
27
37
  const users = await userRepo.getAll();
28
38
 
29
- // Add refreshTokenHashes to users that don't have it yet
30
- const usersToUpdate = users.filter((user) => !user.auth.refreshTokenHashes);
39
+ // Find users that are missing projectAccess entirely or are missing
40
+ // any of the expected fields.
41
+ const usersToUpdate = users.filter((user) => {
42
+ if (!user.projectAccess) return true;
43
+ return Object.keys(PROJECT_ACCESS_DEFAULTS).some(
44
+ (key) => user.projectAccess[key] === undefined
45
+ );
46
+ });
31
47
 
32
48
  DR.logger.info(
33
- `Found ${usersToUpdate.length} of ${users.length} users missing auth.refreshTokenHashes.`
49
+ `Found ${usersToUpdate.length} of ${users.length} users with missing projectAccess fields.`
34
50
  );
35
51
 
36
52
  if (usersToUpdate.length === 0) {
@@ -41,17 +57,25 @@ export default class MigrationService {
41
57
  if (dryRun) {
42
58
  DR.logger.info('Dry run: Would update the following users:');
43
59
  usersToUpdate.forEach((user) => {
44
- DR.logger.info(` - ${user.userName} (${user._id})`);
60
+ const existing = user.projectAccess ?? {};
61
+ const merged = { ...PROJECT_ACCESS_DEFAULTS, ...existing };
62
+ DR.logger.info(
63
+ ` - ${user.userName} (${user._id}): ${JSON.stringify(existing)} → ${JSON.stringify(merged)}`
64
+ );
45
65
  });
46
66
  return;
47
67
  }
48
68
 
49
69
  for (const user of usersToUpdate) {
70
+ const existing = user.projectAccess ?? {};
71
+ const merged = { ...PROJECT_ACCESS_DEFAULTS, ...existing };
50
72
  await userRepo.update({
51
73
  _id: user._id,
52
- auth: { ...user.auth, refreshTokenHashes: [] }
74
+ projectAccess: merged
53
75
  });
54
- DR.logger.info(`Updated user ${user.userName} (${user._id})`);
76
+ DR.logger.info(
77
+ `Updated user ${user.userName} (${user._id}): ${JSON.stringify(existing)} → ${JSON.stringify(merged)}`
78
+ );
55
79
  }
56
80
 
57
81
  DR.logger.success(`Migration complete. Updated ${usersToUpdate.length} users.`);
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@aneuhold/be-ts-db-lib",
3
3
  "author": "Anton G. Neuhold Jr.",
4
4
  "license": "MIT",
5
- "version": "4.2.19",
5
+ "version": "4.2.20",
6
6
  "description": "A backend database library meant to actually interact with various databases in personal projects",
7
7
  "packageManager": "pnpm@10.25.0",
8
8
  "type": "module",
@@ -58,8 +58,8 @@
58
58
  "MongoDB"
59
59
  ],
60
60
  "dependencies": {
61
- "@aneuhold/be-ts-lib": "^3.1.6",
62
- "@aneuhold/core-ts-db-lib": "^5.0.1",
61
+ "@aneuhold/be-ts-lib": "^3.1.7",
62
+ "@aneuhold/core-ts-db-lib": "^5.0.2",
63
63
  "@aneuhold/core-ts-lib": "^2.4.3",
64
64
  "bson": "^7.0.0",
65
65
  "google-auth-library": "^10.6.1",