@tech4good/platform-auth 0.0.0-stage → 0.1.0-alpha.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/EXTRACTION-CHANGES.md +159 -0
- package/FUTURE-WORK.md +73 -0
- package/MIGRATION.md +89 -0
- package/README.md +213 -2
- package/fesm2022/tech4good-platform-auth-firebase.mjs +254 -0
- package/fesm2022/tech4good-platform-auth-firebase.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth-profiles.mjs +72 -0
- package/fesm2022/tech4good-platform-auth-profiles.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth-testing.mjs +198 -0
- package/fesm2022/tech4good-platform-auth-testing.mjs.map +1 -0
- package/fesm2022/tech4good-platform-auth.mjs +390 -0
- package/fesm2022/tech4good-platform-auth.mjs.map +1 -0
- package/package.json +45 -3
- package/types/tech4good-platform-auth-firebase.d.ts +99 -0
- package/types/tech4good-platform-auth-firebase.d.ts.map +1 -0
- package/types/tech4good-platform-auth-profiles.d.ts +55 -0
- package/types/tech4good-platform-auth-profiles.d.ts.map +1 -0
- package/types/tech4good-platform-auth-testing.d.ts +87 -0
- package/types/tech4good-platform-auth-testing.d.ts.map +1 -0
- package/types/tech4good-platform-auth.d.ts +164 -0
- package/types/tech4good-platform-auth.d.ts.map +1 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { DOCUMENT } from '@angular/common';
|
|
2
|
+
import * as i0 from '@angular/core';
|
|
3
|
+
import { InjectionToken, inject, Injectable } from '@angular/core';
|
|
4
|
+
import { Observable, from } from 'rxjs';
|
|
5
|
+
import { switchMap, map } from 'rxjs/operators';
|
|
6
|
+
import { EmailAuthProvider, onIdTokenChanged, signInWithPopup, GoogleAuthProvider, signInAnonymously, linkWithPopup, isSignInWithEmailLink, linkWithCredential, signInWithEmailLink, signOut, sendSignInLinkToEmail } from 'firebase/auth';
|
|
7
|
+
import { PLATFORM_AUTH_OPTIONS, EmailLinkContextService, AUTH_ACCESS } from '@tech4good/platform-auth';
|
|
8
|
+
import { doc, runTransaction, serverTimestamp, getDoc } from 'firebase/firestore';
|
|
9
|
+
import { PLATFORM_FIRESTORE, decodeFirestoreData, encodeFirestoreData } from '@tech4good/platform-data/firestore';
|
|
10
|
+
import { PROFILE_PERSISTENCE } from '@tech4good/platform-auth/profiles';
|
|
11
|
+
|
|
12
|
+
/** The application initializes Firebase Auth and chooses its persistence/emulator. */
|
|
13
|
+
const PLATFORM_FIREBASE_AUTH = new InjectionToken('PlatformFirebaseAuth');
|
|
14
|
+
/**
|
|
15
|
+
* Maps a Firebase Auth `User` instance (or subset) into the application's normalized `AuthSession` model.
|
|
16
|
+
*
|
|
17
|
+
* Checks both top-level Firebase `User` properties and `providerData` entries to resolve
|
|
18
|
+
* available display names, profile avatars, verified email addresses, and enabled sign-in providers.
|
|
19
|
+
*
|
|
20
|
+
* @param currentUser The raw Firebase Auth user object.
|
|
21
|
+
* @returns A normalized `AuthSession` instance for state stores and guards.
|
|
22
|
+
*/
|
|
23
|
+
function firebaseUserToAuthSession(currentUser) {
|
|
24
|
+
const providerIds = currentUser.providerData.map((provider) => provider.providerId);
|
|
25
|
+
const firstProviderWithMeta = currentUser.providerData.find((p) => p.displayName || p.photoURL || p.email);
|
|
26
|
+
const displayName = currentUser.displayName || firstProviderWithMeta?.displayName || null;
|
|
27
|
+
const photoURL = currentUser.photoURL || firstProviderWithMeta?.photoURL || null;
|
|
28
|
+
const email = currentUser.email || firstProviderWithMeta?.email || null;
|
|
29
|
+
return {
|
|
30
|
+
uid: currentUser.uid,
|
|
31
|
+
email,
|
|
32
|
+
displayName,
|
|
33
|
+
photoURL,
|
|
34
|
+
isAnonymous: currentUser.isAnonymous,
|
|
35
|
+
emailVerified: currentUser.emailVerified,
|
|
36
|
+
emailLinkEnabled: providerIds.includes(EmailAuthProvider.PROVIDER_ID),
|
|
37
|
+
providerIds,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Firebase authentication operations extracted from the original FirebaseService. */
|
|
41
|
+
class FirebaseAuthService {
|
|
42
|
+
afAuth = inject(PLATFORM_FIREBASE_AUTH);
|
|
43
|
+
document = inject(DOCUMENT);
|
|
44
|
+
options = inject(PLATFORM_AUTH_OPTIONS);
|
|
45
|
+
emailLinkContext = inject(EmailLinkContextService);
|
|
46
|
+
// Firebase's own observer owns the subscription. AngularFire is only needed by
|
|
47
|
+
// apps that choose it for initialization; the package does not import it.
|
|
48
|
+
user$ = new Observable(subscriber => onIdTokenChanged(this.afAuth, user => subscriber.next(user), error => subscriber.error(error)));
|
|
49
|
+
/**
|
|
50
|
+
* Returns an observable stream emitting the current `AuthSession` whenever Firebase authentication state changes.
|
|
51
|
+
* Emits `null` when signed out.
|
|
52
|
+
*/
|
|
53
|
+
afUser() {
|
|
54
|
+
return from(this.afAuth.authStateReady()).pipe(switchMap(() => this.user$), map((currentUser) => currentUser ? firebaseUserToAuthSession(currentUser) : null));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Signs in a user via Google OAuth popup and returns the mapped `AuthSession`.
|
|
58
|
+
*
|
|
59
|
+
* Forces token initialization before Firestore provisioning to avoid a fresh-login credentials race.
|
|
60
|
+
*/
|
|
61
|
+
async signInWithGoogle() {
|
|
62
|
+
const result = await signInWithPopup(this.afAuth, new GoogleAuthProvider());
|
|
63
|
+
await result.user.getIdToken(true);
|
|
64
|
+
return firebaseUserToAuthSession(result.user);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Creates an anonymous Firebase Auth session.
|
|
68
|
+
*
|
|
69
|
+
* Forces ID token initialization immediately after creation to prevent race conditions
|
|
70
|
+
* with Firestore security rules on fresh sign-ins (especially after deleting a previous guest account).
|
|
71
|
+
*/
|
|
72
|
+
async signInAnonymously() {
|
|
73
|
+
const result = await signInAnonymously(this.afAuth);
|
|
74
|
+
// Force Firebase to establish the new anonymous token before AuthStore
|
|
75
|
+
// provisions Firestore data. This is especially important immediately
|
|
76
|
+
// after deleting a previous anonymous account.
|
|
77
|
+
await result.user.getIdToken(true);
|
|
78
|
+
return firebaseUserToAuthSession(result.user);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Links a Google identity to the currently signed-in Firebase user without changing their UID.
|
|
82
|
+
* Preserves existing guest/application data under the current UID.
|
|
83
|
+
*/
|
|
84
|
+
async linkGoogle() {
|
|
85
|
+
const currentUser = this.afAuth.currentUser;
|
|
86
|
+
if (!currentUser)
|
|
87
|
+
throw new Error('No authenticated user is available to link Google.');
|
|
88
|
+
const result = await linkWithPopup(currentUser, new GoogleAuthProvider());
|
|
89
|
+
await result.user.getIdToken(true);
|
|
90
|
+
return firebaseUserToAuthSession(result.user);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Dispatches a passwordless email magic link for sign-in or guest upgrading.
|
|
94
|
+
*
|
|
95
|
+
* Saves flow context into `EmailLinkContextService` before sending the email.
|
|
96
|
+
*
|
|
97
|
+
* @param email The destination email address.
|
|
98
|
+
*/
|
|
99
|
+
async sendEmailSignInLink(email) {
|
|
100
|
+
const currentUser = this.afAuth.currentUser;
|
|
101
|
+
const flow = currentUser?.isAnonymous ? 'guest-upgrade' : 'sign-in';
|
|
102
|
+
await this.sendEmailLink(email, flow, currentUser?.isAnonymous ? currentUser.uid : null);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Dispatches a passwordless email magic link to attach email-link sign-in to an existing account.
|
|
106
|
+
*/
|
|
107
|
+
async sendEmailLinkForCurrentAccount() {
|
|
108
|
+
const currentUser = this.afAuth.currentUser;
|
|
109
|
+
if (!currentUser?.email)
|
|
110
|
+
throw new Error('An email address is required to enable email-link sign-in.');
|
|
111
|
+
await this.sendEmailLink(currentUser.email, 'link-email', currentUser.uid);
|
|
112
|
+
}
|
|
113
|
+
/** Retrieves any stored email magic link email address from `EmailLinkContextService`. */
|
|
114
|
+
getStoredEmailForEmailLink() {
|
|
115
|
+
return this.emailLinkContext.getEmail();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Verifies the magic link URL and completes authentication or account linking.
|
|
119
|
+
*
|
|
120
|
+
* - Handles `sign-in`, `guest-upgrade`, and `link-email` workflows.
|
|
121
|
+
* - Enforces same-browser UID validation for upgrade and link flows.
|
|
122
|
+
* - Refreshes the Firebase token and clears stored magic link context upon completion.
|
|
123
|
+
*
|
|
124
|
+
* @param url The full callback URL (containing action code parameters).
|
|
125
|
+
* @param email The target email address.
|
|
126
|
+
* @returns The updated `AuthSession`.
|
|
127
|
+
*/
|
|
128
|
+
async completeEmailSignInLink(url, email) {
|
|
129
|
+
if (!isSignInWithEmailLink(this.afAuth, url)) {
|
|
130
|
+
throw this.authError('auth/invalid-action-code', 'This sign-in link is not valid.');
|
|
131
|
+
}
|
|
132
|
+
await this.afAuth.authStateReady();
|
|
133
|
+
const flow = this.getEmailLinkFlow(url);
|
|
134
|
+
const currentUser = this.afAuth.currentUser;
|
|
135
|
+
const storedUid = this.emailLinkContext.getUid();
|
|
136
|
+
if (flow === 'link-email' || flow === 'guest-upgrade') {
|
|
137
|
+
if (!currentUser || currentUser.uid !== storedUid) {
|
|
138
|
+
throw this.authError('auth/link-requires-original-session', 'Return to the browser where you started this account upgrade.');
|
|
139
|
+
}
|
|
140
|
+
const result = await linkWithCredential(currentUser, EmailAuthProvider.credentialWithLink(email, url));
|
|
141
|
+
await result.user.getIdToken(true);
|
|
142
|
+
this.clearEmailLinkContext();
|
|
143
|
+
return firebaseUserToAuthSession(result.user);
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
const result = await signInWithEmailLink(this.afAuth, email, url);
|
|
147
|
+
await result.user.getIdToken(true);
|
|
148
|
+
this.clearEmailLinkContext();
|
|
149
|
+
return firebaseUserToAuthSession(result.user);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
const activeUser = this.afAuth.currentUser;
|
|
153
|
+
if (activeUser && activeUser.email?.toLowerCase() === email.toLowerCase()) {
|
|
154
|
+
await activeUser.getIdToken(true);
|
|
155
|
+
this.clearEmailLinkContext();
|
|
156
|
+
return firebaseUserToAuthSession(activeUser);
|
|
157
|
+
}
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** Signs out the current Firebase user. */
|
|
162
|
+
async logout() {
|
|
163
|
+
await signOut(this.afAuth);
|
|
164
|
+
}
|
|
165
|
+
actionCodeSettings(flow) {
|
|
166
|
+
const origin = this.document.defaultView?.location.origin;
|
|
167
|
+
if (!origin)
|
|
168
|
+
throw new Error('Email actions require a browser origin.');
|
|
169
|
+
const url = new URL(this.options.emailActionUrl ?? '/auth/action', origin);
|
|
170
|
+
url.searchParams.set('flow', flow);
|
|
171
|
+
return { url: url.href, handleCodeInApp: true };
|
|
172
|
+
}
|
|
173
|
+
async sendEmailLink(email, flow, uid) {
|
|
174
|
+
const context = { email, flow, uid };
|
|
175
|
+
this.emailLinkContext.remember(context);
|
|
176
|
+
try {
|
|
177
|
+
await sendSignInLinkToEmail(this.afAuth, email, this.actionCodeSettings(flow));
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
this.emailLinkContext.clearIfMatches(context);
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
getEmailLinkFlow(url) {
|
|
185
|
+
const parsed = new URL(url);
|
|
186
|
+
const directFlow = parsed.searchParams.get('flow');
|
|
187
|
+
const continueUrl = parsed.searchParams.get('continueUrl');
|
|
188
|
+
const nestedFlow = continueUrl ? new URL(continueUrl).searchParams.get('flow') : null;
|
|
189
|
+
const flow = directFlow || nestedFlow || this.emailLinkContext.getFlow() || 'sign-in';
|
|
190
|
+
return flow === 'guest-upgrade' || flow === 'link-email' ? flow : 'sign-in';
|
|
191
|
+
}
|
|
192
|
+
clearEmailLinkContext() {
|
|
193
|
+
this.emailLinkContext.clear();
|
|
194
|
+
}
|
|
195
|
+
authError(code, message) {
|
|
196
|
+
return Object.assign(new Error(message), { code });
|
|
197
|
+
}
|
|
198
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirebaseAuthService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
199
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirebaseAuthService, providedIn: 'root' });
|
|
200
|
+
}
|
|
201
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirebaseAuthService, decorators: [{
|
|
202
|
+
type: Injectable,
|
|
203
|
+
args: [{ providedIn: 'root' }]
|
|
204
|
+
}] });
|
|
205
|
+
function provideFirebaseAuth() {
|
|
206
|
+
return [{ provide: AUTH_ACCESS, useExisting: FirebaseAuthService }];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Keep a concurrent login/tab from overwriting an already-created profile with defaults. */
|
|
210
|
+
class FirestoreProfilePersistence {
|
|
211
|
+
firestore = inject(PLATFORM_FIRESTORE);
|
|
212
|
+
async ensure(collection, privateCollection, uid, decide) {
|
|
213
|
+
const profileRef = doc(this.firestore, collection, uid);
|
|
214
|
+
const privateRef = privateCollection ? doc(this.firestore, privateCollection, uid) : null;
|
|
215
|
+
await runTransaction(this.firestore, async (transaction) => {
|
|
216
|
+
const snapshot = await transaction.get(profileRef);
|
|
217
|
+
const privateSnapshot = privateRef ? await transaction.get(privateRef) : null;
|
|
218
|
+
const existing = snapshot.exists() ? { ...decodeFirestoreData(snapshot.data()), __id: uid } : null;
|
|
219
|
+
const existingPrivate = privateSnapshot?.exists() ? { ...decodeFirestoreData(privateSnapshot.data()), __id: uid } : null;
|
|
220
|
+
const changes = decide(existing, existingPrivate);
|
|
221
|
+
const values = (fields, exists) => {
|
|
222
|
+
// Factories choose domain fields; identity and metadata remain adapter-owned.
|
|
223
|
+
const { __id, _createdAt, _updatedAt, _deleted, ...domain } = fields;
|
|
224
|
+
return { ...encodeFirestoreData(domain), __id: uid, _updatedAt: serverTimestamp(),
|
|
225
|
+
...(!exists ? { _createdAt: serverTimestamp(), _deleted: false } : {}) };
|
|
226
|
+
};
|
|
227
|
+
if (changes.profile)
|
|
228
|
+
transaction.set(profileRef, values(changes.profile, !!existing), { merge: !!existing });
|
|
229
|
+
if (privateRef && changes.privateProfile)
|
|
230
|
+
transaction.set(privateRef, values(changes.privateProfile, !!existingPrivate), { merge: !!existingPrivate });
|
|
231
|
+
});
|
|
232
|
+
// Read after acknowledgement so required timestamps are resolved server values.
|
|
233
|
+
const stored = await getDoc(profileRef);
|
|
234
|
+
if (!stored.exists())
|
|
235
|
+
throw new Error('The newly created user profile could not be read.');
|
|
236
|
+
return { ...decodeFirestoreData(stored.data()), __id: uid };
|
|
237
|
+
}
|
|
238
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirestoreProfilePersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
239
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirestoreProfilePersistence, providedIn: 'root' });
|
|
240
|
+
}
|
|
241
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: FirestoreProfilePersistence, decorators: [{
|
|
242
|
+
type: Injectable,
|
|
243
|
+
args: [{ providedIn: 'root' }]
|
|
244
|
+
}] });
|
|
245
|
+
function provideFirestoreProfiles() {
|
|
246
|
+
return [{ provide: PROFILE_PERSISTENCE, useExisting: FirestoreProfilePersistence }];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Generated bundle index. Do not edit.
|
|
251
|
+
*/
|
|
252
|
+
|
|
253
|
+
export { FirebaseAuthService, FirestoreProfilePersistence, PLATFORM_FIREBASE_AUTH, firebaseUserToAuthSession, provideFirebaseAuth, provideFirestoreProfiles };
|
|
254
|
+
//# sourceMappingURL=tech4good-platform-auth-firebase.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-auth-firebase.mjs","sources":["../../firebase/auth.ts","../../firebase/profiles.ts","../../firebase/tech4good-platform-auth-firebase.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport { Injectable, InjectionToken, inject, Provider } from '@angular/core';\nimport { Observable, from } from 'rxjs';\nimport { map, switchMap } from 'rxjs/operators';\nimport {\n Auth, User, onIdTokenChanged, signInWithPopup, signOut, linkWithPopup,\n linkWithCredential, EmailAuthProvider, isSignInWithEmailLink,\n sendSignInLinkToEmail, signInAnonymously, signInWithEmailLink, GoogleAuthProvider,\n} from 'firebase/auth';\nimport { AuthAccess, AuthSession, AUTH_ACCESS, EmailLinkContextService, EmailLinkFlow, PLATFORM_AUTH_OPTIONS } from '@tech4good/platform-auth';\n\n/** The application initializes Firebase Auth and chooses its persistence/emulator. */\nexport const PLATFORM_FIREBASE_AUTH = new InjectionToken<Auth>('PlatformFirebaseAuth');\n\ntype FirebaseAuthUser = Pick<\n User,\n | 'uid'\n | 'email'\n | 'displayName'\n | 'photoURL'\n | 'isAnonymous'\n | 'emailVerified'\n | 'providerData'\n>;\n\n/**\n * Maps a Firebase Auth `User` instance (or subset) into the application's normalized `AuthSession` model.\n *\n * Checks both top-level Firebase `User` properties and `providerData` entries to resolve\n * available display names, profile avatars, verified email addresses, and enabled sign-in providers.\n *\n * @param currentUser The raw Firebase Auth user object.\n * @returns A normalized `AuthSession` instance for state stores and guards.\n */\nexport function firebaseUserToAuthSession(currentUser: FirebaseAuthUser): AuthSession {\n const providerIds = currentUser.providerData.map((provider) => provider.providerId);\n const firstProviderWithMeta = currentUser.providerData.find((p) => p.displayName || p.photoURL || p.email);\n const displayName = currentUser.displayName || firstProviderWithMeta?.displayName || null;\n const photoURL = currentUser.photoURL || firstProviderWithMeta?.photoURL || null;\n const email = currentUser.email || firstProviderWithMeta?.email || null;\n\n return {\n uid: currentUser.uid,\n email,\n displayName,\n photoURL,\n isAnonymous: currentUser.isAnonymous,\n emailVerified: currentUser.emailVerified,\n emailLinkEnabled: providerIds.includes(EmailAuthProvider.PROVIDER_ID),\n providerIds,\n };\n}\n\n/** Firebase authentication operations extracted from the original FirebaseService. */\n@Injectable({ providedIn: 'root' })\nexport class FirebaseAuthService implements AuthAccess {\n private afAuth = inject(PLATFORM_FIREBASE_AUTH);\n private document = inject(DOCUMENT);\n private options = inject(PLATFORM_AUTH_OPTIONS);\n private emailLinkContext = inject(EmailLinkContextService);\n // Firebase's own observer owns the subscription. AngularFire is only needed by\n // apps that choose it for initialization; the package does not import it.\n private user$ = new Observable<User | null>(subscriber =>\n onIdTokenChanged(this.afAuth, user => subscriber.next(user), error => subscriber.error(error)));\n\n /**\n * Returns an observable stream emitting the current `AuthSession` whenever Firebase authentication state changes.\n * Emits `null` when signed out.\n */\n afUser(): Observable<AuthSession | null> {\n return from(this.afAuth.authStateReady()).pipe(\n switchMap(() => this.user$),\n map((currentUser) => currentUser ? firebaseUserToAuthSession(currentUser) : null),\n );\n }\n\n /**\n * Signs in a user via Google OAuth popup and returns the mapped `AuthSession`.\n *\n * Forces token initialization before Firestore provisioning to avoid a fresh-login credentials race.\n */\n async signInWithGoogle(): Promise<AuthSession> {\n const result = await signInWithPopup(this.afAuth, new GoogleAuthProvider());\n await result.user.getIdToken(true);\n return firebaseUserToAuthSession(result.user);\n }\n\n /**\n * Creates an anonymous Firebase Auth session.\n *\n * Forces ID token initialization immediately after creation to prevent race conditions\n * with Firestore security rules on fresh sign-ins (especially after deleting a previous guest account).\n */\n async signInAnonymously(): Promise<AuthSession> {\n const result = await signInAnonymously(this.afAuth);\n // Force Firebase to establish the new anonymous token before AuthStore\n // provisions Firestore data. This is especially important immediately\n // after deleting a previous anonymous account.\n await result.user.getIdToken(true);\n return firebaseUserToAuthSession(result.user);\n }\n\n /**\n * Links a Google identity to the currently signed-in Firebase user without changing their UID.\n * Preserves existing guest/application data under the current UID.\n */\n async linkGoogle(): Promise<AuthSession> {\n const currentUser = this.afAuth.currentUser;\n if (!currentUser) throw new Error('No authenticated user is available to link Google.');\n const result = await linkWithPopup(currentUser, new GoogleAuthProvider());\n await result.user.getIdToken(true);\n return firebaseUserToAuthSession(result.user);\n }\n\n /**\n * Dispatches a passwordless email magic link for sign-in or guest upgrading.\n *\n * Saves flow context into `EmailLinkContextService` before sending the email.\n *\n * @param email The destination email address.\n */\n async sendEmailSignInLink(email: string): Promise<void> {\n const currentUser = this.afAuth.currentUser;\n const flow = currentUser?.isAnonymous ? 'guest-upgrade' : 'sign-in';\n await this.sendEmailLink(email, flow, currentUser?.isAnonymous ? currentUser.uid : null);\n }\n\n /**\n * Dispatches a passwordless email magic link to attach email-link sign-in to an existing account.\n */\n async sendEmailLinkForCurrentAccount(): Promise<void> {\n const currentUser = this.afAuth.currentUser;\n if (!currentUser?.email) throw new Error('An email address is required to enable email-link sign-in.');\n await this.sendEmailLink(currentUser.email, 'link-email', currentUser.uid);\n }\n\n /** Retrieves any stored email magic link email address from `EmailLinkContextService`. */\n getStoredEmailForEmailLink(): string | null {\n return this.emailLinkContext.getEmail();\n }\n\n /**\n * Verifies the magic link URL and completes authentication or account linking.\n *\n * - Handles `sign-in`, `guest-upgrade`, and `link-email` workflows.\n * - Enforces same-browser UID validation for upgrade and link flows.\n * - Refreshes the Firebase token and clears stored magic link context upon completion.\n *\n * @param url The full callback URL (containing action code parameters).\n * @param email The target email address.\n * @returns The updated `AuthSession`.\n */\n async completeEmailSignInLink(url: string, email: string): Promise<AuthSession> {\n if (!isSignInWithEmailLink(this.afAuth, url)) {\n throw this.authError('auth/invalid-action-code', 'This sign-in link is not valid.');\n }\n await this.afAuth.authStateReady();\n\n const flow = this.getEmailLinkFlow(url);\n const currentUser = this.afAuth.currentUser;\n const storedUid = this.emailLinkContext.getUid();\n\n if (flow === 'link-email' || flow === 'guest-upgrade') {\n if (!currentUser || currentUser.uid !== storedUid) {\n throw this.authError('auth/link-requires-original-session', 'Return to the browser where you started this account upgrade.');\n }\n const result = await linkWithCredential(currentUser, EmailAuthProvider.credentialWithLink(email, url));\n await result.user.getIdToken(true);\n this.clearEmailLinkContext();\n return firebaseUserToAuthSession(result.user);\n }\n\n try {\n const result = await signInWithEmailLink(this.afAuth, email, url);\n await result.user.getIdToken(true);\n this.clearEmailLinkContext();\n return firebaseUserToAuthSession(result.user);\n } catch (error) {\n const activeUser = this.afAuth.currentUser;\n if (activeUser && activeUser.email?.toLowerCase() === email.toLowerCase()) {\n await activeUser.getIdToken(true);\n this.clearEmailLinkContext();\n return firebaseUserToAuthSession(activeUser);\n }\n throw error;\n }\n }\n\n /** Signs out the current Firebase user. */\n async logout() {\n await signOut(this.afAuth);\n }\n\n private actionCodeSettings(flow: EmailLinkFlow) {\n const origin = this.document.defaultView?.location.origin;\n if (!origin) throw new Error('Email actions require a browser origin.');\n const url = new URL(this.options.emailActionUrl ?? '/auth/action', origin);\n url.searchParams.set('flow', flow);\n return { url: url.href, handleCodeInApp: true };\n }\n\n private async sendEmailLink(email: string, flow: EmailLinkFlow, uid: string | null): Promise<void> {\n const context = { email, flow, uid };\n this.emailLinkContext.remember(context);\n try {\n await sendSignInLinkToEmail(this.afAuth, email, this.actionCodeSettings(flow));\n } catch (error) {\n this.emailLinkContext.clearIfMatches(context);\n throw error;\n }\n }\n\n private getEmailLinkFlow(url: string): EmailLinkFlow {\n const parsed = new URL(url);\n const directFlow = parsed.searchParams.get('flow');\n const continueUrl = parsed.searchParams.get('continueUrl');\n const nestedFlow = continueUrl ? new URL(continueUrl).searchParams.get('flow') : null;\n const flow = directFlow || nestedFlow || this.emailLinkContext.getFlow() || 'sign-in';\n return flow === 'guest-upgrade' || flow === 'link-email' ? flow : 'sign-in';\n }\n\n private clearEmailLinkContext(): void {\n this.emailLinkContext.clear();\n }\n\n private authError(code: string, message: string): Error & { code: string } {\n return Object.assign(new Error(message), { code });\n }\n}\n\nexport function provideFirebaseAuth(): Provider[] {\n return [{ provide: AUTH_ACCESS, useExisting: FirebaseAuthService }];\n}\n","import { Injectable, inject, Provider } from '@angular/core';\nimport { doc, getDoc, runTransaction, serverTimestamp } from 'firebase/firestore';\nimport { PLATFORM_FIRESTORE, decodeFirestoreData, encodeFirestoreData } from '@tech4good/platform-data/firestore';\nimport { ProfilePersistence, ProfileRecord, PROFILE_PERSISTENCE, ProfileChanges } from '@tech4good/platform-auth/profiles';\n\n/** Keep a concurrent login/tab from overwriting an already-created profile with defaults. */\n@Injectable({ providedIn: 'root' })\nexport class FirestoreProfilePersistence implements ProfilePersistence {\n private readonly firestore = inject(PLATFORM_FIRESTORE);\n async ensure(collection: string, privateCollection: string | null, uid: string,\n decide: (profile: ProfileRecord | null, privateProfile: ProfileRecord | null) => ProfileChanges,\n ): Promise<ProfileRecord> {\n const profileRef = doc(this.firestore, collection, uid);\n const privateRef = privateCollection ? doc(this.firestore, privateCollection, uid) : null;\n await runTransaction(this.firestore, async transaction => {\n const snapshot = await transaction.get(profileRef);\n const privateSnapshot = privateRef ? await transaction.get(privateRef) : null;\n const existing = snapshot.exists() ? { ...decodeFirestoreData(snapshot.data()), __id: uid } : null;\n const existingPrivate = privateSnapshot?.exists() ? { ...decodeFirestoreData(privateSnapshot.data()), __id: uid } : null;\n const changes = decide(existing, existingPrivate);\n const values = (fields: Record<string, unknown>, exists: boolean) => {\n // Factories choose domain fields; identity and metadata remain adapter-owned.\n const { __id, _createdAt, _updatedAt, _deleted, ...domain } = fields;\n return { ...encodeFirestoreData(domain), __id: uid, _updatedAt: serverTimestamp(),\n ...(!exists ? { _createdAt: serverTimestamp(), _deleted: false } : {}) };\n };\n if (changes.profile) transaction.set(profileRef, values(changes.profile, !!existing), { merge: !!existing });\n if (privateRef && changes.privateProfile) transaction.set(privateRef, values(changes.privateProfile, !!existingPrivate), { merge: !!existingPrivate });\n });\n // Read after acknowledgement so required timestamps are resolved server values.\n const stored = await getDoc(profileRef);\n if (!stored.exists()) throw new Error('The newly created user profile could not be read.');\n return { ...decodeFirestoreData(stored.data()), __id: uid };\n }\n}\nexport function provideFirestoreProfiles(): Provider[] {\n return [{ provide: PROFILE_PERSISTENCE, useExisting: FirestoreProfilePersistence }];\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;;;;AAWA;MACa,sBAAsB,GAAG,IAAI,cAAc,CAAO,sBAAsB;AAarF;;;;;;;;AAQG;AACG,SAAU,yBAAyB,CAAC,WAA6B,EAAA;AACrE,IAAA,MAAM,WAAW,GAAG,WAAW,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,QAAQ,KAAK,QAAQ,CAAC,UAAU,CAAC;IACnF,MAAM,qBAAqB,GAAG,WAAW,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC;IAC1G,MAAM,WAAW,GAAG,WAAW,CAAC,WAAW,IAAI,qBAAqB,EAAE,WAAW,IAAI,IAAI;IACzF,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,IAAI,qBAAqB,EAAE,QAAQ,IAAI,IAAI;IAChF,MAAM,KAAK,GAAG,WAAW,CAAC,KAAK,IAAI,qBAAqB,EAAE,KAAK,IAAI,IAAI;IAEvE,OAAO;QACL,GAAG,EAAE,WAAW,CAAC,GAAG;QACpB,KAAK;QACL,WAAW;QACX,QAAQ;QACR,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,aAAa,EAAE,WAAW,CAAC,aAAa;QACxC,gBAAgB,EAAE,WAAW,CAAC,QAAQ,CAAC,iBAAiB,CAAC,WAAW,CAAC;QACrE,WAAW;KACZ;AACH;AAEA;MAEa,mBAAmB,CAAA;AACtB,IAAA,MAAM,GAAG,MAAM,CAAC,sBAAsB,CAAC;AACvC,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC3B,IAAA,OAAO,GAAG,MAAM,CAAC,q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
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, Injectable } from '@angular/core';
|
|
3
|
+
import { PROFILE_PROVISIONER } from '@tech4good/platform-auth';
|
|
4
|
+
|
|
5
|
+
const PROFILE_PERSISTENCE = new InjectionToken('PlatformProfilePersistence');
|
|
6
|
+
const USER_PROFILE_OPTIONS = new InjectionToken('PlatformUserProfileOptions');
|
|
7
|
+
/** Default new-user fields. App access state is deliberately supplied by the caller. */
|
|
8
|
+
function defaultLabProfile(session, fallbackName = 'Learner') {
|
|
9
|
+
return {
|
|
10
|
+
name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : fallbackName),
|
|
11
|
+
isAdmin: false,
|
|
12
|
+
consented: false,
|
|
13
|
+
...(session.photoURL ? { photoURL: session.photoURL } : {}),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
class UserProfileService {
|
|
17
|
+
persistence = inject(PROFILE_PERSISTENCE);
|
|
18
|
+
options = inject(USER_PROFILE_OPTIONS);
|
|
19
|
+
/**
|
|
20
|
+
* Ensure users/{uid} and userPrivates/{uid} exist for an authenticated user.
|
|
21
|
+
* Initialize missing profiles with app-configured defaults. For an existing
|
|
22
|
+
* profile, only update a generated name or changed avatar unless the app
|
|
23
|
+
* explicitly supplies another reconciliation policy. Existing consent, roles
|
|
24
|
+
* and access state must not be replaced with new-user defaults on each login.
|
|
25
|
+
*/
|
|
26
|
+
ensureUserProfile(session) {
|
|
27
|
+
const options = this.options;
|
|
28
|
+
return this.persistence.ensure(options.profileCollection ?? 'users', options.privateCollection === undefined ? 'userPrivates' : options.privateCollection, session.uid, (existing, existingPrivate) => {
|
|
29
|
+
let profile = null;
|
|
30
|
+
if (!existing) {
|
|
31
|
+
profile = options.createProfile(session);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
const generatedName = !existing['name'] ||
|
|
35
|
+
(options.generatedNames ?? ['Guest', 'Learner']).includes(existing['name']) ||
|
|
36
|
+
existing['name'] === session.email;
|
|
37
|
+
const changes = options.reconcileProfile ? options.reconcileProfile(existing, session) : {
|
|
38
|
+
...(generatedName && session.displayName ? { name: session.displayName } : {}),
|
|
39
|
+
...(session.photoURL && existing['photoURL'] !== session.photoURL ? { photoURL: session.photoURL } : {}),
|
|
40
|
+
};
|
|
41
|
+
if (Object.keys(changes).length > 0)
|
|
42
|
+
profile = changes;
|
|
43
|
+
}
|
|
44
|
+
// Preserve the original email-only private-record synchronization. A
|
|
45
|
+
// missing email does not erase an existing private profile.
|
|
46
|
+
const privateProfile = session.email ? {
|
|
47
|
+
email: session.email,
|
|
48
|
+
...(session.emailLinkEnabled !== undefined ? { emailLinkEnabled: session.emailLinkEnabled } : {}),
|
|
49
|
+
} : null;
|
|
50
|
+
return { profile, privateProfile };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: UserProfileService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
54
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: UserProfileService, providedIn: 'root' });
|
|
55
|
+
}
|
|
56
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: UserProfileService, decorators: [{
|
|
57
|
+
type: Injectable,
|
|
58
|
+
args: [{ providedIn: 'root' }]
|
|
59
|
+
}] });
|
|
60
|
+
function provideUserProfiles(options) {
|
|
61
|
+
return [
|
|
62
|
+
{ provide: USER_PROFILE_OPTIONS, useValue: options },
|
|
63
|
+
{ provide: PROFILE_PROVISIONER, useExisting: UserProfileService },
|
|
64
|
+
];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Generated bundle index. Do not edit.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
export { PROFILE_PERSISTENCE, USER_PROFILE_OPTIONS, UserProfileService, defaultLabProfile, provideUserProfiles };
|
|
72
|
+
//# sourceMappingURL=tech4good-platform-auth-profiles.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-auth-profiles.mjs","sources":["../../profiles/public-api.ts","../../profiles/tech4good-platform-auth-profiles.ts"],"sourcesContent":["import { Injectable, InjectionToken, inject, Provider } from '@angular/core';\nimport { DataEntity, NewDataEntity } from '@tech4good/platform-data';\nimport { AuthSession, PROFILE_PROVISIONER, ProfileProvisioner } from '@tech4good/platform-auth';\n\n/** Default lab fields; each app extends this with its own access states and roles. */\nexport interface LabProfile extends DataEntity {\n name: string;\n isAdmin: boolean;\n consented: boolean;\n photoURL?: string | null;\n}\nexport type ProfileRecord = DataEntity & Record<string, any>;\nexport interface ProfileChanges {\n /** New fields when absent; only changed fields when present; null means no write. */\n profile: Record<string, unknown> | null;\n privateProfile: Record<string, unknown> | null;\n}\n/** Atomic read/decide/write boundary. A get followed by an unconditional set is insufficient. */\nexport interface ProfilePersistence {\n ensure(profileCollection: string, privateCollection: string | null, uid: string,\n changes: (profile: ProfileRecord | null, privateProfile: ProfileRecord | null) => ProfileChanges,\n ): Promise<ProfileRecord>;\n}\nexport const PROFILE_PERSISTENCE = new InjectionToken<ProfilePersistence>('PlatformProfilePersistence');\n\nexport interface UserProfileOptions<T extends LabProfile> {\n profileCollection?: string;\n /** Set null when this app does not keep a separate private email record. */\n privateCollection?: string | null;\n /** Called only for a missing profile. Must be pure: Firestore can retry it. */\n createProfile: (session: AuthSession) => NewDataEntity<T>;\n /** Override the default generated-name/avatar synchronization for existing records. */\n reconcileProfile?: (profile: T, session: AuthSession) => Partial<NewDataEntity<T>>;\n generatedNames?: readonly string[];\n}\nexport const USER_PROFILE_OPTIONS = new InjectionToken<UserProfileOptions<any>>('PlatformUserProfileOptions');\n\n/** Default new-user fields. App access state is deliberately supplied by the caller. */\nexport function defaultLabProfile(session: AuthSession, fallbackName = 'Learner'): NewDataEntity<LabProfile> {\n return {\n name: session.displayName || session.email || (session.isAnonymous ? 'Guest' : fallbackName),\n isAdmin: false,\n consented: false,\n ...(session.photoURL ? { photoURL: session.photoURL } : {}),\n };\n}\n\n@Injectable({ providedIn: 'root' })\nexport class UserProfileService implements ProfileProvisioner {\n private readonly persistence = inject(PROFILE_PERSISTENCE);\n private readonly options = inject(USER_PROFILE_OPTIONS);\n\n /**\n * Ensure users/{uid} and userPrivates/{uid} exist for an authenticated user.\n * Initialize missing profiles with app-configured defaults. For an existing\n * profile, only update a generated name or changed avatar unless the app\n * explicitly supplies another reconciliation policy. Existing consent, roles\n * and access state must not be replaced with new-user defaults on each login.\n */\n ensureUserProfile(session: AuthSession): Promise<ProfileRecord> {\n const options = this.options;\n return this.persistence.ensure(options.profileCollection ?? 'users',\n options.privateCollection === undefined ? 'userPrivates' : options.privateCollection,\n session.uid, (existing, existingPrivate) => {\n let profile: Record<string, unknown> | null = null;\n if (!existing) {\n profile = options.createProfile(session);\n } else {\n const generatedName = !existing['name'] ||\n (options.generatedNames ?? ['Guest', 'Learner']).includes(existing['name']) ||\n existing['name'] === session.email;\n const changes = options.reconcileProfile ? options.reconcileProfile(existing, session) : {\n ...(generatedName && session.displayName ? { name: session.displayName } : {}),\n ...(session.photoURL && existing['photoURL'] !== session.photoURL ? { photoURL: session.photoURL } : {}),\n };\n if (Object.keys(changes).length > 0) profile = changes;\n }\n // Preserve the original email-only private-record synchronization. A\n // missing email does not erase an existing private profile.\n const privateProfile = session.email ? {\n email: session.email,\n ...(session.emailLinkEnabled !== undefined ? { emailLinkEnabled: session.emailLinkEnabled } : {}),\n } : null;\n return { profile, privateProfile };\n });\n }\n}\nexport function provideUserProfiles<T extends LabProfile>(options: UserProfileOptions<T>): Provider[] {\n return [\n { provide: USER_PROFILE_OPTIONS, useValue: options },\n { provide: PROFILE_PROVISIONER, useExisting: UserProfileService },\n ];\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;MAuB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M,EAAE;;AAwC5B,SAAU,mBAAmB,CAAuB,OAA8B,EAAA;IACtF,OAAO;AACL,QAAA,EAAE,OAAO,EAAE,oBAAoB,EAAE,QAAQ,EAAE,OAAO,EAAE;AACpD,QAAA,EAAE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,kBAAkB,EAAE;KAClE;AACH;;AC5FA;;AAEG;;"}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { DOCUMENT } from '@angular/common';
|
|
2
|
+
import * as i0 from '@angular/core';
|
|
3
|
+
import { InjectionToken, inject, Inject, Injectable, DestroyRef } from '@angular/core';
|
|
4
|
+
import { signalStoreFeature, withState, withMethods, patchState } from '@ngrx/signals';
|
|
5
|
+
import { BehaviorSubject } from 'rxjs';
|
|
6
|
+
import { EmailLinkContextService, AUTH_ACCESS } from '@tech4good/platform-auth';
|
|
7
|
+
import { dataTimestampNow } from '@tech4good/platform-data';
|
|
8
|
+
import { MockDataService } from '@tech4good/platform-data/testing';
|
|
9
|
+
import { PROFILE_PERSISTENCE } from '@tech4good/platform-auth/profiles';
|
|
10
|
+
|
|
11
|
+
const MOCK_AUTH_OPTIONS = new InjectionToken('MockAuthOptions', {
|
|
12
|
+
providedIn: 'root', factory: () => ({}),
|
|
13
|
+
});
|
|
14
|
+
/** Generic fixture identity; apps supply their own seeded user's identity. */
|
|
15
|
+
function createMockAuthSession(overrides = {}) {
|
|
16
|
+
return {
|
|
17
|
+
uid: 'mock-user', email: 'learner@example.test', displayName: 'Learner', photoURL: null,
|
|
18
|
+
isAnonymous: false, emailVerified: true, emailLinkEnabled: false, providerIds: ['google.com'], ...overrides,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** In-memory auth simulator. It never contacts an identity provider or sends email. */
|
|
22
|
+
class MockAuthService {
|
|
23
|
+
document = inject(DOCUMENT);
|
|
24
|
+
context = inject(EmailLinkContextService);
|
|
25
|
+
options;
|
|
26
|
+
sessions;
|
|
27
|
+
/** Configure a rejection for a particular operation, then remove it to retry. */
|
|
28
|
+
failures = {};
|
|
29
|
+
constructor(options = inject(MOCK_AUTH_OPTIONS)) {
|
|
30
|
+
this.options = options;
|
|
31
|
+
let initial = options.initialSession ?? null;
|
|
32
|
+
if (options.persistSession) {
|
|
33
|
+
try {
|
|
34
|
+
const saved = this.document.defaultView?.localStorage.getItem(options.storageKey ?? 'mockUser');
|
|
35
|
+
if (saved)
|
|
36
|
+
initial = createMockAuthSession(JSON.parse(saved));
|
|
37
|
+
}
|
|
38
|
+
catch { /* Storage may be unavailable in a privacy-restricted browser. */ }
|
|
39
|
+
}
|
|
40
|
+
this.sessions = new BehaviorSubject(initial);
|
|
41
|
+
}
|
|
42
|
+
afUser() { return this.sessions.asObservable(); }
|
|
43
|
+
get session() { return this.sessions.value; }
|
|
44
|
+
/** Simulate restoration, another tab signing out, or an external UID change. */
|
|
45
|
+
setSession(session) {
|
|
46
|
+
this.sessions.next(session);
|
|
47
|
+
if (this.options.persistSession) {
|
|
48
|
+
try {
|
|
49
|
+
const storage = this.document.defaultView?.localStorage;
|
|
50
|
+
const key = this.options.storageKey ?? 'mockUser';
|
|
51
|
+
if (session)
|
|
52
|
+
storage?.setItem(key, JSON.stringify(session));
|
|
53
|
+
else
|
|
54
|
+
storage?.removeItem(key);
|
|
55
|
+
}
|
|
56
|
+
catch { /* In-memory auth continues if persistence is blocked. */ }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
check(operation) {
|
|
60
|
+
if (operation in this.failures)
|
|
61
|
+
throw this.failures[operation];
|
|
62
|
+
}
|
|
63
|
+
complete(session) { this.setSession(session); return session; }
|
|
64
|
+
async signInWithGoogle() {
|
|
65
|
+
this.check('signInWithGoogle');
|
|
66
|
+
return this.complete(this.options.googleSession ?? createMockAuthSession());
|
|
67
|
+
}
|
|
68
|
+
async signInAnonymously() {
|
|
69
|
+
this.check('signInAnonymously');
|
|
70
|
+
return this.complete(createMockAuthSession({ uid: this.options.anonymousUid ?? 'guest-anon-id',
|
|
71
|
+
email: null, displayName: 'Guest', photoURL: null, isAnonymous: true, emailVerified: false, providerIds: [] }));
|
|
72
|
+
}
|
|
73
|
+
async linkGoogle() {
|
|
74
|
+
this.check('linkGoogle');
|
|
75
|
+
if (!this.session)
|
|
76
|
+
throw new Error('No authenticated user is available to link Google.');
|
|
77
|
+
const google = this.options.googleSession ?? createMockAuthSession();
|
|
78
|
+
// Linking upgrades this account. Signing into a fixture's different UID would
|
|
79
|
+
// hide bugs where the app accidentally abandons a guest's existing records.
|
|
80
|
+
return this.complete({ ...this.session, email: google.email, displayName: google.displayName,
|
|
81
|
+
photoURL: google.photoURL, isAnonymous: false, emailVerified: google.emailVerified,
|
|
82
|
+
providerIds: [...new Set([...this.session.providerIds, 'google.com'])] });
|
|
83
|
+
}
|
|
84
|
+
async sendEmailSignInLink(email) {
|
|
85
|
+
this.check('sendEmailSignInLink');
|
|
86
|
+
const guest = this.session?.isAnonymous;
|
|
87
|
+
this.context.remember({ email, flow: guest ? 'guest-upgrade' : 'sign-in', uid: guest ? this.session.uid : null });
|
|
88
|
+
}
|
|
89
|
+
async sendEmailLinkForCurrentAccount() {
|
|
90
|
+
this.check('sendEmailLinkForCurrentAccount');
|
|
91
|
+
if (!this.session?.email)
|
|
92
|
+
throw new Error('An email address is required to enable email-link sign-in.');
|
|
93
|
+
this.context.remember({ email: this.session.email, flow: 'link-email', uid: this.session.uid });
|
|
94
|
+
}
|
|
95
|
+
getStoredEmailForEmailLink() { return this.context.getEmail(); }
|
|
96
|
+
async completeEmailSignInLink(url, email) {
|
|
97
|
+
this.check('completeEmailSignInLink');
|
|
98
|
+
const parsed = new URL(url);
|
|
99
|
+
const continueUrl = parsed.searchParams.get('continueUrl');
|
|
100
|
+
const flow = parsed.searchParams.get('flow') || (continueUrl ? new URL(continueUrl).searchParams.get('flow') : null) || this.context.getFlow();
|
|
101
|
+
const linking = flow === 'guest-upgrade' || flow === 'link-email';
|
|
102
|
+
if (linking && (!this.session || this.session.uid !== this.context.getUid())) {
|
|
103
|
+
throw Object.assign(new Error('Return to the browser where you started this account upgrade.'), { code: 'auth/link-requires-original-session' });
|
|
104
|
+
}
|
|
105
|
+
const base = linking ? this.session : this.options.emailSession ?? this.options.googleSession ?? createMockAuthSession();
|
|
106
|
+
const session = this.complete({ ...base, email, emailVerified: true, isAnonymous: false,
|
|
107
|
+
emailLinkEnabled: true, providerIds: [...new Set([...(linking ? base.providerIds : []), 'password'])] });
|
|
108
|
+
this.context.clear();
|
|
109
|
+
return session;
|
|
110
|
+
}
|
|
111
|
+
async logout() { this.check('logout'); this.setSession(null); }
|
|
112
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockAuthService, deps: [{ token: MOCK_AUTH_OPTIONS }], target: i0.ɵɵFactoryTarget.Injectable });
|
|
113
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockAuthService, providedIn: 'root' });
|
|
114
|
+
}
|
|
115
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockAuthService, decorators: [{
|
|
116
|
+
type: Injectable,
|
|
117
|
+
args: [{ providedIn: 'root' }]
|
|
118
|
+
}], ctorParameters: () => [{ type: undefined, decorators: [{
|
|
119
|
+
type: Inject,
|
|
120
|
+
args: [MOCK_AUTH_OPTIONS]
|
|
121
|
+
}] }] });
|
|
122
|
+
function provideMockAuth(options = {}) {
|
|
123
|
+
return [{ provide: MOCK_AUTH_OPTIONS, useValue: options }, { provide: AUTH_ACCESS, useExisting: MockAuthService }];
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Lightweight UI-test store feature: skips profile loading deliberately. Use
|
|
127
|
+
* withAuthSession + provideMockAuth to test the actual provisioning lifecycle.
|
|
128
|
+
* Apps add their user selector over their own profile fixtures.
|
|
129
|
+
*/
|
|
130
|
+
function withMockAuthSession(options = {}) {
|
|
131
|
+
return signalStoreFeature(withState({ afUser: null, isLoadingLogin: false, authStatus: 'initializing', authError: null }), withMethods(store => {
|
|
132
|
+
const auth = new MockAuthService(options);
|
|
133
|
+
const subscription = auth.afUser().subscribe(afUser => patchState(store, { afUser, authStatus: afUser ? 'ready' : 'signed-out' }));
|
|
134
|
+
inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
|
|
135
|
+
return {
|
|
136
|
+
loadAuth() { },
|
|
137
|
+
async signInWithGoogle() { await auth.signInWithGoogle(); },
|
|
138
|
+
async loginAnonymously() { await auth.signInAnonymously(); },
|
|
139
|
+
async linkGoogle() { await auth.linkGoogle(); },
|
|
140
|
+
async sendEmailSignInLink(email) { await auth.sendEmailSignInLink(email); },
|
|
141
|
+
async sendEmailLinkForCurrentAccount() { await auth.sendEmailLinkForCurrentAccount(); },
|
|
142
|
+
getStoredEmailForEmailLink() { return auth.getStoredEmailForEmailLink(); },
|
|
143
|
+
async completeEmailSignInLink(url, email) { return auth.completeEmailSignInLink(url, email); },
|
|
144
|
+
async deleteAnonymousAccount() { await auth.logout(); },
|
|
145
|
+
async logout() { await auth.logout(); },
|
|
146
|
+
async whenReady() { return store.afUser(); },
|
|
147
|
+
};
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Same profile decisions as Firestore, with serialized mock read/decide/write operations. */
|
|
152
|
+
class MockProfilePersistence {
|
|
153
|
+
db = inject(MockDataService);
|
|
154
|
+
pending = Promise.resolve();
|
|
155
|
+
ensure(collection, privateCollection, uid, decide) {
|
|
156
|
+
const operation = this.pending.then(async () => {
|
|
157
|
+
const existing = await this.db.getEntity(collection, uid);
|
|
158
|
+
const existingPrivate = privateCollection ? await this.db.getEntity(privateCollection, uid) : null;
|
|
159
|
+
const changes = decide(existing, existingPrivate);
|
|
160
|
+
const values = (fields, exists) => {
|
|
161
|
+
const { __id, _createdAt, _updatedAt, _deleted, ...domain } = fields;
|
|
162
|
+
const now = dataTimestampNow();
|
|
163
|
+
return { ...domain, __id: uid, _updatedAt: now,
|
|
164
|
+
...(!exists ? { _createdAt: now, _deleted: false } : {}) };
|
|
165
|
+
};
|
|
166
|
+
const operations = [];
|
|
167
|
+
if (changes.profile)
|
|
168
|
+
operations.push({ kind: existing ? 'update' : 'set', path: `${collection}/${uid}`, value: values(changes.profile, !!existing) });
|
|
169
|
+
if (privateCollection && changes.privateProfile)
|
|
170
|
+
operations.push({ kind: existingPrivate ? 'update' : 'set', path: `${privateCollection}/${uid}`, value: values(changes.privateProfile, !!existingPrivate) });
|
|
171
|
+
// MockDataService validates the complete batch before changing any collection.
|
|
172
|
+
if (operations.length)
|
|
173
|
+
await this.db.commitOperations(operations);
|
|
174
|
+
const profile = await this.db.getEntity(collection, uid);
|
|
175
|
+
if (!profile)
|
|
176
|
+
throw new Error('The newly created user profile could not be read.');
|
|
177
|
+
return profile;
|
|
178
|
+
});
|
|
179
|
+
this.pending = operation.catch(() => { }); // A failed request must not poison later retries.
|
|
180
|
+
return operation;
|
|
181
|
+
}
|
|
182
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockProfilePersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
183
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockProfilePersistence, providedIn: 'root' });
|
|
184
|
+
}
|
|
185
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.23", ngImport: i0, type: MockProfilePersistence, decorators: [{
|
|
186
|
+
type: Injectable,
|
|
187
|
+
args: [{ providedIn: 'root' }]
|
|
188
|
+
}] });
|
|
189
|
+
function provideMockProfiles() {
|
|
190
|
+
return [{ provide: PROFILE_PERSISTENCE, useExisting: MockProfilePersistence }];
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Generated bundle index. Do not edit.
|
|
195
|
+
*/
|
|
196
|
+
|
|
197
|
+
export { MOCK_AUTH_OPTIONS, MockAuthService, MockProfilePersistence, createMockAuthSession, provideMockAuth, provideMockProfiles, withMockAuthSession };
|
|
198
|
+
//# sourceMappingURL=tech4good-platform-auth-testing.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-auth-testing.mjs","sources":["../../testing/auth.ts","../../testing/profiles.ts","../../testing/tech4good-platform-auth-testing.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport { DestroyRef, Inject, Injectable, InjectionToken, Provider, inject } from '@angular/core';\nimport { patchState, signalStoreFeature, withMethods, withState } from '@ngrx/signals';\nimport { BehaviorSubject } from 'rxjs';\nimport { AUTH_ACCESS, AuthAccess, AuthSession, AuthStatus, EmailLinkContextService } from '@tech4good/platform-auth';\n\nexport interface MockAuthOptions {\n initialSession?: AuthSession | null;\n googleSession?: AuthSession;\n emailSession?: AuthSession;\n anonymousUid?: string;\n /** Opt-in browser persistence, matching the app's former mockUser key. */\n persistSession?: boolean;\n storageKey?: string;\n}\nexport const MOCK_AUTH_OPTIONS = new InjectionToken<MockAuthOptions>('MockAuthOptions', {\n providedIn: 'root', factory: () => ({}),\n});\n\n/** Generic fixture identity; apps supply their own seeded user's identity. */\nexport function createMockAuthSession(overrides: Partial<AuthSession> = {}): AuthSession {\n return {\n uid: 'mock-user', email: 'learner@example.test', displayName: 'Learner', photoURL: null,\n isAnonymous: false, emailVerified: true, emailLinkEnabled: false, providerIds: ['google.com'], ...overrides,\n };\n}\n\n/** In-memory auth simulator. It never contacts an identity provider or sends email. */\n@Injectable({ providedIn: 'root' })\nexport class MockAuthService implements AuthAccess {\n private document = inject(DOCUMENT);\n private context = inject(EmailLinkContextService);\n private options: MockAuthOptions;\n private sessions: BehaviorSubject<AuthSession | null>;\n /** Configure a rejection for a particular operation, then remove it to retry. */\n readonly failures: Partial<Record<keyof AuthAccess, unknown>> = {};\n\n constructor(@Inject(MOCK_AUTH_OPTIONS) options: MockAuthOptions = inject(MOCK_AUTH_OPTIONS)) {\n this.options = options;\n let initial = options.initialSession ?? null;\n if (options.persistSession) {\n try {\n const saved = this.document.defaultView?.localStorage.getItem(options.storageKey ?? 'mockUser');\n if (saved) initial = createMockAuthSession(JSON.parse(saved));\n } catch { /* Storage may be unavailable in a privacy-restricted browser. */ }\n }\n this.sessions = new BehaviorSubject(initial);\n }\n afUser() { return this.sessions.asObservable(); }\n get session(): AuthSession | null { return this.sessions.value; }\n /** Simulate restoration, another tab signing out, or an external UID change. */\n setSession(session: AuthSession | null): void {\n this.sessions.next(session);\n if (this.options.persistSession) {\n try {\n const storage = this.document.defaultView?.localStorage;\n const key = this.options.storageKey ?? 'mockUser';\n if (session) storage?.setItem(key, JSON.stringify(session)); else storage?.removeItem(key);\n } catch { /* In-memory auth continues if persistence is blocked. */ }\n }\n }\n private check(operation: keyof AuthAccess): void {\n if (operation in this.failures) throw this.failures[operation];\n }\n private complete(session: AuthSession): AuthSession { this.setSession(session); return session; }\n async signInWithGoogle(): Promise<AuthSession> {\n this.check('signInWithGoogle');\n return this.complete(this.options.googleSession ?? createMockAuthSession());\n }\n async signInAnonymously(): Promise<AuthSession> {\n this.check('signInAnonymously');\n return this.complete(createMockAuthSession({ uid: this.options.anonymousUid ?? 'guest-anon-id',\n email: null, displayName: 'Guest', photoURL: null, isAnonymous: true, emailVerified: false, providerIds: [] }));\n }\n async linkGoogle(): Promise<AuthSession> {\n this.check('linkGoogle');\n if (!this.session) throw new Error('No authenticated user is available to link Google.');\n const google = this.options.googleSession ?? createMockAuthSession();\n // Linking upgrades this account. Signing into a fixture's different UID would\n // hide bugs where the app accidentally abandons a guest's existing records.\n return this.complete({ ...this.session, email: google.email, displayName: google.displayName,\n photoURL: google.photoURL, isAnonymous: false, emailVerified: google.emailVerified,\n providerIds: [...new Set([...this.session.providerIds, 'google.com'])] });\n }\n async sendEmailSignInLink(email: string): Promise<void> {\n this.check('sendEmailSignInLink');\n const guest = this.session?.isAnonymous;\n this.context.remember({ email, flow: guest ? 'guest-upgrade' : 'sign-in', uid: guest ? this.session!.uid : null });\n }\n async sendEmailLinkForCurrentAccount(): Promise<void> {\n this.check('sendEmailLinkForCurrentAccount');\n if (!this.session?.email) throw new Error('An email address is required to enable email-link sign-in.');\n this.context.remember({ email: this.session.email, flow: 'link-email', uid: this.session.uid });\n }\n getStoredEmailForEmailLink(): string | null { return this.context.getEmail(); }\n async completeEmailSignInLink(url: string, email: string): Promise<AuthSession> {\n this.check('completeEmailSignInLink');\n const parsed = new URL(url);\n const continueUrl = parsed.searchParams.get('continueUrl');\n const flow = parsed.searchParams.get('flow') || (continueUrl ? new URL(continueUrl).searchParams.get('flow') : null) || this.context.getFlow();\n const linking = flow === 'guest-upgrade' || flow === 'link-email';\n if (linking && (!this.session || this.session.uid !== this.context.getUid())) {\n throw Object.assign(new Error('Return to the browser where you started this account upgrade.'), { code: 'auth/link-requires-original-session' });\n }\n const base = linking ? this.session! : this.options.emailSession ?? this.options.googleSession ?? createMockAuthSession();\n const session = this.complete({ ...base, email, emailVerified: true, isAnonymous: false,\n emailLinkEnabled: true, providerIds: [...new Set([...(linking ? base.providerIds : []), 'password'])] });\n this.context.clear();\n return session;\n }\n async logout(): Promise<void> { this.check('logout'); this.setSession(null); }\n}\nexport function provideMockAuth(options: MockAuthOptions = {}): Provider[] {\n return [{ provide: MOCK_AUTH_OPTIONS, useValue: options }, { provide: AUTH_ACCESS, useExisting: MockAuthService }];\n}\n\n/**\n * Lightweight UI-test store feature: skips profile loading deliberately. Use\n * withAuthSession + provideMockAuth to test the actual provisioning lifecycle.\n * Apps add their user selector over their own profile fixtures.\n */\nexport function withMockAuthSession(options: MockAuthOptions = {}) {\n return signalStoreFeature(\n withState({ afUser: null as AuthSession | null, isLoadingLogin: false, authStatus: 'initializing' as AuthStatus, authError: null as unknown }),\n withMethods(store => {\n const auth = new MockAuthService(options);\n const subscription = auth.afUser().subscribe(afUser => patchState(store, { afUser, authStatus: afUser ? 'ready' : 'signed-out' }));\n inject(DestroyRef).onDestroy(() => subscription.unsubscribe());\n return {\n loadAuth() {},\n async signInWithGoogle() { await auth.signInWithGoogle(); },\n async loginAnonymously() { await auth.signInAnonymously(); },\n async linkGoogle() { await auth.linkGoogle(); },\n async sendEmailSignInLink(email: string) { await auth.sendEmailSignInLink(email); },\n async sendEmailLinkForCurrentAccount() { await auth.sendEmailLinkForCurrentAccount(); },\n getStoredEmailForEmailLink() { return auth.getStoredEmailForEmailLink(); },\n async completeEmailSignInLink(url: string, email: string) { return auth.completeEmailSignInLink(url, email); },\n async deleteAnonymousAccount() { await auth.logout(); },\n async logout() { await auth.logout(); },\n async whenReady() { return store.afUser(); },\n };\n }),\n );\n}\n","import { Injectable, inject, Provider } from '@angular/core';\nimport { dataTimestampNow } from '@tech4good/platform-data';\nimport { MockDataService } from '@tech4good/platform-data/testing';\nimport { ProfilePersistence, ProfileRecord, ProfileChanges, PROFILE_PERSISTENCE } from '@tech4good/platform-auth/profiles';\n\n/** Same profile decisions as Firestore, with serialized mock read/decide/write operations. */\n@Injectable({ providedIn: 'root' })\nexport class MockProfilePersistence implements ProfilePersistence {\n private readonly db = inject(MockDataService);\n private pending: Promise<unknown> = Promise.resolve();\n ensure(collection: string, privateCollection: string | null, uid: string,\n decide: (profile: ProfileRecord | null, privateProfile: ProfileRecord | null) => ProfileChanges,\n ): Promise<ProfileRecord> {\n const operation = this.pending.then(async () => {\n const existing = await this.db.getEntity<ProfileRecord>(collection, uid);\n const existingPrivate = privateCollection ? await this.db.getEntity<ProfileRecord>(privateCollection, uid) : null;\n const changes = decide(existing, existingPrivate);\n const values = (fields: Record<string, unknown>, exists: boolean) => {\n const { __id, _createdAt, _updatedAt, _deleted, ...domain } = fields;\n const now = dataTimestampNow();\n return { ...domain, __id: uid, _updatedAt: now,\n ...(!exists ? { _createdAt: now, _deleted: false } : {}) };\n };\n const operations: { kind: 'set' | 'update'; path: string; value: unknown }[] = [];\n if (changes.profile) operations.push({ kind: existing ? 'update' : 'set', path: `${collection}/${uid}`, value: values(changes.profile, !!existing) });\n if (privateCollection && changes.privateProfile) operations.push({ kind: existingPrivate ? 'update' : 'set', path: `${privateCollection}/${uid}`, value: values(changes.privateProfile, !!existingPrivate) });\n // MockDataService validates the complete batch before changing any collection.\n if (operations.length) await this.db.commitOperations(operations);\n const profile = await this.db.getEntity<ProfileRecord>(collection, uid);\n if (!profile) throw new Error('The newly created user profile could not be read.');\n return profile;\n });\n this.pending = operation.catch(() => {}); // A failed request must not poison later retries.\n return operation;\n }\n}\nexport function provideMockProfiles(): Provider[] {\n return [{ provide: PROFILE_PERSISTENCE, useExisting: MockProfilePersistence }];\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;;;MAea,iBAAiB,GAAG,IAAI,cAAc,CAAkB,iBAAiB,EAAE;IACtF,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AACxC,CAAA;AAED;AACM,SAAU,qBAAqB,CAAC,SAAA,GAAkC,EAAE,EAAA;IACxE,OAAO;AACL,QAAA,GAAG,EAAE,WAAW,EAAE,KAAK,EAAE,sBAAsB,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,IAAI;AACvF,QAAA,WAAW,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,YAAY,CAAC,EAAE,GAAG,SAAS;KAC5G;AACH;AAEA;MAEa,eAAe,CAAA;AAClB,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC3B,IAAA,OAAO,GAAG,MAAM,CAAC,uBAAuB,CAAC;AACzC,IAAA,OAAO;AACP,IAAA,QAAQ;;IAEP,QAAQ,GAA+C,EAAE;AAElE,IAAA,WAAA,CAAuC,OAAA,GAA2B,MAAM,CAAC,iBAAiB,CAAC,EAAA;AACzF,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;AACtB,QAAA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