@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.
- package/CHANGELOG.md +16 -0
- package/package.json +1 -1
- package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +2 -1
- package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +2 -1
- package/src/entity/index.js +57 -0
- package/src/entity/index.js.map +1 -1
- package/src/entity/schema.json +4 -0
- package/src/ng-add/files/.gitignore.template +2 -0
- package/src/ng-add/files/docs-infra/authentication-architecture.md.template +270 -0
- package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +16 -10
- package/src/ng-add/files/firebase.json.template +6 -0
- package/src/ng-add/files/firestore.indexes.json.template +23 -0
- package/src/ng-add/files/firestore.rules.spec.ts.template +84 -15
- package/src/ng-add/files/firestore.rules.template +29 -17
- package/src/ng-add/files/functions/.gitignore.template +3 -0
- package/src/ng-add/files/functions/package.json.template +12 -0
- package/src/ng-add/files/functions/src/index.ts.template +44 -0
- package/src/ng-add/files/functions/tsconfig.json.template +13 -0
- package/src/ng-add/files/package.json.template +5 -3
- package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +3 -1
- package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +6 -8
- package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +2 -0
- package/src/ng-add/files/src/app/app.component.html.template +2 -2
- package/src/ng-add/files/src/app/app.component.ts.template +2 -0
- package/src/ng-add/files/src/app/app.routes.ts.template +6 -0
- package/src/ng-add/files/src/app/auth-routing.spec.ts.template +9 -4
- package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +6 -1
- package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +38 -0
- package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +3 -2
- package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +7 -2
- package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +11 -5
- package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +34 -17
- package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +59 -0
- package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +147 -0
- package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +104 -17
- package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +116 -0
- package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +367 -70
- package/src/ng-add/files/src/app/core/store/app.store.ts.template +4 -1
- package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +52 -66
- package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +127 -0
- package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +216 -147
- package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +2 -4
- package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +1 -1
- package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +1 -0
- package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.html.template +4 -0
- package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.scss.template +1 -0
- package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.ts.template +38 -0
- package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +5 -1
- package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +12 -1
- package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +93 -48
- package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +5 -1
- package/src/ng-add/files/src/app/first-time/email-link/email-link.component.html.template +18 -0
- package/src/ng-add/files/src/app/first-time/email-link/email-link.component.scss.template +2 -0
- package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +40 -0
- package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +76 -0
- package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +7 -2
- package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +19 -7
- package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +51 -0
- package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +29 -5
- package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +2 -1
- package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +12 -8
- package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +31 -10
- package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +6 -19
- package/src/ng-add/files/src/app/first-time/login/login.component.html.template +58 -6
- package/src/ng-add/files/src/app/first-time/login/login.component.scss.template +151 -22
- package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +18 -38
- package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +59 -31
- package/src/ng-add/files/src/app/main/account-profile/account-profile.component.html.template +12 -0
- package/src/ng-add/files/src/app/main/account-profile/account-profile.component.scss.template +39 -0
- package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +68 -0
- package/src/ng-add/files/src/app/main/account-profile/account-profile.component.ts.template +20 -0
- package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.html.template +24 -0
- package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.scss.template +50 -0
- package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +65 -0
- package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.ts.template +59 -0
- package/src/ng-add/files/src/app/main/account-profile/guest-deletion-dialog.component.ts.template +51 -0
- package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.html.template +50 -0
- package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.scss.template +137 -0
- package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +57 -0
- package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.ts.template +59 -0
- package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.html.template +133 -0
- package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.scss.template +207 -0
- package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +74 -0
- package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.ts.template +130 -0
- package/src/ng-add/files/src/app/main/home/home.component.ts.template +0 -5
- package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.html.template +15 -0
- package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.scss.template +79 -0
- package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +59 -0
- package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.ts.template +44 -0
- package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +45 -15
- package/src/ng-add/files/src/app/shared/navbar/navbar.component.scss.template +103 -19
- package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +73 -9
- package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +46 -18
- package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
- package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
- package/src/ng-add/files/src/environments/environment.ts.template +1 -1
- package/src/ng-add/index_spec.d.ts +1 -0
- package/src/ng-add/index_spec.js +108 -0
- package/src/ng-add/index_spec.js.map +1 -0
- package/tsconfig.json +2 -2
|
@@ -1,11 +1,115 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DOCUMENT } from '@angular/common';
|
|
2
|
+
import { Injectable, inject } from '@angular/core';
|
|
2
3
|
import { Observable, combineLatest, merge, of, from, pipe } from 'rxjs';
|
|
3
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
tap,
|
|
6
|
+
pluck,
|
|
7
|
+
mergeMap,
|
|
8
|
+
filter,
|
|
9
|
+
takeUntil,
|
|
10
|
+
skip,
|
|
11
|
+
switchMap,
|
|
12
|
+
map,
|
|
13
|
+
take,
|
|
14
|
+
} from 'rxjs/operators';
|
|
4
15
|
import { environment } from '../../../environments/environment';
|
|
5
|
-
import {
|
|
6
|
-
|
|
16
|
+
import {
|
|
17
|
+
Firestore,
|
|
18
|
+
DocumentSnapshot,
|
|
19
|
+
serverTimestamp,
|
|
20
|
+
sum,
|
|
21
|
+
count,
|
|
22
|
+
average,
|
|
23
|
+
Timestamp,
|
|
24
|
+
getDoc,
|
|
25
|
+
getDocs,
|
|
26
|
+
doc,
|
|
27
|
+
setDoc,
|
|
28
|
+
updateDoc,
|
|
29
|
+
deleteDoc,
|
|
30
|
+
docData,
|
|
31
|
+
collection,
|
|
32
|
+
collectionData,
|
|
33
|
+
collectionChanges,
|
|
34
|
+
query,
|
|
35
|
+
where,
|
|
36
|
+
orderBy,
|
|
37
|
+
OrderByDirection,
|
|
38
|
+
limit,
|
|
39
|
+
startAt,
|
|
40
|
+
startAfter,
|
|
41
|
+
endAt,
|
|
42
|
+
endBefore,
|
|
43
|
+
DocumentChange,
|
|
44
|
+
increment,
|
|
45
|
+
AggregateQuerySnapshot,
|
|
46
|
+
AggregateField,
|
|
47
|
+
AggregateSpec,
|
|
48
|
+
getAggregateFromServer,
|
|
49
|
+
getCountFromServer,
|
|
50
|
+
writeBatch,
|
|
51
|
+
WriteBatch,
|
|
52
|
+
} from '@angular/fire/firestore';
|
|
53
|
+
import {
|
|
54
|
+
Auth,
|
|
55
|
+
user,
|
|
56
|
+
User,
|
|
57
|
+
signInWithPopup,
|
|
58
|
+
signOut,
|
|
59
|
+
linkWithPopup,
|
|
60
|
+
linkWithCredential,
|
|
61
|
+
EmailAuthProvider,
|
|
62
|
+
isSignInWithEmailLink,
|
|
63
|
+
sendSignInLinkToEmail,
|
|
64
|
+
signInAnonymously,
|
|
65
|
+
signInWithEmailLink,
|
|
66
|
+
GoogleAuthProvider,
|
|
67
|
+
} from '@angular/fire/auth';
|
|
7
68
|
import { QueryParams, QueryOptions, AnyEntity } from '../store/app.model';
|
|
8
|
-
import { DatabaseService } from './database.service';
|
|
69
|
+
import { AuthSession, DatabaseService } from './database.service';
|
|
70
|
+
import { Functions, httpsCallable } from '@angular/fire/functions';
|
|
71
|
+
import { AccessState, User as AppUser } from '../store/user/user.model';
|
|
72
|
+
import { UserPrivate } from '../store/user-private/user-private.model';
|
|
73
|
+
import { EmailLinkContextService, EmailLinkFlow } from './email-link-context.service';
|
|
74
|
+
|
|
75
|
+
type FirebaseAuthUser = Pick<
|
|
76
|
+
User,
|
|
77
|
+
| 'uid'
|
|
78
|
+
| 'email'
|
|
79
|
+
| 'displayName'
|
|
80
|
+
| 'photoURL'
|
|
81
|
+
| 'isAnonymous'
|
|
82
|
+
| 'emailVerified'
|
|
83
|
+
| 'providerData'
|
|
84
|
+
>;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Maps a Firebase Auth `User` instance (or subset) into the application's normalized `AuthSession` model.
|
|
88
|
+
*
|
|
89
|
+
* Checks both top-level Firebase `User` properties and `providerData` entries to resolve
|
|
90
|
+
* available display names, profile avatars, verified email addresses, and enabled sign-in providers.
|
|
91
|
+
*
|
|
92
|
+
* @param currentUser The raw Firebase Auth user object.
|
|
93
|
+
* @returns A normalized `AuthSession` instance for state stores and guards.
|
|
94
|
+
*/
|
|
95
|
+
export function firebaseUserToAuthSession(currentUser: FirebaseAuthUser): AuthSession {
|
|
96
|
+
const providerIds = currentUser.providerData.map((provider) => provider.providerId);
|
|
97
|
+
const firstProviderWithMeta = currentUser.providerData.find((p) => p.displayName || p.photoURL || p.email);
|
|
98
|
+
const displayName = currentUser.displayName || firstProviderWithMeta?.displayName || null;
|
|
99
|
+
const photoURL = currentUser.photoURL || firstProviderWithMeta?.photoURL || null;
|
|
100
|
+
const email = currentUser.email || firstProviderWithMeta?.email || null;
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
uid: currentUser.uid,
|
|
104
|
+
email,
|
|
105
|
+
displayName,
|
|
106
|
+
photoURL,
|
|
107
|
+
isAnonymous: currentUser.isAnonymous,
|
|
108
|
+
emailVerified: currentUser.emailVerified,
|
|
109
|
+
emailLinkEnabled: providerIds.includes(EmailAuthProvider.PROVIDER_ID),
|
|
110
|
+
providerIds,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
9
113
|
|
|
10
114
|
@Injectable({
|
|
11
115
|
providedIn: 'root',
|
|
@@ -14,17 +118,18 @@ export class FirebaseService implements DatabaseService {
|
|
|
14
118
|
private afAuth = inject(Auth);
|
|
15
119
|
private firestore = inject(Firestore);
|
|
16
120
|
private user$ = user(this.afAuth);
|
|
121
|
+
private functions = inject(Functions);
|
|
122
|
+
private document = inject(DOCUMENT);
|
|
123
|
+
private emailLinkContext = inject(EmailLinkContextService);
|
|
17
124
|
|
|
18
|
-
constructor(
|
|
19
|
-
) { }
|
|
125
|
+
constructor() {}
|
|
20
126
|
|
|
21
|
-
/** Creates a unique
|
|
127
|
+
/** Creates a unique Firestore auto-generated ID. */
|
|
22
128
|
createId(): string {
|
|
23
129
|
// see https://stackoverflow.com/questions/56574593/access-firestore-id-generator-on-the-front-end?noredirect=1&lq=1
|
|
24
130
|
// see https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36
|
|
25
131
|
// Alphanumeric characters
|
|
26
|
-
const chars =
|
|
27
|
-
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
132
|
+
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
28
133
|
let autoId = '';
|
|
29
134
|
for (let i = 0; i < 20; i++) {
|
|
30
135
|
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
|
|
@@ -32,63 +137,245 @@ export class FirebaseService implements DatabaseService {
|
|
|
32
137
|
return autoId;
|
|
33
138
|
}
|
|
34
139
|
|
|
35
|
-
|
|
140
|
+
/**
|
|
141
|
+
* Returns an observable stream emitting the current `AuthSession` whenever Firebase authentication state changes.
|
|
142
|
+
* Emits `null` when signed out.
|
|
143
|
+
*/
|
|
144
|
+
afUser(): Observable<AuthSession | null> {
|
|
36
145
|
return from(this.afAuth.authStateReady()).pipe(
|
|
37
146
|
switchMap(() => this.user$),
|
|
147
|
+
map((currentUser) => currentUser ? firebaseUserToAuthSession(currentUser) : null),
|
|
38
148
|
);
|
|
39
149
|
}
|
|
40
150
|
|
|
41
|
-
|
|
42
|
-
|
|
151
|
+
/**
|
|
152
|
+
* Signs in a user via Google OAuth popup and returns the mapped `AuthSession`.
|
|
153
|
+
*
|
|
154
|
+
* Forces token initialization before Firestore provisioning to avoid a fresh-login credentials race.
|
|
155
|
+
*/
|
|
156
|
+
async signInWithGoogle(): Promise<AuthSession> {
|
|
157
|
+
const result = await signInWithPopup(this.afAuth, new GoogleAuthProvider());
|
|
158
|
+
await result.user.getIdToken(true);
|
|
159
|
+
return firebaseUserToAuthSession(result.user);
|
|
160
|
+
}
|
|
43
161
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
162
|
+
/**
|
|
163
|
+
* Creates an anonymous Firebase Auth session.
|
|
164
|
+
*
|
|
165
|
+
* Forces ID token initialization immediately after creation to prevent race conditions
|
|
166
|
+
* with Firestore security rules on fresh sign-ins (especially after deleting a previous guest account).
|
|
167
|
+
*/
|
|
168
|
+
async signInAnonymously(): Promise<AuthSession> {
|
|
169
|
+
const result = await signInAnonymously(this.afAuth);
|
|
170
|
+
// Force Firebase to establish the new anonymous token before AuthStore
|
|
171
|
+
// provisions Firestore data. This is especially important immediately
|
|
172
|
+
// after deleting a previous anonymous account.
|
|
173
|
+
await result.user.getIdToken(true);
|
|
174
|
+
return firebaseUserToAuthSession(result.user);
|
|
49
175
|
}
|
|
50
176
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
177
|
+
/**
|
|
178
|
+
* Links a Google identity to the currently signed-in Firebase user without changing their UID.
|
|
179
|
+
* Preserves existing guest/application data under the current UID.
|
|
180
|
+
*/
|
|
181
|
+
async linkGoogle(): Promise<AuthSession> {
|
|
182
|
+
const currentUser = this.afAuth.currentUser;
|
|
183
|
+
if (!currentUser) throw new Error('No authenticated user is available to link Google.');
|
|
184
|
+
const result = await linkWithPopup(currentUser, new GoogleAuthProvider());
|
|
185
|
+
await result.user.getIdToken(true);
|
|
186
|
+
return firebaseUserToAuthSession(result.user);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Dispatches a passwordless email magic link for sign-in or guest upgrading.
|
|
191
|
+
*
|
|
192
|
+
* Saves flow context into `EmailLinkContextService` before sending the email.
|
|
193
|
+
*
|
|
194
|
+
* @param email The destination email address.
|
|
195
|
+
*/
|
|
196
|
+
async sendEmailSignInLink(email: string): Promise<void> {
|
|
197
|
+
const currentUser = this.afAuth.currentUser;
|
|
198
|
+
const flow = currentUser?.isAnonymous ? 'guest-upgrade' : 'sign-in';
|
|
199
|
+
await this.sendEmailLink(email, flow, currentUser?.isAnonymous ? currentUser.uid : null);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Dispatches a passwordless email magic link to attach email-link sign-in to an existing account.
|
|
204
|
+
*/
|
|
205
|
+
async sendEmailLinkForCurrentAccount(): Promise<void> {
|
|
206
|
+
const currentUser = this.afAuth.currentUser;
|
|
207
|
+
if (!currentUser?.email) throw new Error('An email address is required to enable email-link sign-in.');
|
|
208
|
+
await this.sendEmailLink(currentUser.email, 'link-email', currentUser.uid);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Retrieves any stored email magic link email address from `EmailLinkContextService`. */
|
|
212
|
+
getStoredEmailForEmailLink(): string | null {
|
|
213
|
+
return this.emailLinkContext.getEmail();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Verifies the magic link URL and completes authentication or account linking.
|
|
218
|
+
*
|
|
219
|
+
* - Handles `sign-in`, `guest-upgrade`, and `link-email` workflows.
|
|
220
|
+
* - Enforces same-browser UID validation for upgrade and link flows.
|
|
221
|
+
* - Refreshes the Firebase token and clears stored magic link context upon completion.
|
|
222
|
+
*
|
|
223
|
+
* @param url The full callback URL (containing action code parameters).
|
|
224
|
+
* @param email The target email address.
|
|
225
|
+
* @returns The updated `AuthSession`.
|
|
226
|
+
*/
|
|
227
|
+
async completeEmailSignInLink(url: string, email: string): Promise<AuthSession> {
|
|
228
|
+
if (!isSignInWithEmailLink(this.afAuth, url)) {
|
|
229
|
+
throw this.authError('auth/invalid-action-code', 'This sign-in link is not valid.');
|
|
230
|
+
}
|
|
231
|
+
await this.afAuth.authStateReady();
|
|
232
|
+
|
|
233
|
+
const flow = this.getEmailLinkFlow(url);
|
|
234
|
+
const currentUser = this.afAuth.currentUser;
|
|
235
|
+
const storedUid = this.emailLinkContext.getUid();
|
|
236
|
+
|
|
237
|
+
if (flow === 'link-email' || flow === 'guest-upgrade') {
|
|
238
|
+
if (!currentUser || currentUser.uid !== storedUid) {
|
|
239
|
+
throw this.authError('auth/link-requires-original-session', 'Return to the browser where you started this account upgrade.');
|
|
61
240
|
}
|
|
241
|
+
const result = await linkWithCredential(currentUser, EmailAuthProvider.credentialWithLink(email, url));
|
|
242
|
+
await result.user.getIdToken(true);
|
|
243
|
+
this.clearEmailLinkContext();
|
|
244
|
+
return firebaseUserToAuthSession(result.user);
|
|
62
245
|
}
|
|
63
|
-
|
|
64
|
-
|
|
246
|
+
|
|
247
|
+
try {
|
|
248
|
+
const result = await signInWithEmailLink(this.afAuth, email, url);
|
|
249
|
+
await result.user.getIdToken(true);
|
|
250
|
+
this.clearEmailLinkContext();
|
|
251
|
+
return firebaseUserToAuthSession(result.user);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
const activeUser = this.afAuth.currentUser;
|
|
254
|
+
if (activeUser && activeUser.email?.toLowerCase() === email.toLowerCase()) {
|
|
255
|
+
await activeUser.getIdToken(true);
|
|
256
|
+
this.clearEmailLinkContext();
|
|
257
|
+
return firebaseUserToAuthSession(activeUser);
|
|
258
|
+
}
|
|
259
|
+
throw error;
|
|
65
260
|
}
|
|
66
|
-
return provider;
|
|
67
261
|
}
|
|
68
262
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
263
|
+
/**
|
|
264
|
+
* Calls the `deleteAnonymousAccount` callable Cloud Function to server-delete guest-owned data
|
|
265
|
+
* and the anonymous Firebase Auth account.
|
|
266
|
+
*/
|
|
267
|
+
async deleteAnonymousAccount(): Promise<void> {
|
|
268
|
+
await httpsCallable<void, void>(this.functions, 'deleteAnonymousAccount')();
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Ensures Firestore `users/{uid}` and `userPrivates/{uid}` profile documents exist for an authenticated user.
|
|
273
|
+
*
|
|
274
|
+
* Initializes missing profiles with default values (e.g. `accessState: SUBMIT_INTEREST`).
|
|
275
|
+
* Updates profile name/photoURL if newly available from an upgraded Google login.
|
|
276
|
+
*
|
|
277
|
+
* @param session The active authentication session.
|
|
278
|
+
* @returns The loaded or updated application user record.
|
|
279
|
+
*/
|
|
280
|
+
async ensureUserProfile(session: AuthSession): Promise<AppUser> {
|
|
281
|
+
const existing = await this.getEntity<AppUser>('users', session.uid);
|
|
282
|
+
const existingPrivate = await this.getEntity<UserPrivate>('userPrivates', session.uid);
|
|
283
|
+
|
|
284
|
+
if (!existing) {
|
|
285
|
+
const profileData: AppUser = {
|
|
286
|
+
__id: session.uid,
|
|
287
|
+
name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : 'Learner'),
|
|
288
|
+
isAdmin: false,
|
|
289
|
+
consented: false,
|
|
290
|
+
accessState: AccessState.SUBMIT_INTEREST,
|
|
291
|
+
...(session.photoURL ? { photoURL: session.photoURL } : {}),
|
|
292
|
+
};
|
|
293
|
+
await this.addEntity('users', profileData);
|
|
294
|
+
} else {
|
|
295
|
+
const generatedName =
|
|
296
|
+
!existing.name ||
|
|
297
|
+
existing.name === 'Guest' ||
|
|
298
|
+
existing.name === 'Learner' ||
|
|
299
|
+
existing.name === session.email;
|
|
300
|
+
const changes = {
|
|
301
|
+
...(generatedName && session.displayName ? { name: session.displayName } : {}),
|
|
302
|
+
...(session.photoURL && existing.photoURL !== session.photoURL ?
|
|
303
|
+
{ photoURL: session.photoURL } :
|
|
304
|
+
{}),
|
|
305
|
+
};
|
|
306
|
+
if (Object.keys(changes).length > 0) {
|
|
307
|
+
await this.updateEntity('users', session.uid, changes);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (session.email) {
|
|
312
|
+
if (existingPrivate) {
|
|
313
|
+
await this.updateEntity('userPrivates', session.uid, {
|
|
314
|
+
email: session.email,
|
|
315
|
+
...(session.emailLinkEnabled !== undefined ? { emailLinkEnabled: session.emailLinkEnabled } : {}),
|
|
84
316
|
});
|
|
85
|
-
}
|
|
317
|
+
} else {
|
|
318
|
+
const privateData: UserPrivate = {
|
|
319
|
+
__id: session.uid,
|
|
320
|
+
email: session.email,
|
|
321
|
+
...(session.emailLinkEnabled !== undefined ? { emailLinkEnabled: session.emailLinkEnabled } : {}),
|
|
322
|
+
};
|
|
323
|
+
await this.addEntity('userPrivates', privateData);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const updatedProfile = await this.getEntity<AppUser>('users', session.uid);
|
|
328
|
+
return (
|
|
329
|
+
updatedProfile ||
|
|
330
|
+
existing || {
|
|
331
|
+
__id: session.uid,
|
|
332
|
+
name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : 'Learner'),
|
|
333
|
+
isAdmin: false,
|
|
334
|
+
consented: false,
|
|
335
|
+
accessState: AccessState.SUBMIT_INTEREST,
|
|
336
|
+
}
|
|
337
|
+
);
|
|
86
338
|
}
|
|
87
339
|
|
|
340
|
+
/** Signs out the current Firebase user. */
|
|
88
341
|
async logout() {
|
|
89
342
|
await signOut(this.afAuth);
|
|
90
343
|
}
|
|
91
344
|
|
|
345
|
+
private actionCodeSettings(flow: EmailLinkFlow) {
|
|
346
|
+
const origin = this.document.defaultView?.location.origin;
|
|
347
|
+
if (!origin) throw new Error('Email actions require a browser origin.');
|
|
348
|
+
return { url: `${origin}/auth/action?flow=${flow}`, handleCodeInApp: true };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
private async sendEmailLink(email: string, flow: EmailLinkFlow, uid: string | null): Promise<void> {
|
|
352
|
+
const context = { email, flow, uid };
|
|
353
|
+
this.emailLinkContext.remember(context);
|
|
354
|
+
try {
|
|
355
|
+
await sendSignInLinkToEmail(this.afAuth, email, this.actionCodeSettings(flow));
|
|
356
|
+
} catch (error) {
|
|
357
|
+
this.emailLinkContext.clearIfMatches(context);
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private getEmailLinkFlow(url: string): EmailLinkFlow {
|
|
363
|
+
const parsed = new URL(url);
|
|
364
|
+
const directFlow = parsed.searchParams.get('flow');
|
|
365
|
+
const continueUrl = parsed.searchParams.get('continueUrl');
|
|
366
|
+
const nestedFlow = continueUrl ? new URL(continueUrl).searchParams.get('flow') : null;
|
|
367
|
+
const flow = directFlow || nestedFlow || this.emailLinkContext.getFlow() || 'sign-in';
|
|
368
|
+
return flow === 'guest-upgrade' || flow === 'link-email' ? flow : 'sign-in';
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
private clearEmailLinkContext(): void {
|
|
372
|
+
this.emailLinkContext.clear();
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
private authError(code: string, message: string): Error & { code: string } {
|
|
376
|
+
return Object.assign(new Error(message), { code });
|
|
377
|
+
}
|
|
378
|
+
|
|
92
379
|
streamEntity<T>(collectionName: string, id: string) {
|
|
93
380
|
const docRef = doc(this.firestore, `${collectionName}/${id}`);
|
|
94
381
|
return docData(docRef) as Observable<T>;
|
|
@@ -105,10 +392,16 @@ export class FirebaseService implements DatabaseService {
|
|
|
105
392
|
}
|
|
106
393
|
}
|
|
107
394
|
|
|
108
|
-
streamEntitiesChanges<T>(
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
395
|
+
streamEntitiesChanges<T>(
|
|
396
|
+
collectionName,
|
|
397
|
+
queryParams,
|
|
398
|
+
queryOptions?,
|
|
399
|
+
): Observable<
|
|
400
|
+
{
|
|
401
|
+
type: string;
|
|
402
|
+
docData: T;
|
|
403
|
+
}[]
|
|
404
|
+
> {
|
|
112
405
|
let stateChangeObs$;
|
|
113
406
|
const collectionRef = collection(this.firestore, collectionName);
|
|
114
407
|
|
|
@@ -122,10 +415,14 @@ export class FirebaseService implements DatabaseService {
|
|
|
122
415
|
|
|
123
416
|
return stateChangeObs$.pipe(
|
|
124
417
|
map((changes: DocumentChange<T>[]) => {
|
|
125
|
-
return changes.map((dc) =>
|
|
126
|
-
|
|
127
|
-
docData: dc.doc.data()
|
|
128
|
-
|
|
418
|
+
return changes.map((dc) => {
|
|
419
|
+
const data = dc.doc.data();
|
|
420
|
+
const docData = data ? { __id: dc.doc.id, ...data } : ({ __id: dc.doc.id } as unknown as T);
|
|
421
|
+
return {
|
|
422
|
+
type: dc.type,
|
|
423
|
+
docData,
|
|
424
|
+
};
|
|
425
|
+
});
|
|
129
426
|
}),
|
|
130
427
|
);
|
|
131
428
|
}
|
|
@@ -156,7 +453,12 @@ export class FirebaseService implements DatabaseService {
|
|
|
156
453
|
queryArray.push(orderBy(order[0], order[1] as OrderByDirection));
|
|
157
454
|
}
|
|
158
455
|
} else {
|
|
159
|
-
queryArray.push(
|
|
456
|
+
queryArray.push(
|
|
457
|
+
orderBy(
|
|
458
|
+
queryOptions.orderBy[0] as string,
|
|
459
|
+
queryOptions.orderBy[1] as OrderByDirection,
|
|
460
|
+
),
|
|
461
|
+
);
|
|
160
462
|
}
|
|
161
463
|
} else {
|
|
162
464
|
queryArray.push(orderBy(queryOptions.orderBy));
|
|
@@ -193,7 +495,7 @@ export class FirebaseService implements DatabaseService {
|
|
|
193
495
|
|
|
194
496
|
async getEntity<T>(collectionName: string, id: string) {
|
|
195
497
|
const docRef = doc(this.firestore, `${collectionName}/${id}`);
|
|
196
|
-
const docSnap = await getDoc(docRef) as DocumentSnapshot<T, T>;
|
|
498
|
+
const docSnap = (await getDoc(docRef)) as DocumentSnapshot<T, T>;
|
|
197
499
|
|
|
198
500
|
if (docSnap.exists()) {
|
|
199
501
|
return docSnap.data();
|
|
@@ -277,11 +579,7 @@ export class FirebaseService implements DatabaseService {
|
|
|
277
579
|
return querySnapshot.data();
|
|
278
580
|
}
|
|
279
581
|
|
|
280
|
-
async addEntity(
|
|
281
|
-
collectionName: string,
|
|
282
|
-
entity: AnyEntity,
|
|
283
|
-
batch?: WriteBatch,
|
|
284
|
-
) {
|
|
582
|
+
async addEntity(collectionName: string, entity: AnyEntity, batch?: WriteBatch) {
|
|
285
583
|
const docRef = doc(this.firestore, `${collectionName}/${entity.__id}`);
|
|
286
584
|
const entityFinal = Object.assign({}, entity, {
|
|
287
585
|
_createdAt: serverTimestamp(),
|
|
@@ -312,11 +610,7 @@ export class FirebaseService implements DatabaseService {
|
|
|
312
610
|
}
|
|
313
611
|
}
|
|
314
612
|
|
|
315
|
-
async removeEntity(
|
|
316
|
-
collectionName: string,
|
|
317
|
-
id: string,
|
|
318
|
-
batch?: WriteBatch,
|
|
319
|
-
) {
|
|
613
|
+
async removeEntity(collectionName: string, id: string, batch?: WriteBatch) {
|
|
320
614
|
const docRef = doc(this.firestore, `${collectionName}/${id}`);
|
|
321
615
|
// we do soft deletes from client side
|
|
322
616
|
const changes = {
|
|
@@ -335,8 +629,11 @@ export class FirebaseService implements DatabaseService {
|
|
|
335
629
|
const changes = {};
|
|
336
630
|
changes[field] = increment(delta);
|
|
337
631
|
|
|
338
|
-
return updateDoc(
|
|
339
|
-
|
|
340
|
-
|
|
632
|
+
return updateDoc(
|
|
633
|
+
docRef,
|
|
634
|
+
Object.assign({}, changes, {
|
|
635
|
+
_updatedAt: serverTimestamp(),
|
|
636
|
+
}),
|
|
637
|
+
);
|
|
341
638
|
}
|
|
342
639
|
}
|
|
@@ -13,7 +13,7 @@ import { LoggingService, getLogger } from '../logging/logging.service';
|
|
|
13
13
|
|
|
14
14
|
const queryLogger = getLogger('query');
|
|
15
15
|
|
|
16
|
-
const selectId: SelectEntityId<AnyEntity> = (entity) => entity
|
|
16
|
+
const selectId: SelectEntityId<AnyEntity> = (entity) => entity?.__id ?? '';
|
|
17
17
|
|
|
18
18
|
export function openSnackBarWithUndoOption(
|
|
19
19
|
snackBar: MatSnackBar,
|
|
@@ -180,6 +180,9 @@ export function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: st
|
|
|
180
180
|
init(entities: S[]) {
|
|
181
181
|
patchState(store, setAllEntities<S>(entities, { selectId }));
|
|
182
182
|
},
|
|
183
|
+
reset() {
|
|
184
|
+
patchState(store, setAllEntities<S>([], { selectId }));
|
|
185
|
+
},
|
|
183
186
|
// streaming tries to reduce redundant loads through the following:
|
|
184
187
|
// - caching listeners and reusing them with a 5-second delay after moving to a new container before unsubscribing
|
|
185
188
|
// additionally, it has the following constraints:
|