@sneat/auth-ui 0.27.9 → 0.27.11

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.
@@ -1,4 +1,5 @@
1
1
  export * from './user-required-fields';
2
2
  export * from './user-auth-providers/user-auth-accounts.component';
3
3
  export * from './auth-menu-item/auth-menu-item.component';
4
+ export * from './phone-verification';
4
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../libs/auth/ui/src/lib/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,oDAAoD,CAAC;AACnE,cAAc,2CAA2C,CAAC","sourcesContent":["export * from './user-required-fields';\nexport * from './user-auth-providers/user-auth-accounts.component';\nexport * from './auth-menu-item/auth-menu-item.component';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../libs/auth/ui/src/lib/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,cAAc,oDAAoD,CAAC;AACnE,cAAc,2CAA2C,CAAC;AAC1D,cAAc,sBAAsB,CAAC","sourcesContent":["export * from './user-required-fields';\nexport * from './user-auth-providers/user-auth-accounts.component';\nexport * from './auth-menu-item/auth-menu-item.component';\nexport * from './phone-verification';\n"]}
@@ -0,0 +1,2 @@
1
+ export * from './phone-verification.component';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/components/phone-verification/index.ts"],"names":[],"mappings":"AAAA,cAAc,gCAAgC,CAAC","sourcesContent":["export * from './phone-verification.component';\n"]}
@@ -0,0 +1,147 @@
1
+ import { ChangeDetectionStrategy, Component, inject, output, signal, viewChild, } from '@angular/core';
2
+ import { FormsModule } from '@angular/forms';
3
+ import { IonButton, IonInput, IonItem, IonNote, IonSpinner, IonText, } from '@ionic/angular';
4
+ import { FirebaseError } from 'firebase/app';
5
+ import { PhoneVerificationService, PhoneVerificationStateError, } from './phone-verification.service';
6
+ import * as i0 from "@angular/core";
7
+ import * as i1 from "@angular/forms";
8
+ export class PhoneVerificationComponent {
9
+ constructor() {
10
+ this.phoneVerification = inject(PhoneVerificationService);
11
+ this.recaptchaContainer = viewChild('recaptchaContainer', /* @ts-ignore */
12
+ ...(ngDevMode ? [{ debugName: "recaptchaContainer" }] : /* istanbul ignore next */ []));
13
+ this.verified = output();
14
+ this.phoneNumber = signal(this.phoneVerification.currentPhoneNumber, /* @ts-ignore */
15
+ ...(ngDevMode ? [{ debugName: "phoneNumber" }] : /* istanbul ignore next */ []));
16
+ this.verificationCode = signal('', /* @ts-ignore */
17
+ ...(ngDevMode ? [{ debugName: "verificationCode" }] : /* istanbul ignore next */ []));
18
+ this.verificationId = signal(undefined, /* @ts-ignore */
19
+ ...(ngDevMode ? [{ debugName: "verificationId" }] : /* istanbul ignore next */ []));
20
+ this.verifiedPhoneNumber = signal(undefined, /* @ts-ignore */
21
+ ...(ngDevMode ? [{ debugName: "verifiedPhoneNumber" }] : /* istanbul ignore next */ []));
22
+ this.pending = signal(undefined, /* @ts-ignore */
23
+ ...(ngDevMode ? [{ debugName: "pending" }] : /* istanbul ignore next */ []));
24
+ this.errorMessage = signal(undefined, /* @ts-ignore */
25
+ ...(ngDevMode ? [{ debugName: "errorMessage" }] : /* istanbul ignore next */ []));
26
+ }
27
+ get isPhoneNumberValid() {
28
+ return /^\+[1-9]\d{7,14}$/.test(this.phoneNumber().trim());
29
+ }
30
+ get isVerificationCodeValid() {
31
+ return /^\d{6}$/.test(this.verificationCode().trim());
32
+ }
33
+ async requestCode() {
34
+ if (this.pending())
35
+ return;
36
+ const phoneNumber = this.phoneNumber().trim();
37
+ this.phoneNumber.set(phoneNumber);
38
+ if (!this.isPhoneNumberValid) {
39
+ this.errorMessage.set('Enter a valid international phone number, including the country code.');
40
+ return;
41
+ }
42
+ const container = this.recaptchaContainer()?.nativeElement;
43
+ if (!container) {
44
+ this.errorMessage.set('Phone verification is temporarily unavailable. Please try again.');
45
+ return;
46
+ }
47
+ this.errorMessage.set(undefined);
48
+ this.pending.set('sending');
49
+ try {
50
+ const verificationId = await this.phoneVerification.requestCode(phoneNumber, container);
51
+ this.verificationId.set(verificationId);
52
+ this.verificationCode.set('');
53
+ }
54
+ catch (error) {
55
+ this.errorMessage.set(this.safeErrorMessage(error));
56
+ }
57
+ finally {
58
+ this.pending.set(undefined);
59
+ }
60
+ }
61
+ async verifyCode() {
62
+ if (this.pending())
63
+ return;
64
+ const verificationId = this.verificationId();
65
+ const code = this.verificationCode().trim();
66
+ this.verificationCode.set(code);
67
+ if (!verificationId) {
68
+ this.errorMessage.set('Request a new verification code.');
69
+ return;
70
+ }
71
+ if (!this.isVerificationCodeValid) {
72
+ this.errorMessage.set('Enter the six-digit code from the SMS.');
73
+ return;
74
+ }
75
+ this.errorMessage.set(undefined);
76
+ this.pending.set('verifying');
77
+ try {
78
+ await this.phoneVerification.verifyCode(verificationId, code);
79
+ this.verifiedPhoneNumber.set(this.phoneNumber());
80
+ this.verificationId.set(undefined);
81
+ this.verificationCode.set('');
82
+ this.verified.emit();
83
+ }
84
+ catch (error) {
85
+ this.errorMessage.set(this.safeErrorMessage(error));
86
+ }
87
+ finally {
88
+ this.pending.set(undefined);
89
+ }
90
+ }
91
+ useAnotherNumber() {
92
+ if (this.pending())
93
+ return;
94
+ this.phoneVerification.reset();
95
+ this.verificationId.set(undefined);
96
+ this.verificationCode.set('');
97
+ this.errorMessage.set(undefined);
98
+ }
99
+ ngOnDestroy() {
100
+ this.phoneVerification.reset();
101
+ }
102
+ safeErrorMessage(error) {
103
+ if (error instanceof PhoneVerificationStateError) {
104
+ return error.code === 'user-changed'
105
+ ? 'Your sign-in changed. Start phone verification again.'
106
+ : 'Sign in with your account before verifying a phone number.';
107
+ }
108
+ if (!(error instanceof FirebaseError)) {
109
+ return 'Phone verification failed. Please try again.';
110
+ }
111
+ switch (error.code) {
112
+ case 'auth/invalid-phone-number':
113
+ case 'auth/missing-phone-number':
114
+ return 'Enter a valid international phone number, including the country code.';
115
+ case 'auth/invalid-verification-code':
116
+ return 'That verification code is not correct. Check the SMS and try again.';
117
+ case 'auth/code-expired':
118
+ case 'auth/session-expired':
119
+ return 'That code has expired. Request a new verification code.';
120
+ case 'auth/credential-already-in-use':
121
+ case 'auth/account-exists-with-different-credential':
122
+ return 'That phone number is already linked to another account.';
123
+ case 'auth/requires-recent-login':
124
+ return 'For security, sign in again before changing your phone number.';
125
+ case 'auth/quota-exceeded':
126
+ case 'auth/too-many-requests':
127
+ return 'Too many verification attempts. Please wait before trying again.';
128
+ default:
129
+ return 'Phone verification failed. Please try again.';
130
+ }
131
+ }
132
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: PhoneVerificationComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
133
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.3", type: PhoneVerificationComponent, isStandalone: true, selector: "sneat-phone-verification", outputs: { verified: "verified" }, providers: [PhoneVerificationService], viewQueries: [{ propertyName: "recaptchaContainer", first: true, predicate: ["recaptchaContainer"], descendants: true, isSignal: true }], ngImport: i0, template: "<section aria-labelledby=\"phone-verification-heading\">\n <h2 id=\"phone-verification-heading\">Verify your phone number</h2>\n\n @if (verifiedPhoneNumber(); as verifiedNumber) {\n <p role=\"status\">\n <strong>{{ verifiedNumber }}</strong> is verified and linked to your\n account.\n </p>\n } @else if (verificationId()) {\n <form (ngSubmit)=\"verifyCode()\" novalidate>\n <p>\n Enter the six-digit code sent to\n <strong>{{ phoneNumber() }}</strong>.\n </p>\n <ion-item>\n <ion-input\n name=\"verificationCode\"\n label=\"Verification code\"\n labelPlacement=\"stacked\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n maxlength=\"6\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"verificationCode()\"\n (ngModelChange)=\"verificationCode.set($event)\"\n />\n </ion-item>\n <div class=\"actions\">\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isVerificationCodeValid\"\n >\n @if (pending() === 'verifying') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Verifying\u2026\n } @else {\n Verify phone\n }\n </ion-button>\n <ion-button\n type=\"button\"\n fill=\"clear\"\n [disabled]=\"!!pending()\"\n (click)=\"useAnotherNumber()\"\n >\n Request another code or change number\n </ion-button>\n </div>\n </form>\n } @else {\n <form (ngSubmit)=\"requestCode()\" novalidate>\n <ion-item>\n <ion-input\n name=\"phoneNumber\"\n type=\"tel\"\n inputmode=\"tel\"\n autocomplete=\"tel\"\n label=\"Phone number\"\n labelPlacement=\"stacked\"\n placeholder=\"+353\u2026\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"phoneNumber()\"\n (ngModelChange)=\"phoneNumber.set($event)\"\n />\n </ion-item>\n <ion-note>\n Use the international format beginning with \u201C+\u201D. Google Firebase will\n send an authentication SMS and process your phone number for spam and\n abuse prevention. Standard SMS rates may apply. We will not use this\n verification message for marketing.\n </ion-note>\n <div #recaptchaContainer class=\"recaptcha\" aria-label=\"Security check\"></div>\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isPhoneNumberValid\"\n >\n @if (pending() === 'sending') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Sending code\u2026\n } @else {\n Send verification code\n }\n </ion-button>\n </form>\n }\n\n @if (errorMessage(); as message) {\n <ion-text color=\"danger\">\n <p class=\"error\" role=\"alert\">{{ message }}</p>\n </ion-text>\n }\n</section>\n", styles: [":host{display:block}h2{font-size:1.25rem;margin-top:0}ion-note{display:block;line-height:1.4;margin:.75rem 1rem}.recaptcha{margin:1rem;min-height:78px}.actions{display:flex;flex-wrap:wrap;gap:.5rem}.error{margin:.75rem 1rem}\n"], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i1.NgForm, selector: "form:not([ngNoForm]):not([formGroup]):not([formArray]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: IonButton, selector: "ion-button", inputs: ["buttonType", "color", "disabled", "download", "expand", "fill", "form", "href", "mode", "rel", "routerAnimation", "routerDirection", "shape", "size", "strong", "target", "type"], outputs: ["ionFocus", "ionBlur"] }, { kind: "component", type: IonInput, selector: "ion-input", inputs: ["accept", "autocapitalize", "autocomplete", "autocorrect", "autofocus", "clearInput", "clearOnEdit", "color", "counter", "counterFormatter", "debounce", "disabled", "enterkeyhint", "errorText", "fill", "helperText", "inputmode", "label", "labelPlacement", "max", "maxlength", "min", "minlength", "mode", "multiple", "name", "pattern", "placeholder", "readonly", "required", "shape", "size", "spellcheck", "step", "type", "value"] }, { kind: "component", type: IonItem, selector: "ion-item", inputs: ["button", "color", "detail", "detailIcon", "disabled", "download", "href", "lines", "mode", "rel", "routerAnimation", "routerDirection", "target", "type"] }, { kind: "component", type: IonNote, selector: "ion-note", inputs: ["color", "mode"] }, { kind: "component", type: IonSpinner, selector: "ion-spinner", inputs: ["color", "duration", "name", "paused"] }, { kind: "component", type: IonText, selector: "ion-text", inputs: ["color", "mode"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
134
+ }
135
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: PhoneVerificationComponent, decorators: [{
136
+ type: Component,
137
+ args: [{ selector: 'sneat-phone-verification', changeDetection: ChangeDetectionStrategy.OnPush, imports: [
138
+ FormsModule,
139
+ IonButton,
140
+ IonInput,
141
+ IonItem,
142
+ IonNote,
143
+ IonSpinner,
144
+ IonText,
145
+ ], providers: [PhoneVerificationService], template: "<section aria-labelledby=\"phone-verification-heading\">\n <h2 id=\"phone-verification-heading\">Verify your phone number</h2>\n\n @if (verifiedPhoneNumber(); as verifiedNumber) {\n <p role=\"status\">\n <strong>{{ verifiedNumber }}</strong> is verified and linked to your\n account.\n </p>\n } @else if (verificationId()) {\n <form (ngSubmit)=\"verifyCode()\" novalidate>\n <p>\n Enter the six-digit code sent to\n <strong>{{ phoneNumber() }}</strong>.\n </p>\n <ion-item>\n <ion-input\n name=\"verificationCode\"\n label=\"Verification code\"\n labelPlacement=\"stacked\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n maxlength=\"6\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"verificationCode()\"\n (ngModelChange)=\"verificationCode.set($event)\"\n />\n </ion-item>\n <div class=\"actions\">\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isVerificationCodeValid\"\n >\n @if (pending() === 'verifying') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Verifying\u2026\n } @else {\n Verify phone\n }\n </ion-button>\n <ion-button\n type=\"button\"\n fill=\"clear\"\n [disabled]=\"!!pending()\"\n (click)=\"useAnotherNumber()\"\n >\n Request another code or change number\n </ion-button>\n </div>\n </form>\n } @else {\n <form (ngSubmit)=\"requestCode()\" novalidate>\n <ion-item>\n <ion-input\n name=\"phoneNumber\"\n type=\"tel\"\n inputmode=\"tel\"\n autocomplete=\"tel\"\n label=\"Phone number\"\n labelPlacement=\"stacked\"\n placeholder=\"+353\u2026\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"phoneNumber()\"\n (ngModelChange)=\"phoneNumber.set($event)\"\n />\n </ion-item>\n <ion-note>\n Use the international format beginning with \u201C+\u201D. Google Firebase will\n send an authentication SMS and process your phone number for spam and\n abuse prevention. Standard SMS rates may apply. We will not use this\n verification message for marketing.\n </ion-note>\n <div #recaptchaContainer class=\"recaptcha\" aria-label=\"Security check\"></div>\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isPhoneNumberValid\"\n >\n @if (pending() === 'sending') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Sending code\u2026\n } @else {\n Send verification code\n }\n </ion-button>\n </form>\n }\n\n @if (errorMessage(); as message) {\n <ion-text color=\"danger\">\n <p class=\"error\" role=\"alert\">{{ message }}</p>\n </ion-text>\n }\n</section>\n", styles: [":host{display:block}h2{font-size:1.25rem;margin-top:0}ion-note{display:block;line-height:1.4;margin:.75rem 1rem}.recaptcha{margin:1rem;min-height:78px}.actions{display:flex;flex-wrap:wrap;gap:.5rem}.error{margin:.75rem 1rem}\n"] }]
146
+ }], propDecorators: { recaptchaContainer: [{ type: i0.ViewChild, args: ['recaptchaContainer', { isSignal: true }] }], verified: [{ type: i0.Output, args: ["verified"] }] } });
147
+ //# sourceMappingURL=phone-verification.component.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phone-verification.component.js","sourceRoot":"","sources":["../../../../../../../../libs/auth/ui/src/lib/components/phone-verification/phone-verification.component.ts","../../../../../../../../libs/auth/ui/src/lib/components/phone-verification/phone-verification.component.html"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,SAAS,EAGT,MAAM,EACN,MAAM,EACN,MAAM,EACN,SAAS,GACV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EACL,SAAS,EACT,QAAQ,EACR,OAAO,EACP,OAAO,EACP,UAAU,EACV,OAAO,GACR,MAAM,gBA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C,IAAI,KAAK,YAAY,2BAA2B,EAAE,CAAC;YACjD,OAAO,KAAK,CAAC,IAAI,KAAK,cAAc;gBAClC,CAAC,CAAC,uDAAuD;gBACzD,CAAC,CAAC,4DAA4D,CAAC;QACnE,CAAC;QACD,IAAI,CAAC,CAAC,KAAK,YAAY,aAAa,CAAC,EAAE,CAAC;YACtC,OAAO,8CAA8C,CAAC;QACxD,CAAC;QACD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;YACnB,KAAK,2BAA2B,CAAC;YACjC,KAAK,2BAA2B;gBAC9B,OAAO,uEAAuE,CAAC;YACjF,KAAK,gCAAgC;gBACnC,OAAO,qEAAqE,CAAC;YAC/E,KAAK,mBAAmB,CAAC;YACzB,KAAK,sBAAsB;gBACzB,OAAO,yDAAyD,CAAC;YACnE,KAAK,gCAAgC,CAAC;YACtC,KAAK,+CAA+C;gBAClD,OAAO,yDAAyD,CAAC;YACnE,KAAK,4BAA4B;gBAC/B,OAAO,gEAAgE,CAAC;YAC1E,KAAK,qBAAqB,CAAC;YAC3B,KAAK,wBAAwB;gBAC3B,OAAO,kEAAkE,CAAC;YAC5E;gBACE,OAAO,8CAA8C,CAAC;QAC1D,CAAC;IACH,CAAC;8GAlIU,0BAA0B;kGAA1B,0BAA0B,0GAF1B,CAAC,wBAAwB,CAAC,oKCzCvC,w8FA4FA,2RD3DI,WAAW,w9BACX,SAAS,sRACT,QAAQ,8eACR,OAAO,0NACP,OAAO,gFACP,UAAU,yGACV,OAAO;;2FAIE,0BAA0B;kBAhBtC,SAAS;+BACE,0BAA0B,mBAGnB,uBAAuB,CAAC,MAAM,WACtC;wBACP,WAAW;wBACX,SAAS;wBACT,QAAQ;wBACR,OAAO;wBACP,OAAO;wBACP,UAAU;wBACV,OAAO;qBACR,aACU,CAAC,wBAAwB,CAAC;gFAKG,oBAAoB","sourcesContent":["import {\n ChangeDetectionStrategy,\n Component,\n ElementRef,\n OnDestroy,\n inject,\n output,\n signal,\n viewChild,\n} from '@angular/core';\nimport { FormsModule } from '@angular/forms';\nimport {\n IonButton,\n IonInput,\n IonItem,\n IonNote,\n IonSpinner,\n IonText,\n} from '@ionic/angular';\nimport { FirebaseError } from 'firebase/app';\nimport {\n PhoneVerificationService,\n PhoneVerificationStateError,\n} from './phone-verification.service';\n\ntype PendingAction = 'sending' | 'verifying';\n\n@Component({\n selector: 'sneat-phone-verification',\n templateUrl: './phone-verification.component.html',\n styleUrl: './phone-verification.component.scss',\n changeDetection: ChangeDetectionStrategy.OnPush,\n imports: [\n FormsModule,\n IonButton,\n IonInput,\n IonItem,\n IonNote,\n IonSpinner,\n IonText,\n ],\n providers: [PhoneVerificationService],\n})\nexport class PhoneVerificationComponent implements OnDestroy {\n private readonly phoneVerification = inject(PhoneVerificationService);\n private readonly recaptchaContainer =\n viewChild<ElementRef<HTMLDivElement>>('recaptchaContainer');\n\n readonly verified = output<void>();\n\n protected readonly phoneNumber = signal(\n this.phoneVerification.currentPhoneNumber,\n );\n protected readonly verificationCode = signal('');\n protected readonly verificationId = signal<string | undefined>(undefined);\n protected readonly verifiedPhoneNumber = signal<string | undefined>(\n undefined,\n );\n protected readonly pending = signal<PendingAction | undefined>(undefined);\n protected readonly errorMessage = signal<string | undefined>(undefined);\n\n protected get isPhoneNumberValid(): boolean {\n return /^\\+[1-9]\\d{7,14}$/.test(this.phoneNumber().trim());\n }\n\n protected get isVerificationCodeValid(): boolean {\n return /^\\d{6}$/.test(this.verificationCode().trim());\n }\n\n protected async requestCode(): Promise<void> {\n if (this.pending()) return;\n const phoneNumber = this.phoneNumber().trim();\n this.phoneNumber.set(phoneNumber);\n if (!this.isPhoneNumberValid) {\n this.errorMessage.set(\n 'Enter a valid international phone number, including the country code.',\n );\n return;\n }\n const container = this.recaptchaContainer()?.nativeElement;\n if (!container) {\n this.errorMessage.set(\n 'Phone verification is temporarily unavailable. Please try again.',\n );\n return;\n }\n\n this.errorMessage.set(undefined);\n this.pending.set('sending');\n try {\n const verificationId = await this.phoneVerification.requestCode(\n phoneNumber,\n container,\n );\n this.verificationId.set(verificationId);\n this.verificationCode.set('');\n } catch (error) {\n this.errorMessage.set(this.safeErrorMessage(error));\n } finally {\n this.pending.set(undefined);\n }\n }\n\n protected async verifyCode(): Promise<void> {\n if (this.pending()) return;\n const verificationId = this.verificationId();\n const code = this.verificationCode().trim();\n this.verificationCode.set(code);\n if (!verificationId) {\n this.errorMessage.set('Request a new verification code.');\n return;\n }\n if (!this.isVerificationCodeValid) {\n this.errorMessage.set('Enter the six-digit code from the SMS.');\n return;\n }\n\n this.errorMessage.set(undefined);\n this.pending.set('verifying');\n try {\n await this.phoneVerification.verifyCode(verificationId, code);\n this.verifiedPhoneNumber.set(this.phoneNumber());\n this.verificationId.set(undefined);\n this.verificationCode.set('');\n this.verified.emit();\n } catch (error) {\n this.errorMessage.set(this.safeErrorMessage(error));\n } finally {\n this.pending.set(undefined);\n }\n }\n\n protected useAnotherNumber(): void {\n if (this.pending()) return;\n this.phoneVerification.reset();\n this.verificationId.set(undefined);\n this.verificationCode.set('');\n this.errorMessage.set(undefined);\n }\n\n ngOnDestroy(): void {\n this.phoneVerification.reset();\n }\n\n private safeErrorMessage(error: unknown): string {\n if (error instanceof PhoneVerificationStateError) {\n return error.code === 'user-changed'\n ? 'Your sign-in changed. Start phone verification again.'\n : 'Sign in with your account before verifying a phone number.';\n }\n if (!(error instanceof FirebaseError)) {\n return 'Phone verification failed. Please try again.';\n }\n switch (error.code) {\n case 'auth/invalid-phone-number':\n case 'auth/missing-phone-number':\n return 'Enter a valid international phone number, including the country code.';\n case 'auth/invalid-verification-code':\n return 'That verification code is not correct. Check the SMS and try again.';\n case 'auth/code-expired':\n case 'auth/session-expired':\n return 'That code has expired. Request a new verification code.';\n case 'auth/credential-already-in-use':\n case 'auth/account-exists-with-different-credential':\n return 'That phone number is already linked to another account.';\n case 'auth/requires-recent-login':\n return 'For security, sign in again before changing your phone number.';\n case 'auth/quota-exceeded':\n case 'auth/too-many-requests':\n return 'Too many verification attempts. Please wait before trying again.';\n default:\n return 'Phone verification failed. Please try again.';\n }\n }\n}\n","<section aria-labelledby=\"phone-verification-heading\">\n <h2 id=\"phone-verification-heading\">Verify your phone number</h2>\n\n @if (verifiedPhoneNumber(); as verifiedNumber) {\n <p role=\"status\">\n <strong>{{ verifiedNumber }}</strong> is verified and linked to your\n account.\n </p>\n } @else if (verificationId()) {\n <form (ngSubmit)=\"verifyCode()\" novalidate>\n <p>\n Enter the six-digit code sent to\n <strong>{{ phoneNumber() }}</strong>.\n </p>\n <ion-item>\n <ion-input\n name=\"verificationCode\"\n label=\"Verification code\"\n labelPlacement=\"stacked\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n maxlength=\"6\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"verificationCode()\"\n (ngModelChange)=\"verificationCode.set($event)\"\n />\n </ion-item>\n <div class=\"actions\">\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isVerificationCodeValid\"\n >\n @if (pending() === 'verifying') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Verifying…\n } @else {\n Verify phone\n }\n </ion-button>\n <ion-button\n type=\"button\"\n fill=\"clear\"\n [disabled]=\"!!pending()\"\n (click)=\"useAnotherNumber()\"\n >\n Request another code or change number\n </ion-button>\n </div>\n </form>\n } @else {\n <form (ngSubmit)=\"requestCode()\" novalidate>\n <ion-item>\n <ion-input\n name=\"phoneNumber\"\n type=\"tel\"\n inputmode=\"tel\"\n autocomplete=\"tel\"\n label=\"Phone number\"\n labelPlacement=\"stacked\"\n placeholder=\"+353…\"\n [disabled]=\"!!pending()\"\n [ngModel]=\"phoneNumber()\"\n (ngModelChange)=\"phoneNumber.set($event)\"\n />\n </ion-item>\n <ion-note>\n Use the international format beginning with “+”. Google Firebase will\n send an authentication SMS and process your phone number for spam and\n abuse prevention. Standard SMS rates may apply. We will not use this\n verification message for marketing.\n </ion-note>\n <div #recaptchaContainer class=\"recaptcha\" aria-label=\"Security check\"></div>\n <ion-button\n type=\"submit\"\n [disabled]=\"!!pending() || !isPhoneNumberValid\"\n >\n @if (pending() === 'sending') {\n <ion-spinner name=\"lines-small\" aria-hidden=\"true\" />\n Sending code…\n } @else {\n Send verification code\n }\n </ion-button>\n </form>\n }\n\n @if (errorMessage(); as message) {\n <ion-text color=\"danger\">\n <p class=\"error\" role=\"alert\">{{ message }}</p>\n </ion-text>\n }\n</section>\n"]}
@@ -0,0 +1,83 @@
1
+ import { inject, Injectable, InjectionToken, NgZone } from '@angular/core';
2
+ import { SNEAT_FIREBASE_AUTH } from '@sneat/core';
3
+ import { getIdToken, PhoneAuthProvider, RecaptchaVerifier, updatePhoneNumber, } from 'firebase/auth';
4
+ import * as i0 from "@angular/core";
5
+ export const PHONE_AUTH_ADAPTER = new InjectionToken('PHONE_AUTH_ADAPTER', {
6
+ providedIn: 'root',
7
+ factory: () => ({
8
+ createRecaptcha: (auth, container) => new RecaptchaVerifier(auth, container, { size: 'normal' }),
9
+ getCredential: (verificationId, code) => PhoneAuthProvider.credential(verificationId, code),
10
+ getIdToken: (user) => getIdToken(user, true),
11
+ updatePhoneNumber,
12
+ verifyPhoneNumber: (auth, phoneNumber, verifier) => new PhoneAuthProvider(auth).verifyPhoneNumber(phoneNumber, verifier),
13
+ }),
14
+ });
15
+ export class PhoneVerificationStateError extends Error {
16
+ constructor(code) {
17
+ super(code);
18
+ this.code = code;
19
+ }
20
+ }
21
+ export class PhoneVerificationService {
22
+ constructor() {
23
+ this.auth = inject(SNEAT_FIREBASE_AUTH);
24
+ this.adapter = inject(PHONE_AUTH_ADAPTER);
25
+ this.zone = inject(NgZone);
26
+ }
27
+ get currentPhoneNumber() {
28
+ return this.auth.currentUser?.phoneNumber ?? '';
29
+ }
30
+ async requestCode(phoneNumber, recaptchaContainer) {
31
+ const user = this.requireEligibleUser();
32
+ this.verificationUserUid = user.uid;
33
+ this.clearRecaptcha();
34
+ try {
35
+ this.recaptcha = this.zone.runOutsideAngular(() => this.adapter.createRecaptcha(this.auth, recaptchaContainer));
36
+ return await this.zone.runOutsideAngular(() => this.adapter.verifyPhoneNumber(this.auth, phoneNumber, this.recaptcha));
37
+ }
38
+ catch (error) {
39
+ this.verificationUserUid = undefined;
40
+ throw error;
41
+ }
42
+ finally {
43
+ this.clearRecaptcha();
44
+ }
45
+ }
46
+ async verifyCode(verificationId, code) {
47
+ const user = this.requireEligibleUser();
48
+ if (!this.verificationUserUid || user.uid !== this.verificationUserUid) {
49
+ throw new PhoneVerificationStateError('user-changed');
50
+ }
51
+ const credential = this.adapter.getCredential(verificationId, code);
52
+ await this.zone.runOutsideAngular(() => this.adapter.updatePhoneNumber(user, credential));
53
+ await this.zone.runOutsideAngular(() => this.adapter.getIdToken(user));
54
+ this.verificationUserUid = undefined;
55
+ }
56
+ reset() {
57
+ this.verificationUserUid = undefined;
58
+ this.clearRecaptcha();
59
+ }
60
+ ngOnDestroy() {
61
+ this.reset();
62
+ }
63
+ requireEligibleUser() {
64
+ const user = this.auth.currentUser;
65
+ if (!user) {
66
+ throw new PhoneVerificationStateError('no-user');
67
+ }
68
+ if (user.isAnonymous) {
69
+ throw new PhoneVerificationStateError('anonymous-user');
70
+ }
71
+ return user;
72
+ }
73
+ clearRecaptcha() {
74
+ this.recaptcha?.clear();
75
+ this.recaptcha = undefined;
76
+ }
77
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: PhoneVerificationService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
78
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: PhoneVerificationService }); }
79
+ }
80
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImport: i0, type: PhoneVerificationService, decorators: [{
81
+ type: Injectable
82
+ }] });
83
+ //# sourceMappingURL=phone-verification.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"phone-verification.service.js","sourceRoot":"","sources":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IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;QACpE,MAAM,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,CACrC,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,EAAE,UAAU,CAAC,CACjD,CAAC;QACF,MAAM,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;QACvE,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;IACvC,CAAC;IAED,KAAK;QACH,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;QACrC,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED,WAAW;QACT,IAAI,CAAC,KAAK,EAAE,CAAC;IACf,CAAC;IAEO,mBAAmB;QACzB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;QACnC,IAAI,CAAC,IAAI,EAAE,CAAC;YACV,MAAM,IAAI,2BAA2B,CAAC,SAAS,CAAC,CAAC;QACnD,CAAC;QACD,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,MAAM,IAAI,2BAA2B,CAAC,gBAAgB,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc;QACpB,IAAI,CAAC,SAAS,EAAE,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;8GA1EU,wBAAwB;kHAAxB,wBAAwB;;2FAAxB,wBAAwB;kBADpC,UAAU","sourcesContent":["import { inject, Injectable, InjectionToken, NgZone, OnDestroy } from '@angular/core';\nimport { SNEAT_FIREBASE_AUTH } from '@sneat/core';\nimport {\n ApplicationVerifier,\n Auth,\n getIdToken,\n PhoneAuthCredential,\n PhoneAuthProvider,\n RecaptchaVerifier,\n updatePhoneNumber,\n User,\n} from 'firebase/auth';\n\ninterface PhoneAuthAdapter {\n createRecaptcha(auth: Auth, container: HTMLElement): RecaptchaVerifier;\n getCredential(verificationId: string, code: string): PhoneAuthCredential;\n getIdToken(user: User): Promise<string>;\n updatePhoneNumber(user: User, credential: PhoneAuthCredential): Promise<void>;\n verifyPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n verifier: ApplicationVerifier,\n ): Promise<string>;\n}\n\nexport const PHONE_AUTH_ADAPTER = new InjectionToken<PhoneAuthAdapter>(\n 'PHONE_AUTH_ADAPTER',\n {\n providedIn: 'root',\n factory: (): PhoneAuthAdapter => ({\n createRecaptcha: (auth, container) =>\n new RecaptchaVerifier(auth, container, { size: 'normal' }),\n getCredential: (verificationId, code) =>\n PhoneAuthProvider.credential(verificationId, code),\n getIdToken: (user) => getIdToken(user, true),\n updatePhoneNumber,\n verifyPhoneNumber: (auth, phoneNumber, verifier) =>\n new PhoneAuthProvider(auth).verifyPhoneNumber(phoneNumber, verifier),\n }),\n },\n);\n\nexport class PhoneVerificationStateError extends Error {\n constructor(readonly code: 'no-user' | 'anonymous-user' | 'user-changed') {\n super(code);\n }\n}\n\n@Injectable()\nexport class PhoneVerificationService implements OnDestroy {\n private readonly auth = inject(SNEAT_FIREBASE_AUTH);\n private readonly adapter = inject(PHONE_AUTH_ADAPTER);\n private readonly zone = inject(NgZone);\n\n private recaptcha?: RecaptchaVerifier;\n private verificationUserUid?: string;\n\n get currentPhoneNumber(): string {\n return this.auth.currentUser?.phoneNumber ?? '';\n }\n\n async requestCode(\n phoneNumber: string,\n recaptchaContainer: HTMLElement,\n ): Promise<string> {\n const user = this.requireEligibleUser();\n this.verificationUserUid = user.uid;\n this.clearRecaptcha();\n try {\n this.recaptcha = this.zone.runOutsideAngular(() =>\n this.adapter.createRecaptcha(this.auth, recaptchaContainer),\n );\n return await this.zone.runOutsideAngular(() =>\n this.adapter.verifyPhoneNumber(\n this.auth,\n phoneNumber,\n this.recaptcha as RecaptchaVerifier,\n ),\n );\n } catch (error) {\n this.verificationUserUid = undefined;\n throw error;\n } finally {\n this.clearRecaptcha();\n }\n }\n\n async verifyCode(verificationId: string, code: string): Promise<void> {\n const user = this.requireEligibleUser();\n if (!this.verificationUserUid || user.uid !== this.verificationUserUid) {\n throw new PhoneVerificationStateError('user-changed');\n }\n const credential = this.adapter.getCredential(verificationId, code);\n await this.zone.runOutsideAngular(() =>\n this.adapter.updatePhoneNumber(user, credential),\n );\n await this.zone.runOutsideAngular(() => this.adapter.getIdToken(user));\n this.verificationUserUid = undefined;\n }\n\n reset(): void {\n this.verificationUserUid = undefined;\n this.clearRecaptcha();\n }\n\n ngOnDestroy(): void {\n this.reset();\n }\n\n private requireEligibleUser(): User {\n const user = this.auth.currentUser;\n if (!user) {\n throw new PhoneVerificationStateError('no-user');\n }\n if (user.isAnonymous) {\n throw new PhoneVerificationStateError('anonymous-user');\n }\n return user;\n }\n\n private clearRecaptcha(): void {\n this.recaptcha?.clear();\n this.recaptcha = undefined;\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  export * from './user-required-fields';
2
2
  export * from './user-auth-providers/user-auth-accounts.component';
3
3
  export * from './auth-menu-item/auth-menu-item.component';
4
+ export * from './phone-verification';
@@ -0,0 +1 @@
1
+ export * from './phone-verification.component';
@@ -0,0 +1,24 @@
1
+ import { OnDestroy } from '@angular/core';
2
+ import * as i0 from "@angular/core";
3
+ type PendingAction = 'sending' | 'verifying';
4
+ export declare class PhoneVerificationComponent implements OnDestroy {
5
+ private readonly phoneVerification;
6
+ private readonly recaptchaContainer;
7
+ readonly verified: import("@angular/core").OutputEmitterRef<void>;
8
+ protected readonly phoneNumber: import("@angular/core").WritableSignal<string>;
9
+ protected readonly verificationCode: import("@angular/core").WritableSignal<string>;
10
+ protected readonly verificationId: import("@angular/core").WritableSignal<string | undefined>;
11
+ protected readonly verifiedPhoneNumber: import("@angular/core").WritableSignal<string | undefined>;
12
+ protected readonly pending: import("@angular/core").WritableSignal<PendingAction | undefined>;
13
+ protected readonly errorMessage: import("@angular/core").WritableSignal<string | undefined>;
14
+ protected get isPhoneNumberValid(): boolean;
15
+ protected get isVerificationCodeValid(): boolean;
16
+ protected requestCode(): Promise<void>;
17
+ protected verifyCode(): Promise<void>;
18
+ protected useAnotherNumber(): void;
19
+ ngOnDestroy(): void;
20
+ private safeErrorMessage;
21
+ static ɵfac: i0.ɵɵFactoryDeclaration<PhoneVerificationComponent, never>;
22
+ static ɵcmp: i0.ɵɵComponentDeclaration<PhoneVerificationComponent, "sneat-phone-verification", never, {}, { "verified": "verified"; }, never, never, true, never>;
23
+ }
24
+ export {};
@@ -0,0 +1,32 @@
1
+ import { InjectionToken, OnDestroy } from '@angular/core';
2
+ import { ApplicationVerifier, Auth, PhoneAuthCredential, RecaptchaVerifier, User } from 'firebase/auth';
3
+ import * as i0 from "@angular/core";
4
+ interface PhoneAuthAdapter {
5
+ createRecaptcha(auth: Auth, container: HTMLElement): RecaptchaVerifier;
6
+ getCredential(verificationId: string, code: string): PhoneAuthCredential;
7
+ getIdToken(user: User): Promise<string>;
8
+ updatePhoneNumber(user: User, credential: PhoneAuthCredential): Promise<void>;
9
+ verifyPhoneNumber(auth: Auth, phoneNumber: string, verifier: ApplicationVerifier): Promise<string>;
10
+ }
11
+ export declare const PHONE_AUTH_ADAPTER: InjectionToken<PhoneAuthAdapter>;
12
+ export declare class PhoneVerificationStateError extends Error {
13
+ readonly code: 'no-user' | 'anonymous-user' | 'user-changed';
14
+ constructor(code: 'no-user' | 'anonymous-user' | 'user-changed');
15
+ }
16
+ export declare class PhoneVerificationService implements OnDestroy {
17
+ private readonly auth;
18
+ private readonly adapter;
19
+ private readonly zone;
20
+ private recaptcha?;
21
+ private verificationUserUid?;
22
+ get currentPhoneNumber(): string;
23
+ requestCode(phoneNumber: string, recaptchaContainer: HTMLElement): Promise<string>;
24
+ verifyCode(verificationId: string, code: string): Promise<void>;
25
+ reset(): void;
26
+ ngOnDestroy(): void;
27
+ private requireEligibleUser;
28
+ private clearRecaptcha;
29
+ static ɵfac: i0.ɵɵFactoryDeclaration<PhoneVerificationService, never>;
30
+ static ɵprov: i0.ɵɵInjectableDeclaration<PhoneVerificationService>;
31
+ }
32
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sneat/auth-ui",
3
- "version": "0.27.9",
3
+ "version": "0.27.11",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },