@tech4good/platform-auth 0.0.0-stage → 0.1.0-alpha.1
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,159 @@
|
|
|
1
|
+
# Auth extraction: what changed
|
|
2
|
+
|
|
3
|
+
Baseline: commit `17ffa3b`, immediately before this auth extraction, in the
|
|
4
|
+
`src/ng-add/files/src/app` templates. This records changes beyond moving code so
|
|
5
|
+
future debugging can distinguish packaging from behavior changes. The data
|
|
6
|
+
package's own changes are documented separately in its EXTRACTION-CHANGES.md.
|
|
7
|
+
|
|
8
|
+
## 1. Operations moved behind an auth-only interface
|
|
9
|
+
|
|
10
|
+
The original `FirebaseService` and `FirebaseMockService` combined auth, data,
|
|
11
|
+
profile policy and guest deletion. Their auth operations now implement
|
|
12
|
+
`AuthAccess`; data operations remain in platform-data. The app supplies profile
|
|
13
|
+
configuration and its guest-deletion callable. No compatibility facade remains.
|
|
14
|
+
|
|
15
|
+
The Firebase session mapper, Google/anonymous sign-in, Google linking,
|
|
16
|
+
email-link flow selection, original-session validation, token refresh and
|
|
17
|
+
sign-out preserve their original order and detailed comments. Email context
|
|
18
|
+
retains the same default localStorage/cookie keys and 30-minute cookie fallback.
|
|
19
|
+
The adapter uses Firebase's own `onIdTokenChanged` observer instead of
|
|
20
|
+
AngularFire's `user` wrapper; the app passes its existing Auth instance.
|
|
21
|
+
|
|
22
|
+
Example caller change (imports only; the underlying operation is unchanged):
|
|
23
|
+
|
|
24
|
+
```diff
|
|
25
|
+
- import { DATABASE_SERVICE } from '../firebase/database.service';
|
|
26
|
+
- private db = inject(DATABASE_SERVICE);
|
|
27
|
+
+ import { AUTH_ACCESS } from '@tech4good/platform-auth';
|
|
28
|
+
+ private db = inject(AUTH_ACCESS);
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
A data-only caller instead imports `DATA_ACCESS` from platform-data.
|
|
32
|
+
|
|
33
|
+
## 2. One configurable profile policy, with atomic persistence
|
|
34
|
+
|
|
35
|
+
Previously the real and mock services each implemented profile defaults and
|
|
36
|
+
reconciliation. `UserProfileService` now makes those decisions once. The real
|
|
37
|
+
and mock persistence adapters receive the same proposed changes.
|
|
38
|
+
|
|
39
|
+
The default profile fields and generated-name/photo rules are preserved.
|
|
40
|
+
The app explicitly supplies `accessState`; Mentor or another app can supply its
|
|
41
|
+
own fields and fallback names. Existing roles, consent and edited names are not
|
|
42
|
+
reset by the new-profile factory. Metadata and path UID are adapter-owned.
|
|
43
|
+
|
|
44
|
+
The original implementation read documents and later wrote them separately.
|
|
45
|
+
Two browser tabs could both decide a profile was missing and write defaults.
|
|
46
|
+
The Firebase adapter now reads, decides and writes in a transaction. If another
|
|
47
|
+
writer changes a read document, Firestore retries the decision against the newer
|
|
48
|
+
data. The mock serializes its profile operations and commits both documents as
|
|
49
|
+
one validated batch.
|
|
50
|
+
|
|
51
|
+
For example, if the private write is denied, the old sequence could leave a
|
|
52
|
+
public profile without its private record. The new transaction writes neither.
|
|
53
|
+
This is a behavior change: profile provisioning now needs all configured reads
|
|
54
|
+
and writes to succeed together, and Firestore transactions need connectivity.
|
|
55
|
+
Factories/reconciliation callbacks must have no side effects because retries can
|
|
56
|
+
invoke them more than once.
|
|
57
|
+
|
|
58
|
+
The old mock also set `_deleted: false` on existing private profiles during email
|
|
59
|
+
synchronization. The real implementation did not. The mock now preserves the
|
|
60
|
+
existing deletion flag, matching the real adapter. This does not define a new
|
|
61
|
+
account-recovery or soft-deleted-profile policy; see FUTURE-WORK.md.
|
|
62
|
+
|
|
63
|
+
## 3. Profile readiness and errors are explicit
|
|
64
|
+
|
|
65
|
+
The old AuthStore reported a failed restored-profile load to the console and
|
|
66
|
+
returned `EMPTY`. `AuthService.resolveUser()` waited for a non-null profile;
|
|
67
|
+
that wait could remain unresolved after the failure.
|
|
68
|
+
|
|
69
|
+
The shared feature retains `afUser` after authentication and exposes a separate
|
|
70
|
+
status. A profile failure produces `authStatus: 'error'` and `authError`.
|
|
71
|
+
`whenReady()` rejects with that error, and `retryProfile()` retries the same
|
|
72
|
+
identity. If the SDK reports a new identity and then its token-refresh step
|
|
73
|
+
fails, that observed identity is also retained as retryable without starting
|
|
74
|
+
profile work prematurely. The app's full-profile guard service uses that result.
|
|
75
|
+
|
|
76
|
+
Example: Firebase sign-in succeeds, but the `users/{uid}` read is denied. The UI
|
|
77
|
+
can still identify the signed-in account, while the application user selector
|
|
78
|
+
returns null and navigation fails instead of treating the profile as ready.
|
|
79
|
+
The caller can fix/retry the load without creating another account.
|
|
80
|
+
|
|
81
|
+
The generated selector includes this additional condition:
|
|
82
|
+
|
|
83
|
+
```diff
|
|
84
|
+
const afUser = store.afUser();
|
|
85
|
+
- if (!afUser) return null;
|
|
86
|
+
+ if (!afUser || store.authStatus() !== 'ready') return null;
|
|
87
|
+
return userStore.selectEntity(afUser.uid) || null;
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
This exposes a distinction that used to be implicit. Apps should provide a
|
|
91
|
+
visible error/retry experience; the package does not add an error screen.
|
|
92
|
+
|
|
93
|
+
## 4. Session cleanup still uses the app's explicit store list
|
|
94
|
+
|
|
95
|
+
The order of explicit logout remains: wait for tracked profile work, stop all
|
|
96
|
+
data streams, clear selected auth state, then sign out. Guest deletion adds the
|
|
97
|
+
app's callable before browser sign-out. Dialogs and navigation remain local.
|
|
98
|
+
|
|
99
|
+
The original reset list is retained in `core/auth/auth.providers.ts`: UserStore,
|
|
100
|
+
UserContextStore and the telemetry session ID. Domain stores and their query/
|
|
101
|
+
entity load histories stay intact. Ordinary pending data loads are not cancelled.
|
|
102
|
+
|
|
103
|
+
Added protections are limited to auth coordination:
|
|
104
|
+
|
|
105
|
+
- Observed external sign-out and UID changes now invoke that same cleanup hook.
|
|
106
|
+
- If profile A is pending when identity B arrives, A's late completion cannot
|
|
107
|
+
load/start a new auth stream or publish A as ready. A profile load already in
|
|
108
|
+
progress can still finish its data work; the generation check prevents the
|
|
109
|
+
subsequent auth stream/state publication.
|
|
110
|
+
- Explicit Google linking uses the same observer suppression as other explicit
|
|
111
|
+
login methods, avoiding duplicate profile work from its SDK notification.
|
|
112
|
+
- Explicit logout waits for a pending direct login as well as refresh provisioning.
|
|
113
|
+
- Repeated sign-out calls await the same teardown promise.
|
|
114
|
+
- Destroying the injector invalidates pending auth completions.
|
|
115
|
+
|
|
116
|
+
The generation counter belongs to auth. It does not add a global data-session
|
|
117
|
+
epoch, per-store ownership system, or reset-all mechanism.
|
|
118
|
+
|
|
119
|
+
## 5. Mock auth now models linking and email context
|
|
120
|
+
|
|
121
|
+
Previously `AuthMockDB.linkGoogle()` created the default mock user, changing a
|
|
122
|
+
guest's UID. Its email methods were mostly no-ops. `MockAuthService` retains the
|
|
123
|
+
current UID for Google/email linking and validates the stored original UID for
|
|
124
|
+
email upgrades. Signing in normally still selects the configured persona.
|
|
125
|
+
|
|
126
|
+
Example: a guest with UID `guest-anon-id` links the Google fixture `mock-user`.
|
|
127
|
+
The resulting identity stays `guest-anon-id`; its provider metadata changes.
|
|
128
|
+
This makes mock development reveal code that accidentally loses guest ownership.
|
|
129
|
+
|
|
130
|
+
Browser persistence is opt-in and read when the mock is instantiated, rather
|
|
131
|
+
than at module import. Malformed/unavailable storage falls back to memory.
|
|
132
|
+
App fixture stores now compose the package's lightweight mock feature; they
|
|
133
|
+
still choose the app's seeded user and user selector. That UI test double
|
|
134
|
+
intentionally skips profile provisioning, as the original fixture did.
|
|
135
|
+
|
|
136
|
+
## 6. Configurable email context and logging
|
|
137
|
+
|
|
138
|
+
The callback URL, storage prefix and fallback-cookie lifetime are configurable;
|
|
139
|
+
defaults retain the previous behavior. Malformed percent-encoded cookies are
|
|
140
|
+
ignored rather than throwing from `decodeURIComponent`. LocalStorage still has
|
|
141
|
+
no expiry; the configured lifetime applies to fallback cookies only.
|
|
142
|
+
|
|
143
|
+
Shared auth failures use `injectLogger('auth')` from platform-logging. App-owned
|
|
144
|
+
logout UI keeps its existing error handling. Auth does not declare a second
|
|
145
|
+
logger abstraction.
|
|
146
|
+
|
|
147
|
+
## Validation locations
|
|
148
|
+
|
|
149
|
+
- `packages/auth/test/auth.test.mjs`: readiness/retry, deferred operations, UID
|
|
150
|
+
changes, teardown ordering, shared profile policy, mock parity and email context.
|
|
151
|
+
- `packages/auth/test/firebase.test.mjs`: mapping and local Firebase SDK observer.
|
|
152
|
+
- `packages/auth/test/firebase.integration.mjs`: real anonymous/email SDK flows,
|
|
153
|
+
concurrent profile transactions, private-write denial and original-session checks.
|
|
154
|
+
- Generated `core/store/auth/auth.store.spec.ts`: the app's selected-store reset
|
|
155
|
+
policy and retained domain records/history.
|
|
156
|
+
- Generated `core/auth/auth.providers.spec.ts`: the app's profile defaults.
|
|
157
|
+
|
|
158
|
+
Tests exercise the built public package API. Emulator fixture rules are separate
|
|
159
|
+
from the app's production rules; run the app's own rules tests when adopting.
|
package/FUTURE-WORK.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Auth follow-up context
|
|
2
|
+
|
|
3
|
+
This file records deliberate limits and adoption checks. It does not authorize
|
|
4
|
+
implementing every item during the first extraction. Read EXTRACTION-CHANGES.md
|
|
5
|
+
before changing behavior: the user wants extraction diffs to remain comparable
|
|
6
|
+
to the original code, with later refactors in separate commits.
|
|
7
|
+
|
|
8
|
+
## Adoption in MathPets and Mentor
|
|
9
|
+
|
|
10
|
+
The package and schematic composition are implemented. Actual MathPets and
|
|
11
|
+
Mentor auth adoption is a separate step. Use MIGRATION.md and install a local
|
|
12
|
+
tarball or alpha before changing their dependencies.
|
|
13
|
+
|
|
14
|
+
Mentor's role-entry flows need explicit review: new-user defaults can be
|
|
15
|
+
configured, but existing-user mentor/faculty promotions and session navigation
|
|
16
|
+
must remain in the app. Do not make the common profile factory grant roles.
|
|
17
|
+
Review the original comparison in the repository's
|
|
18
|
+
`docs-plans/platform-auth-and-onboarding-extraction.md`.
|
|
19
|
+
|
|
20
|
+
## Things to watch
|
|
21
|
+
|
|
22
|
+
| Situation | Current behavior / next check |
|
|
23
|
+
| --- | --- |
|
|
24
|
+
| Retained domain data after logout or A → B | All listeners stop, but only app-selected auth stores reset. Check actual screens and selectors for account/workspace predicates. Do not reintroduce reset-all without a concrete failing scenario and an app policy decision. |
|
|
25
|
+
| Ordinary data operation finishes after logout | It may update cached records/history. Only pending auth continuation is invalidated. Follow the data package's retained-cache checks. |
|
|
26
|
+
| Profile operation never settles | Explicit logout waits for tracked auth work, matching the prior ordering. There is no timeout/cancellation policy. A stalled backend can delay logout; decide deliberately how to cancel or bound this if it occurs. |
|
|
27
|
+
| Profile failure after successful auth | Identity stays available; whenReady rejects and retryProfile retries. The app owns a visible error/retry view. Guard rejection avoids a hang but is not itself a complete recovery screen. |
|
|
28
|
+
| Offline restored session | Firestore transactions require connectivity. This is stricter than separate cached reads. Decide whether an app needs an explicit offline-ready policy; do not silently mark an unverified/missing profile ready. |
|
|
29
|
+
| Already soft-deleted public/private profile | Existing records are not automatically undeleted. The loader can remove a deleted public record from the store even though the auth identity exists. Define account recovery/deletion policy before changing this behavior. |
|
|
30
|
+
| Profile stream fails later | Readiness covers initial assurance/loading and stream setup. Asynchronous data stream errors still use the data package's reporting; they do not automatically transition auth to error. Decide whether an app needs to surface them in auth UI. |
|
|
31
|
+
| Token-refresh notifications for the same UID | The observer can reconcile/reload the same profile. Check UI transitions and unnecessary work in a real browser before introducing caching/deduplication. |
|
|
32
|
+
| Auth changes while an explicit SDK popup is unresolved | Notifications are suppressed until the SDK operation resolves, as in the original flow. External changes during subsequent profile loading are handled. Test unusual cross-tab/popup timing before adding more state machinery. |
|
|
33
|
+
| Existing-user email-link fallback | The original Firebase catch path returns an active user whose email matches when email sign-in fails. Retained for extraction parity; evaluate which SDK errors should permit that fallback in a focused follow-up. |
|
|
34
|
+
| Deleted guest on server, browser sign-out fails | Retry can encounter an already-deleted account. Keep callable idempotency/retry behavior app-owned and test the full backend flow. |
|
|
35
|
+
| Email context | Cookies expire; localStorage does not. Context can be overwritten by another request/tab. Preserve the original-session check and test actual Safari/private-browser/cross-device flows. |
|
|
36
|
+
|
|
37
|
+
## Browser and Firebase checks
|
|
38
|
+
|
|
39
|
+
Local tests cover real anonymous/email credentials and Firestore transactions.
|
|
40
|
+
They do not automate a live Google OAuth popup, a real email client, Safari
|
|
41
|
+
storage restrictions, Firebase Console provider configuration, or deployed
|
|
42
|
+
Cloud Functions. Validate those flows in a development Firebase project when
|
|
43
|
+
adopting. Token refresh is retained before profile work, but test immediate
|
|
44
|
+
post-login Firestore permissions with the app's actual rules and environment.
|
|
45
|
+
|
|
46
|
+
Rules remain authoritative. The profile factory's non-admin default is not an
|
|
47
|
+
authorization boundary; rules must prevent a client from granting itself roles.
|
|
48
|
+
The package test fixture permits controlled profile changes to test preservation
|
|
49
|
+
and must never replace an app's production rules.
|
|
50
|
+
|
|
51
|
+
## Onboarding and consent package
|
|
52
|
+
|
|
53
|
+
A later `@tech4good/platform-onboarding` can share a standalone consent component
|
|
54
|
+
and validation/saving behavior. Keep study text, optional template slots, labels,
|
|
55
|
+
app-owned submission callbacks and navigation configurable. Avoid bundling the
|
|
56
|
+
app's access-state transition into the component: Mentor and MathPets currently
|
|
57
|
+
advance that state differently. Guards and flow ordering should remain local.
|
|
58
|
+
|
|
59
|
+
This is separate from auth and can depend on small public contracts rather than
|
|
60
|
+
specific app stores. Start from the existing consent UI and preserve comments/
|
|
61
|
+
behavior, then make design changes in later commits.
|
|
62
|
+
|
|
63
|
+
## Other backends and repository maintenance
|
|
64
|
+
|
|
65
|
+
Auth core uses a normalized identity and app hooks, not Firebase types. Another
|
|
66
|
+
backend would implement AuthAccess and, if using shared profile policy,
|
|
67
|
+
ProfilePersistence's atomic read/decide/write operation. Backend data adaptation
|
|
68
|
+
is a separate project; see platform-data's backend-adapter document.
|
|
69
|
+
|
|
70
|
+
Keep core free of Firebase/Material/router imports. Keep data independent of
|
|
71
|
+
auth. Avoid adding speculative providers or generic workflow engines before a
|
|
72
|
+
real app needs them. Consider moving schematics into its own workspace only
|
|
73
|
+
when maintaining the current repository layout becomes a concrete problem.
|
package/MIGRATION.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# Adopting platform-auth
|
|
2
|
+
|
|
3
|
+
This is a deliberate migration, not an instruction to rerun `ng-add` over an
|
|
4
|
+
existing application. Preserve each app's guards, role choices, profile fields,
|
|
5
|
+
consent flow and account-deletion graph. MathPets and Mentor have not been
|
|
6
|
+
migrated by the package extraction in this repository.
|
|
7
|
+
|
|
8
|
+
## 1. Install the package and split the contracts
|
|
9
|
+
|
|
10
|
+
Install `@tech4good/platform-auth` and its matching platform peers, or install
|
|
11
|
+
local tarballs while developing. Replace combined database-facade imports:
|
|
12
|
+
|
|
13
|
+
| Previous use | Direct import |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `AuthSession`, auth SDK operations | `AuthSession`, `AuthAccess`, `AUTH_ACCESS` from `@tech4good/platform-auth` |
|
|
16
|
+
| CRUD, aggregation, query loading | `DataAccess`, `DATA_ACCESS` from `@tech4good/platform-data` |
|
|
17
|
+
| Profile creation/reconciliation | `PROFILE_PROVISIONER` from auth, configured with `/profiles` |
|
|
18
|
+
| Firebase SDK auth implementation | `FirebaseAuthService`, `provideFirebaseAuth` from `/firebase` |
|
|
19
|
+
| Email-link local/cookie context | `EmailLinkContextService` from auth |
|
|
20
|
+
| Mock auth | `MockAuthService`, `provideMockAuth` from `/testing` |
|
|
21
|
+
|
|
22
|
+
Delete local compatibility aliases after updating callers. There is no
|
|
23
|
+
`DATABASE_SERVICE` alias in the new package. A service such as TimeAnalytics that
|
|
24
|
+
only watches auth should inject `AUTH_ACCESS`, not the data adapter.
|
|
25
|
+
|
|
26
|
+
## 2. Configure real and mock providers
|
|
27
|
+
|
|
28
|
+
Pass the app's existing Firebase Auth instance to `PLATFORM_FIREBASE_AUTH` and
|
|
29
|
+
Firestore instance to data's `PLATFORM_FIRESTORE`. Compose `provideFirebaseAuth`,
|
|
30
|
+
`provideFirestoreProfiles`, `provideUserProfiles` and `AUTH_LIFECYCLE`. Use data's
|
|
31
|
+
Firestore service and batch writer directly.
|
|
32
|
+
|
|
33
|
+
For development, replace the implementations together using `provideMockAuth`,
|
|
34
|
+
`provideMockProfiles` and `provideMockData`. Keep entity seeds and personas in the
|
|
35
|
+
app. The generated `core/testing/app-mocks.ts` shows how to use a generated mock
|
|
36
|
+
registry and typed seed overrides without a local FirebaseMockService subclass.
|
|
37
|
+
Production must exclude that fixture module; the generated provider-file
|
|
38
|
+
replacement retains this behavior.
|
|
39
|
+
|
|
40
|
+
## 3. Move profile policy into configuration
|
|
41
|
+
|
|
42
|
+
Copy each app's new-profile defaults into `createProfile`. Start from
|
|
43
|
+
`defaultLabProfile(session)` for non-admin, unconsented defaults, then add access
|
|
44
|
+
state and domain fields. Existing data is not migrated or rewritten by installing
|
|
45
|
+
the package.
|
|
46
|
+
|
|
47
|
+
Mentor can use `defaultLabProfile(session, 'User')`, add `isMentor: false`, and set
|
|
48
|
+
`generatedNames: ['Guest', 'User']`. Keep deliberate mentor/faculty promotion in
|
|
49
|
+
its role-entry operation. Do not make ordinary sign-in grant those roles.
|
|
50
|
+
If the app intentionally synchronizes different existing-profile fields, supply
|
|
51
|
+
`reconcileProfile`. It runs inside the transaction and must be pure.
|
|
52
|
+
|
|
53
|
+
Public/private profile writes are now atomic. Check both collections' actual
|
|
54
|
+
Firestore permissions together: an error in either prevents the transaction.
|
|
55
|
+
Transactions require a connection, so test offline/restored-session behavior.
|
|
56
|
+
|
|
57
|
+
## 4. Compose the AuthStore
|
|
58
|
+
|
|
59
|
+
Use `withAuthSession()` inside the app's root signalStore, then retain its local
|
|
60
|
+
user selector and UI methods. The generated store uses `authStatus() === 'ready'`
|
|
61
|
+
before exposing a loaded profile. Keep `loadAuth()` at startup.
|
|
62
|
+
|
|
63
|
+
Connect the UserStore in `AUTH_LIFECYCLE`: ensure-profile is handled by the package;
|
|
64
|
+
the app hook loads and streams that UID's profile. Keep the explicit cleanup
|
|
65
|
+
list: teardown all listeners first, reset chosen auth stores and their histories,
|
|
66
|
+
then clear any app session identifier. Do not introduce reset-all.
|
|
67
|
+
|
|
68
|
+
Shared `signOut()` performs auth cleanup without navigation. Shared
|
|
69
|
+
`deleteGuestAccount()` additionally invokes the supplied app deletion operation.
|
|
70
|
+
The local `logout()` can retain its guest-confirmation dialog, save-account
|
|
71
|
+
choice and destination; local `deleteAnonymousAccount()` can retain its route.
|
|
72
|
+
|
|
73
|
+
The backend callable, deletion graph, guards and role-based navigation stay in
|
|
74
|
+
the app. The package does not deploy or generate an account-deletion backend.
|
|
75
|
+
|
|
76
|
+
## 5. Handle readiness and validate
|
|
77
|
+
|
|
78
|
+
Use `whenReady()` when a guard needs the profile. It resolves a session or null
|
|
79
|
+
and rejects on a profile/auth error. `afUser()` alone only means identity exists.
|
|
80
|
+
Use `authError()` and `retryProfile()` in the app's error/retry experience.
|
|
81
|
+
|
|
82
|
+
Validate fresh Google/guest/email sign-in, refresh, guest linking, edited profile
|
|
83
|
+
preservation, errors/retry, explicit/external sign-out and direct account changes.
|
|
84
|
+
Keep app logout tests that verify retained domain records and load history. Run
|
|
85
|
+
lint, production build, app tests and rules tests with the installed tarball.
|
|
86
|
+
|
|
87
|
+
Lightweight component fixtures can compose `withMockAuthSession()` with an
|
|
88
|
+
app-specific user selector. Those fixtures skip provisioning; they are not a
|
|
89
|
+
replacement for integration tests using the real AuthStore and mock adapters.
|
package/README.md
CHANGED
|
@@ -1,3 +1,214 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tech4good/platform-auth
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shared authentication and user-profile provisioning for Angular 21 applications.
|
|
4
|
+
The initial version is `0.1.0-alpha.0`. Building or packing this repository does
|
|
5
|
+
not publish that version.
|
|
6
|
+
|
|
7
|
+
This package contains the auth operations previously copied into each lab app:
|
|
8
|
+
Google and anonymous sign-in, Google/email linking, email-link context, restored
|
|
9
|
+
sessions, profile creation and session cleanup coordination. The app still owns
|
|
10
|
+
its screens, guards, routes, profile fields, roles and account-deletion backend.
|
|
11
|
+
|
|
12
|
+
## Entry points
|
|
13
|
+
|
|
14
|
+
These are entry points of **one npm package**, installed and versioned together.
|
|
15
|
+
|
|
16
|
+
| Import | Contents |
|
|
17
|
+
| --- | --- |
|
|
18
|
+
| `@tech4good/platform-auth` | `AuthSession`, `AUTH_ACCESS`, `withAuthSession`, lifecycle/profile contracts, email context and configuration. No Firebase, data, router or Material imports. |
|
|
19
|
+
| `@tech4good/platform-auth/profiles` | `provideUserProfiles`, default lab profile fields and configurable profile reconciliation. Uses shared data types. |
|
|
20
|
+
| `@tech4good/platform-auth/firebase` | Firebase Auth adapter and atomic Firestore profile persistence. |
|
|
21
|
+
| `@tech4good/platform-auth/testing` | Mock auth, mock profile persistence and a lightweight UI-test store feature. No Firebase imports. |
|
|
22
|
+
|
|
23
|
+
`platform-data` does not depend on auth. Auth core communicates with application
|
|
24
|
+
stores through `AUTH_LIFECYCLE`, without importing their classes. Firebase is an
|
|
25
|
+
optional peer because only the `/firebase` entry point requires it; normal lab
|
|
26
|
+
apps use it. Data and logging are package peers installed alongside auth.
|
|
27
|
+
|
|
28
|
+
## App composition
|
|
29
|
+
|
|
30
|
+
Install matching platform alpha versions and the Angular/NgRx/RxJS peers required
|
|
31
|
+
by the manifests. Import services directly from the packages; there is no local
|
|
32
|
+
`DATABASE_SERVICE` alias or combined Firebase facade.
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { getAuth } from 'firebase/auth';
|
|
36
|
+
import { getFirestore } from 'firebase/firestore';
|
|
37
|
+
import { providePlatformAuth } from '@tech4good/platform-auth';
|
|
38
|
+
import {
|
|
39
|
+
PLATFORM_FIREBASE_AUTH, provideFirebaseAuth, provideFirestoreProfiles,
|
|
40
|
+
} from '@tech4good/platform-auth/firebase';
|
|
41
|
+
import { provideFirestoreData } from '@tech4good/platform-data/firestore';
|
|
42
|
+
|
|
43
|
+
// The app initializes its Firebase app, emulator connections and persistence.
|
|
44
|
+
const providers = [
|
|
45
|
+
providePlatformAuth({ emailActionUrl: '/auth/action' }),
|
|
46
|
+
{ provide: PLATFORM_FIREBASE_AUTH, useFactory: () => getAuth() },
|
|
47
|
+
...provideFirebaseAuth(),
|
|
48
|
+
provideFirestoreData(() => getFirestore()),
|
|
49
|
+
...provideFirestoreProfiles(),
|
|
50
|
+
// Add app profile defaults and AUTH_LIFECYCLE, as described below.
|
|
51
|
+
];
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
If the app initializes Firebase through AngularFire, pass the existing `Auth`
|
|
55
|
+
and `Firestore` instances into the platform tokens. Do not initialize a second
|
|
56
|
+
Firebase app just for this package. Generated `app.config.ts` demonstrates this.
|
|
57
|
+
|
|
58
|
+
### Profile defaults
|
|
59
|
+
|
|
60
|
+
Every authenticated session, including anonymous users and restored sessions,
|
|
61
|
+
passes through profile assurance before becoming ready.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { defaultLabProfile, provideUserProfiles } from '@tech4good/platform-auth/profiles';
|
|
65
|
+
|
|
66
|
+
provideUserProfiles<User>({
|
|
67
|
+
createProfile: session => ({
|
|
68
|
+
...defaultLabProfile(session),
|
|
69
|
+
accessState: AccessState.SUBMIT_INTEREST,
|
|
70
|
+
// An app can add fields such as isMentor: false here.
|
|
71
|
+
}),
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The factory runs only when the public profile is absent. It must be pure because
|
|
76
|
+
Firestore may retry a transaction. The adapter supplies `__id`, `_createdAt`,
|
|
77
|
+
`_updatedAt` and `_deleted`; factories cannot override them.
|
|
78
|
+
|
|
79
|
+
By default, an existing profile keeps its roles, consent, access state, edited
|
|
80
|
+
name and unrelated fields. A generated name (`Guest`, `Learner`, the current
|
|
81
|
+
email, or an empty name) can be replaced by a provider display name; a changed
|
|
82
|
+
provider photo is synchronized. Override `generatedNames` or `reconcileProfile`
|
|
83
|
+
when an app needs a different policy. Intentional role promotions belong in an
|
|
84
|
+
explicit app action, not a factory that runs on every sign-in.
|
|
85
|
+
|
|
86
|
+
Defaults use `users/{uid}` and `userPrivates/{uid}`. `profileCollection` and
|
|
87
|
+
`privateCollection` change these names; `privateCollection: null` disables the
|
|
88
|
+
private record. Email/private-provider metadata is synchronized only when auth
|
|
89
|
+
supplies an email. A missing email does not erase an existing record.
|
|
90
|
+
|
|
91
|
+
### Connect the app's stores
|
|
92
|
+
|
|
93
|
+
Provide `AUTH_LIFECYCLE` with four operations:
|
|
94
|
+
|
|
95
|
+
- `loadProfile(session)`: load the current profile into the app's UserStore.
|
|
96
|
+
- `streamProfile(session)`: start its profile stream.
|
|
97
|
+
- `clearSessionState()`: stop all data listeners, reset the explicitly chosen
|
|
98
|
+
auth stores and their load history, and clear app session/analytics state.
|
|
99
|
+
- `deleteAnonymousAccount()`: invoke the app's guest-deletion backend.
|
|
100
|
+
|
|
101
|
+
Create this provider with a factory so its store dependencies are injected once.
|
|
102
|
+
The generated `core/auth/auth.providers.ts` is the complete example. It resets
|
|
103
|
+
`UserStore` and `UserContextStore`; it retains domain records and load history.
|
|
104
|
+
There is no automatic reset-all policy or entity-store registry in auth.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
export const AuthStore = signalStore(
|
|
108
|
+
{ providedIn: 'root' },
|
|
109
|
+
withAuthSession(),
|
|
110
|
+
// Add this app's user selector and logout/navigation methods here.
|
|
111
|
+
);
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Call `loadAuth()` once at application startup. The feature provides:
|
|
115
|
+
|
|
116
|
+
| API | Purpose |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| `afUser()`, `authStatus()`, `authError()` | Identity and explicit profile readiness/error state. |
|
|
119
|
+
| `isLoadingLogin()` | Busy indicator for explicit login/email operations. |
|
|
120
|
+
| `signInWithGoogle()`, `loginAnonymously()` | Authenticate, ensure profile, load and stream it. |
|
|
121
|
+
| `linkGoogle()`, `completeEmailSignInLink(url, email)` | Link/complete auth, then reconcile and load the profile. |
|
|
122
|
+
| `sendEmailSignInLink(email)`, `sendEmailLinkForCurrentAccount()`, `getStoredEmailForEmailLink()` | Email-link request and callback context. |
|
|
123
|
+
| `whenReady()` | Resolve the session or signed-out `null`; reject on a profile/auth failure. |
|
|
124
|
+
| `retryProfile()` | Retry profile assurance/loading for the existing identity. |
|
|
125
|
+
| `signOut()`, `deleteGuestAccount()` | Wait for tracked auth work, clear selected state, end the account/session. No dialog or navigation. |
|
|
126
|
+
|
|
127
|
+
`authStatus` is `initializing`, `signed-out`, `loading-profile`, `ready` or
|
|
128
|
+
`error`. Identity and profile readiness are different: a failed profile request
|
|
129
|
+
retains `afUser`, exposes the error, and can be retried without another sign-in.
|
|
130
|
+
Generated profile guards use `whenReady()` and the local ready-user selector.
|
|
131
|
+
|
|
132
|
+
The local AuthStore wraps `signOut()` and `deleteGuestAccount()` with its existing
|
|
133
|
+
logout dialog and routes. An external sign-out or UID change also runs the app's
|
|
134
|
+
cleanup hook. Pending auth work cannot reopen the previous user's profile
|
|
135
|
+
stream. Ordinary data loads may still finish; the data cache policy is unchanged.
|
|
136
|
+
|
|
137
|
+
### Mock development and testing
|
|
138
|
+
|
|
139
|
+
Compose `provideMockAuth`, `provideMockProfiles` and `provideMockData`, plus the
|
|
140
|
+
same app profile defaults and lifecycle provider. Pass app-owned test identities
|
|
141
|
+
to `provideMockAuth({ initialSession, googleSession })`. `MockAuthService` exposes
|
|
142
|
+
`setSession()` for external auth transitions and `failures` for rejected
|
|
143
|
+
operations. Mock Google/email linking retains the current UID.
|
|
144
|
+
|
|
145
|
+
Generated apps use `provideAppMocks()` to combine these providers with the
|
|
146
|
+
generated entity registry and seeds. `withMockAuthSession()` is a lighter UI-test
|
|
147
|
+
double that deliberately skips profiles; use the real `withAuthSession()` for
|
|
148
|
+
provisioning and session-cleanup tests.
|
|
149
|
+
|
|
150
|
+
## Build, test and try locally
|
|
151
|
+
|
|
152
|
+
From the repository root:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
npm ci
|
|
156
|
+
npm run test:auth
|
|
157
|
+
npm run pack:auth
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
`build:auth` builds logging, then data, then auth. Tests use the built public
|
|
161
|
+
entry points, check declaration types and block Firebase imports in core/mock
|
|
162
|
+
tests. Test sources are not shipped as runtime exports.
|
|
163
|
+
|
|
164
|
+
Install the resulting tarball into a disposable consumer or development app:
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
npm install /absolute/path/to/tech4good-platform-auth-0.1.0-alpha.0.tgz
|
|
168
|
+
npm run lint
|
|
169
|
+
npm run build
|
|
170
|
+
npm test
|
|
171
|
+
npm run test:rules
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Also pack/install local data and logging if the required versions are not yet on
|
|
175
|
+
npm or you changed them. Rebuild, repack and reinstall after each package change;
|
|
176
|
+
a tarball is a snapshot. An alpha release is not required for local testing.
|
|
177
|
+
See [migration](MIGRATION.md) before replacing an existing app's auth wiring.
|
|
178
|
+
|
|
179
|
+
### Firebase emulator tests
|
|
180
|
+
|
|
181
|
+
With Firebase CLI and its emulator prerequisites installed, from the repo root:
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
npm run build:auth
|
|
185
|
+
firebase emulators:exec --project demo-platform-auth \
|
|
186
|
+
--config packages/auth/test/emulator/firebase.json \
|
|
187
|
+
'FIREBASE_AUTH_EMULATOR_HOST=127.0.0.1:9099 FIRESTORE_EMULATOR_HOST=127.0.0.1:8088 npm run test:emulator --workspace @tech4good/platform-auth'
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
These exercise real SDK anonymous/email operations and owner-protected profile
|
|
191
|
+
transactions against local demo emulators. The test rules are fixtures, not
|
|
192
|
+
production authorization rules. App rules tests and browser OAuth testing remain
|
|
193
|
+
necessary when adopting the package; see [future work](FUTURE-WORK.md).
|
|
194
|
+
|
|
195
|
+
## Publishing
|
|
196
|
+
|
|
197
|
+
From the repository root, build and test before publishing the **dist directory**:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
npm run test:auth
|
|
201
|
+
npm pack ./packages/auth/dist --dry-run
|
|
202
|
+
npm login
|
|
203
|
+
npm publish ./packages/auth/dist --access public --tag alpha
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Publish required logging/data versions first if they are not available on npm.
|
|
207
|
+
The source workspace intentionally refuses publication, to prevent shipping
|
|
208
|
+
uncompiled TypeScript. The root release scripts version angular-schematics;
|
|
209
|
+
they do not version this package. For a subsequent alpha, update the auth
|
|
210
|
+
workspace version and the generated app dependency, refresh the lockfile, test,
|
|
211
|
+
and publish the newly built dist. Never reuse an already-published version.
|
|
212
|
+
|
|
213
|
+
See [extraction changes](EXTRACTION-CHANGES.md) for behavior differences and
|
|
214
|
+
[future work](FUTURE-WORK.md) for adoption checks and deferred features.
|