@tech4good/angular-schematics 21.5.0 → 21.6.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.
Files changed (100) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +2 -1
  4. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +2 -1
  5. package/src/entity/index.js +57 -0
  6. package/src/entity/index.js.map +1 -1
  7. package/src/entity/schema.json +4 -0
  8. package/src/ng-add/files/.gitignore.template +2 -0
  9. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +270 -0
  10. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +16 -10
  11. package/src/ng-add/files/firebase.json.template +6 -0
  12. package/src/ng-add/files/firestore.indexes.json.template +23 -0
  13. package/src/ng-add/files/firestore.rules.spec.ts.template +84 -15
  14. package/src/ng-add/files/firestore.rules.template +29 -17
  15. package/src/ng-add/files/functions/.gitignore.template +3 -0
  16. package/src/ng-add/files/functions/package.json.template +12 -0
  17. package/src/ng-add/files/functions/src/index.ts.template +44 -0
  18. package/src/ng-add/files/functions/tsconfig.json.template +13 -0
  19. package/src/ng-add/files/package.json.template +5 -3
  20. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +3 -1
  21. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +6 -8
  22. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +2 -0
  23. package/src/ng-add/files/src/app/app.component.html.template +2 -2
  24. package/src/ng-add/files/src/app/app.component.ts.template +2 -0
  25. package/src/ng-add/files/src/app/app.routes.ts.template +6 -0
  26. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +9 -4
  27. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +6 -1
  28. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +38 -0
  29. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +3 -2
  30. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +7 -2
  31. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +11 -5
  32. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +34 -17
  33. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +59 -0
  34. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +147 -0
  35. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +104 -17
  36. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +116 -0
  37. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +367 -70
  38. package/src/ng-add/files/src/app/core/store/app.store.ts.template +4 -1
  39. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +52 -66
  40. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +127 -0
  41. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +216 -147
  42. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +2 -4
  43. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +1 -1
  44. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +1 -0
  45. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.html.template +4 -0
  46. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.scss.template +1 -0
  47. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.ts.template +38 -0
  48. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +5 -1
  49. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +12 -1
  50. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +93 -48
  51. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +5 -1
  52. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.html.template +18 -0
  53. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.scss.template +2 -0
  54. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +40 -0
  55. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +76 -0
  56. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +7 -2
  57. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +19 -7
  58. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +51 -0
  59. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +29 -5
  60. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +2 -1
  61. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +12 -8
  62. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +31 -10
  63. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +6 -19
  64. package/src/ng-add/files/src/app/first-time/login/login.component.html.template +58 -6
  65. package/src/ng-add/files/src/app/first-time/login/login.component.scss.template +151 -22
  66. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +18 -38
  67. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +59 -31
  68. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.html.template +12 -0
  69. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.scss.template +39 -0
  70. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +68 -0
  71. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.ts.template +20 -0
  72. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.html.template +24 -0
  73. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.scss.template +50 -0
  74. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +65 -0
  75. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.ts.template +59 -0
  76. package/src/ng-add/files/src/app/main/account-profile/guest-deletion-dialog.component.ts.template +51 -0
  77. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.html.template +50 -0
  78. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.scss.template +137 -0
  79. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +57 -0
  80. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.ts.template +59 -0
  81. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.html.template +133 -0
  82. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.scss.template +207 -0
  83. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +74 -0
  84. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.ts.template +130 -0
  85. package/src/ng-add/files/src/app/main/home/home.component.ts.template +0 -5
  86. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.html.template +15 -0
  87. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.scss.template +79 -0
  88. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +59 -0
  89. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.ts.template +44 -0
  90. package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +45 -15
  91. package/src/ng-add/files/src/app/shared/navbar/navbar.component.scss.template +103 -19
  92. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +73 -9
  93. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +46 -18
  94. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  95. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  96. package/src/ng-add/files/src/environments/environment.ts.template +1 -1
  97. package/src/ng-add/index_spec.d.ts +1 -0
  98. package/src/ng-add/index_spec.js +108 -0
  99. package/src/ng-add/index_spec.js.map +1 -0
  100. package/tsconfig.json +2 -2
@@ -4,6 +4,7 @@ import { map } from 'rxjs/operators';
4
4
  import { AuthService } from '../auth.service';
5
5
  import { AccessState, User } from '../../store/user/user.model';
6
6
  import { hasAdminOverride } from './admin-override';
7
+ import { environment } from 'src/environments/environment';
7
8
 
8
9
  /**
9
10
  * Combined guard that checks authentication, admin overrides, and full
@@ -16,7 +17,8 @@ import { hasAdminOverride } from './admin-override';
16
17
  * Checks performed in order:
17
18
  * 1. Not logged in → redirect to `/landing`
18
19
  * 2. Admin with route in `adminOverridePaths` → allow immediately
19
- * 3. `accessState` is `SUBMIT_INTEREST` or `WAITING` → redirect to `/early-access`
20
+ * 3. `accessState` is `SUBMIT_INTEREST` (or `WAITING` when the waitlist is enabled)
21
+ * → redirect to `/early-access`
20
22
  * 4. `accessState` is not `DONE` or `consented` is false → redirect to `/consent`
21
23
  * 5. Otherwise → allow
22
24
  */
@@ -25,6 +27,7 @@ export function handleAccess(
25
27
  router: Router,
26
28
  route: ActivatedRouteSnapshot,
27
29
  state: RouterStateSnapshot,
30
+ hasWaitlist: boolean = environment.hasWaitlist,
28
31
  ): boolean {
29
32
  // Step 1: Not logged in → landing
30
33
  if (!user) {
@@ -38,7 +41,9 @@ export function handleAccess(
38
41
  }
39
42
 
40
43
  // Step 3: Still on the waitlist → early-access
41
- const waitingStates = [AccessState.SUBMIT_INTEREST, AccessState.WAITING];
44
+ const waitingStates = hasWaitlist ?
45
+ [AccessState.SUBMIT_INTEREST, AccessState.WAITING] :
46
+ [AccessState.SUBMIT_INTEREST];
42
47
  if (waitingStates.includes(user.accessState)) {
43
48
  router.navigate(['/early-access'], { queryParams: route.queryParams });
44
49
  return false;
@@ -94,12 +94,10 @@ export class CachedListenersService {
94
94
  }
95
95
 
96
96
  /**
97
- * Clear cached connection states and last load times.
98
- * NOTE: This is strictly intended for resetting state between test cases
99
- * in unit/integration tests and should not be used in dev/production environments
100
- * to avoid unexpected stream disconnections.
97
+ * Tears down active Firestore listeners before authentication is removed.
98
+ * Load-time tracking is also reset so the next account performs fresh queries.
101
99
  */
102
- clearCache(): void {
100
+ teardownAllStreams(): void {
103
101
  for (const key of Object.keys(this.connectionByQueryKey)) {
104
102
  const connection = this.connectionByQueryKey[key];
105
103
  if (connection) {
@@ -117,6 +115,14 @@ export class CachedListenersService {
117
115
  this.entityLoadTime = {};
118
116
  }
119
117
 
118
+ /**
119
+ * Clear cached connection states and last load times.
120
+ * NOTE: This is intended for resetting state between tests.
121
+ */
122
+ clearCache(): void {
123
+ this.teardownAllStreams();
124
+ }
125
+
120
126
  /** Return whether a stream exists for this query. */
121
127
  isStreamForQuery(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
122
128
  const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
@@ -4,18 +4,43 @@ import { Observable } from 'rxjs';
4
4
  import { User } from '@angular/fire/auth';
5
5
  import { WriteBatchI } from '../store/batch-write.service';
6
6
 
7
+ /** Firebase Authentication state needed by the application. */
8
+ export interface AuthSession {
9
+ uid: string;
10
+ email: string | null;
11
+ displayName: string | null;
12
+ photoURL: string | null;
13
+ isAnonymous: boolean;
14
+ emailVerified: boolean;
15
+ emailLinkEnabled: boolean;
16
+ providerIds: string[];
17
+ }
18
+
7
19
  export interface DatabaseService {
8
20
  createId(): string;
9
- afUser(): Observable<{ uid: string, email: string, displayName: string, photoURL: string } | null>;
10
- login(providerId: string, scope?: string): any;
11
- loginLink(error): void;
21
+ afUser(): Observable<AuthSession | null>;
22
+ signInWithGoogle(): Promise<AuthSession>;
23
+ signInAnonymously(): Promise<AuthSession>;
24
+ linkGoogle(): Promise<AuthSession>;
25
+ sendEmailSignInLink(email: string): Promise<void>;
26
+ sendEmailLinkForCurrentAccount(): Promise<void>;
27
+ getStoredEmailForEmailLink(): string | null;
28
+ completeEmailSignInLink(url: string, email: string): Promise<AuthSession>;
29
+ deleteAnonymousAccount(): Promise<void>;
30
+ ensureUserProfile(session: AuthSession): Promise<any>;
12
31
  logout(): any;
13
32
  streamEntity<T>(collectionName: string, id: string): Observable<T>;
14
33
  streamEntities<T>(collectionName, queryParams, queryOptions?): Observable<T[]>;
15
- streamEntitiesChanges<T>(collectionName, queryParams, queryOptions?): Observable<{
16
- type: string;
17
- docData: T;
18
- }[]>;
34
+ streamEntitiesChanges<T>(
35
+ collectionName,
36
+ queryParams,
37
+ queryOptions?,
38
+ ): Observable<
39
+ {
40
+ type: string;
41
+ docData: T;
42
+ }[]
43
+ >;
19
44
  getEntity<T>(collectionName: string, id: string): Promise<T>;
20
45
  getEntities<S>(
21
46
  collectionName: string,
@@ -33,22 +58,14 @@ export interface DatabaseService {
33
58
  queryOptions: QueryOptions,
34
59
  aggregateParams: { [K in keyof S]: [string] | [string, string] },
35
60
  ): Promise<{ [K in keyof S]: number }>;
36
- addEntity(
37
- collectionName: string,
38
- entity: AnyEntity,
39
- batch?: WriteBatchI,
40
- ): Promise<any>;
61
+ addEntity(collectionName: string, entity: AnyEntity, batch?: WriteBatchI): Promise<any>;
41
62
  updateEntity(
42
63
  collectionName: string,
43
64
  id: string,
44
65
  changes: Partial<AnyEntity>,
45
66
  batch?: WriteBatchI,
46
67
  ): Promise<any>;
47
- removeEntity(
48
- collectionName: string,
49
- id: string,
50
- batch?: WriteBatchI,
51
- ): Promise<any>;
68
+ removeEntity(collectionName: string, id: string, batch?: WriteBatchI): Promise<any>;
52
69
  incrementEntityField(collectionName, id, field, delta): Promise<void>;
53
70
  }
54
71
 
@@ -0,0 +1,59 @@
1
+ import { TestBed } from '@angular/core/testing';
2
+ import { EmailLinkContextService } from './email-link-context.service';
3
+
4
+ describe('EmailLinkContextService', () => {
5
+ let service: EmailLinkContextService;
6
+
7
+ beforeEach(() => {
8
+ TestBed.configureTestingModule({});
9
+ service = TestBed.inject(EmailLinkContextService);
10
+ service.clear();
11
+ });
12
+
13
+ afterEach(() => service.clear());
14
+
15
+ it('restores the pending email when local storage is unavailable on the callback', () => {
16
+ service.remember({
17
+ email: 'learner@example.com',
18
+ flow: 'sign-in',
19
+ uid: null,
20
+ });
21
+
22
+ localStorage.removeItem('app.email-link.email');
23
+ localStorage.removeItem('app.email-link.flow');
24
+
25
+ expect(service.getEmail()).toBe('learner@example.com');
26
+ expect(service.getFlow()).toBe('sign-in');
27
+ });
28
+
29
+ it('does not clear a newer request when an older send fails', () => {
30
+ service.remember({
31
+ email: 'new@example.com',
32
+ flow: 'sign-in',
33
+ uid: null,
34
+ });
35
+
36
+ service.clearIfMatches({
37
+ email: 'old@example.com',
38
+ flow: 'sign-in',
39
+ uid: null,
40
+ });
41
+
42
+ expect(service.getEmail()).toBe('new@example.com');
43
+ });
44
+
45
+ it('clears matching local-storage and cookie context', () => {
46
+ const context = {
47
+ email: 'learner@example.com',
48
+ flow: 'guest-upgrade' as const,
49
+ uid: 'guest-123',
50
+ };
51
+ service.remember(context);
52
+
53
+ service.clearIfMatches(context);
54
+
55
+ expect(service.getEmail()).toBeNull();
56
+ expect(service.getFlow()).toBeNull();
57
+ expect(service.getUid()).toBeNull();
58
+ });
59
+ });
@@ -0,0 +1,147 @@
1
+ import { DOCUMENT } from '@angular/common';
2
+ import { Injectable, inject } from '@angular/core';
3
+
4
+ /** Supported email magic link authentication workflows. */
5
+ export type EmailLinkFlow = 'sign-in' | 'guest-upgrade' | 'link-email';
6
+
7
+ /**
8
+ * Encapsulates the same-browser state required to complete an email link authentication request.
9
+ */
10
+ type EmailLinkContext = {
11
+ /** The target email address the magic link was sent to. */
12
+ email: string;
13
+ /** The intended authentication workflow. */
14
+ flow: EmailLinkFlow;
15
+ /** The current user's Firebase UID if upgrading a guest or linking email to an existing account. */
16
+ uid: string | null;
17
+ };
18
+
19
+ /**
20
+ * Manages same-browser context persistence for passwordless email magic link sign-in flows.
21
+ *
22
+ * When a user requests a magic link, Firebase Auth redirects them out of the app to their email client.
23
+ * Upon clicking the link in the email, the user lands back on the `/auth/action` route.
24
+ * To securely process the callback, the application must verify the originating email address,
25
+ * flow type, and originating user UID (for account upgrades/linking).
26
+ *
27
+ * To remain resilient against browser storage restrictions (e.g., Safari ITP, private browsing mode),
28
+ * this service uses a dual-layer strategy:
29
+ * 1. Primary storage in `localStorage`.
30
+ * 2. Fallback in a short-lived (30-minute), `SameSite=Lax` cookie.
31
+ */
32
+ @Injectable({
33
+ providedIn: 'root',
34
+ })
35
+ export class EmailLinkContextService {
36
+ private readonly document = inject(DOCUMENT);
37
+ private readonly emailKey = 'app.email-link.email';
38
+ private readonly flowKey = 'app.email-link.flow';
39
+ private readonly uidKey = 'app.email-link.uid';
40
+ private readonly maxAgeSeconds = 30 * 60;
41
+
42
+ /**
43
+ * Persists email magic link context into localStorage and fallback cookies before sending the email.
44
+ *
45
+ * @param context The email, flow type, and optional originating UID to store.
46
+ */
47
+ remember(context: EmailLinkContext): void {
48
+ this.set(this.emailKey, context.email);
49
+ this.set(this.flowKey, context.flow);
50
+ if (context.uid) this.set(this.uidKey, context.uid);
51
+ else this.remove(this.uidKey);
52
+ }
53
+
54
+ /** Retrieves the stored target email address, or `null` if not found or expired. */
55
+ getEmail(): string | null {
56
+ return this.get(this.emailKey);
57
+ }
58
+
59
+ /** Retrieves the stored email link flow type (`sign-in`, `guest-upgrade`, or `link-email`). */
60
+ getFlow(): EmailLinkFlow | null {
61
+ const flow = this.get(this.flowKey);
62
+ return flow === 'sign-in' || flow === 'guest-upgrade' || flow === 'link-email' ? flow : null;
63
+ }
64
+
65
+ /** Retrieves the originating UID for account upgrading/linking flows. */
66
+ getUid(): string | null {
67
+ return this.get(this.uidKey);
68
+ }
69
+
70
+ /**
71
+ * Clears the persisted context if all fields match the completed context.
72
+ */
73
+ clearIfMatches(context: EmailLinkContext): void {
74
+ if (
75
+ this.getEmail() === context.email &&
76
+ this.getFlow() === context.flow &&
77
+ this.getUid() === context.uid
78
+ ) {
79
+ this.clear();
80
+ }
81
+ }
82
+
83
+ /** Clears all stored email link context from both localStorage and cookies. */
84
+ clear(): void {
85
+ this.remove(this.emailKey);
86
+ this.remove(this.flowKey);
87
+ this.remove(this.uidKey);
88
+ }
89
+
90
+ /** Safe getter for `localStorage` that handles SSR or restricted window contexts. */
91
+ private get storage(): Storage | null {
92
+ try {
93
+ return this.document.defaultView?.localStorage || null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /** Reads a stored value from localStorage with cookie fallback. */
100
+ private get(key: string): string | null {
101
+ try {
102
+ const storedValue = this.storage?.getItem(key);
103
+ if (storedValue) return storedValue;
104
+ } catch {
105
+ // Fall back to the short-lived cookie below.
106
+ }
107
+ return this.getCookie(key);
108
+ }
109
+
110
+ /** Writes a value to both localStorage and a short-lived cookie. */
111
+ private set(key: string, value: string): void {
112
+ try {
113
+ this.storage?.setItem(key, value);
114
+ } catch {
115
+ // The cookie still preserves the same-browser callback context.
116
+ }
117
+ this.setCookie(key, value);
118
+ }
119
+
120
+ /** Removes a key from both localStorage and cookies. */
121
+ private remove(key: string): void {
122
+ try {
123
+ this.storage?.removeItem(key);
124
+ } catch {
125
+ // The cookie is cleared independently below.
126
+ }
127
+ this.document.cookie = `${encodeURIComponent(key)}=; Path=/; Max-Age=0; SameSite=Lax`;
128
+ }
129
+
130
+ /** Reads a cookie by key. */
131
+ private getCookie(key: string): string | null {
132
+ const encodedKey = `${encodeURIComponent(key)}=`;
133
+ const match = this.document.cookie
134
+ .split(';')
135
+ .map((cookie) => cookie.trim())
136
+ .find((cookie) => cookie.startsWith(encodedKey));
137
+ return match ? decodeURIComponent(match.slice(encodedKey.length)) : null;
138
+ }
139
+
140
+ /** Writes a cookie with 30-minute max-age and SameSite=Lax. */
141
+ private setCookie(key: string, value: string): void {
142
+ const secure = this.document.location?.protocol === 'https:' ? '; Secure' : '';
143
+ this.document.cookie =
144
+ `${encodeURIComponent(key)}=${encodeURIComponent(value)}; ` +
145
+ `Path=/; Max-Age=${this.maxAgeSeconds}; SameSite=Lax${secure}`;
146
+ }
147
+ }
@@ -5,9 +5,10 @@ import { tap, pluck, mergeMap, pairwise, delay, startWith, filter, takeUntil, sk
5
5
  import { environment } from '../../../environments/environment';
6
6
  import { DocumentSnapshot, serverTimestamp, Timestamp, getDoc, getDocs, doc, setDoc, updateDoc, deleteDoc, docData, collection, collectionData, collectionChanges, query, where, orderBy, OrderByDirection, limit, startAt, startAfter, endAt, endBefore, DocumentChange, increment, AggregateQuerySnapshot, AggregateField, AggregateSpec, getAggregateFromServer, getCountFromServer } from '@angular/fire/firestore';
7
7
  import { AnyEntity, QueryParams, QueryOptions } from '../store/app.model';
8
- import { DatabaseService, DATABASE_SERVICE } from './database.service';
8
+ import { AuthSession, DatabaseService, DATABASE_SERVICE } from './database.service';
9
9
  import { SelectEntityId } from '@ngrx/signals/entities';
10
10
  import { AuthMockDB } from '../store/auth/auth.mock';
11
+ import { AccessState, User } from '../store/user/user.model';
11
12
 
12
13
  // Entity Model DB Data
13
14
  import { UserMockDB, USER_DB } from '../store/user/user.mock';
@@ -69,28 +70,114 @@ export class FirebaseMockService implements DatabaseService {
69
70
  return autoId;
70
71
  }
71
72
 
72
- afUser(): Observable<{ uid: string, email: string, displayName: string, photoURL: string } | null> {
73
+ afUser(): Observable<AuthSession | null> {
73
74
  return this.user$;
74
75
  }
75
76
 
76
- async login(providerId, scope?: string): Promise<any> {
77
- this.authDB.login();
78
- this.user$.next(this.authDB.afUser());
79
- return {
80
- user: {
81
- uid: USER_DB[0].__id,
82
- email: USER_DB[0].email,
83
- displayName: USER_DB[0].name,
84
- photoURL: USER_DB[0].photoURL,
85
- },
86
- };
77
+ private setSession(session: AuthSession | null): void {
78
+ this.user$.next(session);
79
+ }
80
+
81
+ async signInWithGoogle(): Promise<AuthSession> {
82
+ await this.authDB.signInWithGoogle();
83
+ const session = this.authDB.afUser()!;
84
+ this.setSession(session);
85
+ return session;
86
+ }
87
+
88
+ async signInAnonymously(): Promise<AuthSession> {
89
+ await this.authDB.loginAnonymously();
90
+ const session = this.authDB.afUser()!;
91
+ this.setSession(session);
92
+ return session;
93
+ }
94
+
95
+ async linkGoogle(): Promise<AuthSession> {
96
+ await this.authDB.linkGoogle();
97
+ const session = this.authDB.afUser()!;
98
+ this.setSession(session);
99
+ return session;
100
+ }
101
+
102
+ async sendEmailSignInLink(): Promise<void> {}
103
+
104
+ async sendEmailLinkForCurrentAccount(): Promise<void> {}
105
+
106
+ getStoredEmailForEmailLink(): string | null {
107
+ return null;
108
+ }
109
+
110
+ async completeEmailSignInLink(): Promise<AuthSession> {
111
+ const session = await this.authDB.completeEmailSignInLink();
112
+ this.setSession(session);
113
+ return session;
87
114
  }
88
115
 
89
- loginLink(error) { }
116
+ async deleteAnonymousAccount(): Promise<void> {
117
+ await this.authDB.deleteAnonymousAccount();
118
+ this.setSession(null);
119
+ }
120
+
121
+ async ensureUserProfile(session: AuthSession): Promise<User> {
122
+ const existing = this.DB['users'].selectEntity(session.uid);
123
+ const existingPrivate = this.DB['userPrivates'].selectEntity(session.uid);
124
+
125
+ let profile = existing;
126
+ if (!existing) {
127
+ profile = {
128
+ __id: session.uid,
129
+ name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : 'Learner'),
130
+ isAdmin: false,
131
+ consented: false,
132
+ accessState: AccessState.SUBMIT_INTEREST,
133
+ ...(session.photoURL ? { photoURL: session.photoURL } : {}),
134
+ _createdAt: Timestamp.now(),
135
+ _updatedAt: Timestamp.now(),
136
+ _deleted: false,
137
+ };
138
+ await this.DB['users'].add(profile);
139
+ } else {
140
+ const generatedName =
141
+ !existing.name ||
142
+ existing.name === 'Guest' ||
143
+ existing.name === 'Learner' ||
144
+ existing.name === session.email;
145
+ const changes = {
146
+ ...(generatedName && session.displayName ? { name: session.displayName } : {}),
147
+ ...(session.photoURL && existing.photoURL !== session.photoURL ?
148
+ { photoURL: session.photoURL } :
149
+ {}),
150
+ };
151
+ if (Object.keys(changes).length > 0) {
152
+ await this.DB['users'].update(session.uid, changes);
153
+ profile = { ...existing, ...changes };
154
+ }
155
+ }
156
+
157
+ if (session.email) {
158
+ const privateChanges = {
159
+ email: session.email,
160
+ emailLinkEnabled: session.emailLinkEnabled,
161
+ _updatedAt: Timestamp.now(),
162
+ _deleted: false,
163
+ };
164
+ if (existingPrivate) {
165
+ await this.DB['userPrivates'].update(session.uid, privateChanges);
166
+ } else {
167
+ await this.DB['userPrivates'].add({
168
+ __id: session.uid,
169
+ ...privateChanges,
170
+ _createdAt: Timestamp.now(),
171
+ });
172
+ }
173
+ }
174
+
175
+ return profile;
176
+ }
90
177
 
91
- logout() {
92
- this.authDB.logout();
93
- this.user$.next(this.authDB.afUser());
178
+ async logout(): Promise<void> {
179
+ await this.authDB.logout();
180
+ this.setSession(null);
94
181
  }
95
182
 
96
183
  streamEntity<T>(collectionName: string, id: string) {
@@ -0,0 +1,116 @@
1
+ import { TestBed } from '@angular/core/testing';
2
+ import { FirebaseMockService, provideFirebaseMock } from './firebase.mock.service';
3
+ import { firebaseUserToAuthSession } from './firebase.service';
4
+
5
+ describe('firebaseUserToAuthSession', () => {
6
+ it('derives email-link capability from Firebase Auth without reading Firestore', () => {
7
+ const session = firebaseUserToAuthSession({
8
+ uid: 'learner-1',
9
+ email: 'learner@example.com',
10
+ displayName: 'Learner',
11
+ photoURL: null,
12
+ isAnonymous: false,
13
+ emailVerified: true,
14
+ providerData: [
15
+ {
16
+ providerId: 'password',
17
+ uid: 'learner@example.com',
18
+ displayName: null,
19
+ email: 'learner@example.com',
20
+ phoneNumber: null,
21
+ photoURL: null,
22
+ },
23
+ ],
24
+ });
25
+
26
+ expect(session).toEqual({
27
+ uid: 'learner-1',
28
+ email: 'learner@example.com',
29
+ displayName: 'Learner',
30
+ photoURL: null,
31
+ isAnonymous: false,
32
+ emailVerified: true,
33
+ emailLinkEnabled: true,
34
+ providerIds: ['password'],
35
+ });
36
+ });
37
+ });
38
+
39
+ describe('FirebaseMockService profile provisioning parity', () => {
40
+ it('creates public and private profile data from the authenticated session', async () => {
41
+ TestBed.configureTestingModule({
42
+ providers: provideFirebaseMock({
43
+ users: [],
44
+ userPrivates: [],
45
+ disableLatency: true,
46
+ }),
47
+ });
48
+ const db = TestBed.inject(FirebaseMockService);
49
+ const session = {
50
+ uid: 'user-2',
51
+ email: 'user2@example.com',
52
+ displayName: 'User Two',
53
+ photoURL: 'https://example.com/user-2.jpg',
54
+ isAnonymous: false,
55
+ emailVerified: true,
56
+ emailLinkEnabled: true,
57
+ providerIds: ['password'],
58
+ };
59
+
60
+ await db.ensureUserProfile(session);
61
+
62
+ expect(db.DB.users.selectEntity(session.uid)).toEqual(
63
+ expect.objectContaining({
64
+ __id: session.uid,
65
+ name: 'User Two',
66
+ photoURL: 'https://example.com/user-2.jpg',
67
+ }),
68
+ );
69
+ expect(db.DB.userPrivates.selectEntity(session.uid)).toEqual(
70
+ expect.objectContaining({
71
+ __id: session.uid,
72
+ email: 'user2@example.com',
73
+ emailLinkEnabled: true,
74
+ }),
75
+ );
76
+ });
77
+
78
+ it('replaces a generated email name and stale photo when Google profile data becomes available', async () => {
79
+ const uid = 'email-user';
80
+ TestBed.configureTestingModule({
81
+ providers: provideFirebaseMock({
82
+ users: [
83
+ {
84
+ __id: uid,
85
+ name: 'email-user@example.com',
86
+ photoURL: null,
87
+ isAdmin: false,
88
+ consented: false,
89
+ accessState: '01 - submit interest',
90
+ },
91
+ ],
92
+ userPrivates: [{ __id: uid, email: 'email-user@example.com' }],
93
+ disableLatency: true,
94
+ }),
95
+ });
96
+ const db = TestBed.inject(FirebaseMockService);
97
+
98
+ await db.ensureUserProfile({
99
+ uid,
100
+ email: 'email-user@example.com',
101
+ displayName: 'Google User',
102
+ photoURL: 'https://example.com/google-user.jpg',
103
+ isAnonymous: false,
104
+ emailVerified: true,
105
+ emailLinkEnabled: true,
106
+ providerIds: ['password', 'google.com'],
107
+ });
108
+
109
+ expect(db.DB.users.selectEntity(uid)).toEqual(
110
+ expect.objectContaining({
111
+ name: 'Google User',
112
+ photoURL: 'https://example.com/google-user.jpg',
113
+ }),
114
+ );
115
+ });
116
+ });