fix(FE): allow only enabled factors to be displayed on user page (#9313)

# Which Problems Are Solved

- Hides for users MFA options are not allowed by org policy.
- Fix for "ng test" across "console"

# How the Problems Are Solved

- Before displaying MFA options we call "listMyMultiFactors" from parent
component to filter MFA allowed by org

# Additional Changes

- Dependency Injection was fixed around ng unit tests

# Additional Context

admin view
<img width="698" alt="Screenshot 2025-02-06 at 00 26 50"
src="https://github.com/user-attachments/assets/1b642c8a-a640-4bdd-a1ca-bde70c263567"
/>
user view
<img width="751" alt="Screenshot 2025-02-06 at 00 27 16"
src="https://github.com/user-attachments/assets/e1c99907-3226-46ce-b8bc-e993af4b4cae"
/>
test
<img width="1500" alt="Screenshot 2025-02-06 at 00 01 36"
src="https://github.com/user-attachments/assets/d2d8ead1-9f0f-4916-a2fc-f4db9c71cfa8"
/>

The issue: https://github.com/zitadel/zitadel/issues/9176
The bug report:
https://discord.com/channels/927474939156643850/1307006457815896094

---------

Co-authored-by: a k <[email protected]>
Co-authored-by: a k <[email protected]>
Co-authored-by: a k <[email protected]>
Co-authored-by: Ramon <[email protected]>
This commit is contained in:
AnthonyKot
2025-06-04 09:26:53 +00:00
committed by GitHub
co-authored by a k a k a k Ramon
parent 1a80e26502
commit 839c761357
27 changed files with 411 additions and 204 deletions
@@ -1,5 +1,5 @@
<h1 mat-dialog-title>
<span class="title">{{ 'USER.MFA.DIALOG.ADD_MFA_TITLE' | translate }} {{ data?.number }}</span>
<span class="title">{{ 'USER.MFA.DIALOG.ADD_MFA_TITLE' | translate }}</span>
</h1>
<div mat-dialog-content>
<ng-container *ngIf="selectedType === undefined">
@@ -7,6 +7,7 @@
<div class="type-selection">
<button
*ngIf="data.otp$ | async"
mat-stroked-button
[disabled]="data.otpDisabled$ | async"
(click)="selectType(AuthFactorType.OTP)"
@@ -56,7 +57,7 @@
<span>{{ 'USER.MFA.OTP' | translate }}</span>
</div>
</button>
<button mat-stroked-button (click)="selectType(AuthFactorType.U2F)">
<button *ngIf="data.u2f$ | async" mat-stroked-button (click)="selectType(AuthFactorType.U2F)">
<div class="u2f-btn">
<div class="icon-row">
<svg
@@ -78,6 +79,7 @@
</div>
</button>
<button
*ngIf="data.otpSms$ | async"
[disabled]="!data.phoneVerified || (data.otpSmsDisabled$ | async)"
mat-stroked-button
(click)="selectType(AuthFactorType.OTPSMS)"
@@ -110,7 +112,12 @@
</div>
</div>
</button>
<button [disabled]="data.otpEmailDisabled$ | async" mat-stroked-button (click)="selectType(AuthFactorType.OTPEMAIL)">
<button
*ngIf="data.otpEmail$ | async"
[disabled]="data.otpEmailDisabled$ | async"
mat-stroked-button
(click)="selectType(AuthFactorType.OTPEMAIL)"
>
<div class="otp-btn">
<div class="icon-row">
<svg
@@ -2,6 +2,7 @@ import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TranslateService } from '@ngx-translate/core';
import { take } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { GrpcAuthService } from 'src/app/services/grpc-auth.service';
import { ToastService } from 'src/app/services/toast.service';
@@ -16,6 +17,17 @@ export enum AuthFactorType {
OTPEMAIL,
}
export type AddAuthFactorDialogData = {
otp$: Observable<boolean>;
u2f$: Observable<boolean>;
otpSms$: Observable<boolean>;
otpEmail$: Observable<boolean>;
otpDisabled$: Observable<boolean>;
otpSmsDisabled$: Observable<boolean>;
otpEmailDisabled$: Observable<boolean>;
phoneVerified: boolean;
};
@Component({
selector: 'cnsl-auth-factor-dialog',
templateUrl: './auth-factor-dialog.component.html',
@@ -44,7 +56,7 @@ export class AuthFactorDialogComponent {
private toast: ToastService,
private translate: TranslateService,
public dialogRef: MatDialogRef<AuthFactorDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
@Inject(MAT_DIALOG_DATA) public data: AddAuthFactorDialogData,
) {}
closeDialog(code: string = ''): void {
@@ -1,24 +1,147 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { of } from 'rxjs';
import { AuthUserMfaComponent } from './auth-user-mfa.component';
import { ToastService } from 'src/app/services/toast.service';
import { MatDialog } from '@angular/material/dialog';
import { NewAuthService } from 'src/app/services/new-auth.service';
import { SecondFactorType } from 'src/app/proto/generated/zitadel/policy_pb';
import { CardComponent } from 'src/app/modules/card/card.component';
import { RefreshTableComponent } from 'src/app/modules/refresh-table/refresh-table.component';
import { TranslateModule } from '@ngx-translate/core';
import { MatIconModule } from '@angular/material/icon';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AuthFactor, AuthFactorState } from '@zitadel/proto/zitadel/user_pb';
describe('AuthUserMfaComponent', () => {
let component: AuthUserMfaComponent;
let fixture: ComponentFixture<AuthUserMfaComponent>;
// Create a test host component that extends the original component
class TestHostComponent extends AuthUserMfaComponent {
// Expose protected properties for testing
public getOtpEmailDisabled$() {
return this.otpEmailDisabled$;
}
public getOtpDisabled$() {
return this.otpDisabled$;
}
public getOtpSmsDisabled$() {
return this.otpSmsDisabled$;
}
}
let component: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let serviceStub: Partial<NewAuthService>;
let toastStub: Partial<ToastService>;
let dialogStub: Partial<MatDialog>;
beforeEach(waitForAsync(() => {
// Create stubs for required services
serviceStub = {
listMyMultiFactors: jasmine.createSpy('listMyMultiFactors').and.returnValue(
Promise.resolve({
result: [
{ type: { case: 'otp' }, state: AuthFactorState.READY, $typeName: 'zitadel.user.v1.AuthFactor' } as AuthFactor,
{
type: { case: 'otpSms' },
state: AuthFactorState.READY,
$typeName: 'zitadel.user.v1.AuthFactor',
} as AuthFactor,
{
type: { case: 'otpEmail' },
state: AuthFactorState.READY,
$typeName: 'zitadel.user.v1.AuthFactor',
} as AuthFactor,
],
}),
),
getMyLoginPolicy: jasmine.createSpy('getMyLoginPolicy').and.returnValue(
Promise.resolve({
policy: {
secondFactorsList: [
SecondFactorType.SECOND_FACTOR_TYPE_OTP,
SecondFactorType.SECOND_FACTOR_TYPE_U2F,
SecondFactorType.SECOND_FACTOR_TYPE_OTP_EMAIL,
SecondFactorType.SECOND_FACTOR_TYPE_OTP_SMS,
],
},
}),
),
removeMyMultiFactorOTP: jasmine.createSpy('removeMyMultiFactorOTP').and.returnValue(Promise.resolve()),
removeMyMultiFactorU2F: jasmine.createSpy('removeMyMultiFactorU2F').and.returnValue(Promise.resolve()),
removeMyAuthFactorOTPEmail: jasmine.createSpy('removeMyAuthFactorOTPEmail').and.returnValue(Promise.resolve()),
removeMyAuthFactorOTPSMS: jasmine.createSpy('removeMyAuthFactorOTPSMS').and.returnValue(Promise.resolve()),
};
toastStub = {
showInfo: jasmine.createSpy('showInfo'),
showError: jasmine.createSpy('showError'),
};
dialogStub = {
// Opened dialog returns a truthy value after closing
open: jasmine.createSpy('open').and.returnValue({
afterClosed: () => of(true),
}),
};
TestBed.configureTestingModule({
declarations: [AuthUserMfaComponent],
declarations: [TestHostComponent, CardComponent, RefreshTableComponent], // Use TestHostComponent instead
imports: [MatIconModule, TranslateModule.forRoot(), MatTooltipModule, MatTableModule, BrowserAnimationsModule],
providers: [
{ provide: NewAuthService, useValue: serviceStub },
{ provide: ToastService, useValue: toastStub },
{ provide: MatDialog, useValue: dialogStub },
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthUserMfaComponent);
fixture = TestBed.createComponent(TestHostComponent); // Use TestHostComponent
component = fixture.componentInstance;
// Optionally set the phoneVerified input if needed by your tests
component.phoneVerified = true;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call getMFAs and update dataSource and disable flags', async () => {
// Call the method and wait for the Promise resolution
await component.getMFAs();
fixture.detectChanges();
expect(serviceStub.listMyMultiFactors).toHaveBeenCalled();
// Our stub returns 3 items
expect(component.dataSource.data.length).toBe(3);
// Use the public getter methods to access protected properties
component.getOtpDisabled$().subscribe((value) => {
expect(value).toBeTrue();
});
component.getOtpSmsDisabled$().subscribe((value) => {
expect(value).toBeTrue();
});
component.getOtpEmailDisabled$().subscribe((value) => {
expect(value).toBeTrue();
});
});
it('should call deleteMFA and remove OTP factor', async () => {
// OTP is set
const factor = {
type: { case: 'otp' },
state: AuthFactorState.READY,
$typeName: 'zitadel.user.v1.AuthFactor',
} as AuthFactor;
await component.deleteMFA(factor);
// Verify that the service method for OTP removal was called
expect(serviceStub.removeMyMultiFactorOTP).toHaveBeenCalled();
expect(serviceStub.listMyMultiFactors).toHaveBeenCalled();
});
});
@@ -4,12 +4,12 @@ import { MatSort } from '@angular/material/sort';
import { MatTable, MatTableDataSource } from '@angular/material/table';
import { BehaviorSubject, Observable } from 'rxjs';
import { WarnDialogComponent } from 'src/app/modules/warn-dialog/warn-dialog.component';
import { AuthFactor, AuthFactorState } from 'src/app/proto/generated/zitadel/user_pb';
import { GrpcAuthService } from 'src/app/services/grpc-auth.service';
import { AuthFactorState } from 'src/app/proto/generated/zitadel/user_pb';
import { NewAuthService } from 'src/app/services/new-auth.service';
import { ToastService } from 'src/app/services/toast.service';
import { AuthFactorDialogComponent } from '../auth-factor-dialog/auth-factor-dialog.component';
import { AddAuthFactorDialogData, AuthFactorDialogComponent } from '../auth-factor-dialog/auth-factor-dialog.component';
import { AuthFactor } from '@zitadel/proto/zitadel/user_pb';
import { SecondFactorType } from '@zitadel/proto/zitadel/policy_pb';
export interface WebAuthNOptions {
challenge: string;
rp: { name: string; id: string };
@@ -30,26 +30,31 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
private loadingSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public loading$: Observable<boolean> = this.loadingSubject.asObservable();
@ViewChild(MatTable) public table!: MatTable<AuthFactor.AsObject>;
@ViewChild(MatTable) public table!: MatTable<AuthFactor>;
@ViewChild(MatSort) public sort!: MatSort;
@Input() public phoneVerified: boolean = false;
public dataSource: MatTableDataSource<AuthFactor.AsObject> = new MatTableDataSource<AuthFactor.AsObject>([]);
public AuthFactorState: any = AuthFactorState;
public dataSource: MatTableDataSource<AuthFactor> = new MatTableDataSource<AuthFactor>([]);
public error: string = '';
public otpDisabled$ = new BehaviorSubject<boolean>(true);
public otpSmsDisabled$ = new BehaviorSubject<boolean>(true);
public otpEmailDisabled$ = new BehaviorSubject<boolean>(true);
protected error: string = '';
protected otpAvailable$ = new BehaviorSubject<boolean>(false);
protected u2fAvailable$ = new BehaviorSubject<boolean>(false);
protected otpSmsAvailable$ = new BehaviorSubject<boolean>(false);
protected otpEmailAvailable$ = new BehaviorSubject<boolean>(false);
protected otpDisabled$ = new BehaviorSubject<boolean>(true);
protected otpSmsDisabled$ = new BehaviorSubject<boolean>(true);
protected otpEmailDisabled$ = new BehaviorSubject<boolean>(true);
constructor(
private service: GrpcAuthService,
private toast: ToastService,
private dialog: MatDialog,
private readonly service: NewAuthService,
private readonly toast: ToastService,
private readonly dialog: MatDialog,
) {}
public ngOnInit(): void {
this.getMFAs();
this.applyOrgPolicy();
}
public ngOnDestroy(): void {
@@ -57,13 +62,19 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
}
public addAuthFactor(): void {
const data: AddAuthFactorDialogData = {
otp$: this.otpAvailable$,
u2f$: this.u2fAvailable$,
otpSms$: this.otpSmsAvailable$,
otpEmail$: this.otpEmailAvailable$,
otpDisabled$: this.otpDisabled$,
otpSmsDisabled$: this.otpSmsDisabled$,
otpEmailDisabled$: this.otpEmailDisabled$,
phoneVerified: this.phoneVerified,
} as const;
const dialogRef = this.dialog.open(AuthFactorDialogComponent, {
data: {
otpDisabled$: this.otpDisabled$,
otpSmsDisabled$: this.otpSmsDisabled$,
otpEmailDisabled$: this.otpEmailDisabled$,
phoneVerified: this.phoneVerified,
},
data: data,
});
dialogRef.afterClosed().subscribe(() => {
@@ -75,48 +86,32 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
this.service
.listMyMultiFactors()
.then((mfas) => {
const list = mfas.resultList;
const list: AuthFactor[] = mfas.result;
this.dataSource = new MatTableDataSource(list);
this.dataSource.sort = this.sort;
const index = list.findIndex((mfa) => mfa.otp);
if (index === -1) {
this.otpDisabled$.next(false);
}
const sms = list.findIndex((mfa) => mfa.otpSms);
if (sms === -1) {
this.otpSmsDisabled$.next(false);
}
const email = list.findIndex((mfa) => mfa.otpEmail);
if (email === -1) {
this.otpEmailDisabled$.next(false);
}
this.disableAuthFactor(list, 'otp', this.otpDisabled$);
this.disableAuthFactor(list, 'otpSms', this.otpSmsDisabled$);
this.disableAuthFactor(list, 'otpEmail', this.otpEmailDisabled$);
})
.catch((error) => {
this.error = error.message;
});
}
private cleanupList(): void {
const totp = this.dataSource.data.findIndex((mfa) => !!mfa.otp);
if (totp > -1) {
this.dataSource.data.splice(totp, 1);
}
const sms = this.dataSource.data.findIndex((mfa) => !!mfa.otpSms);
if (sms > -1) {
this.dataSource.data.splice(sms, 1);
}
const email = this.dataSource.data.findIndex((mfa) => !!mfa.otpEmail);
if (email > -1) {
this.dataSource.data.splice(email, 1);
}
public applyOrgPolicy(): void {
this.service.getMyLoginPolicy().then((resp) => {
if (resp && resp.policy) {
const secondFactors = resp.policy?.secondFactors;
this.displayAuthFactorBasedOnPolicy(secondFactors, SecondFactorType.OTP, this.otpAvailable$);
this.displayAuthFactorBasedOnPolicy(secondFactors, SecondFactorType.U2F, this.u2fAvailable$);
this.displayAuthFactorBasedOnPolicy(secondFactors, SecondFactorType.OTP_EMAIL, this.otpEmailAvailable$);
this.displayAuthFactorBasedOnPolicy(secondFactors, SecondFactorType.OTP_SMS, this.otpSmsAvailable$);
}
});
}
public deleteMFA(factor: AuthFactor.AsObject): void {
public deleteMFA(factor: AuthFactor): void {
const dialogRef = this.dialog.open(WarnDialogComponent, {
data: {
confirmKey: 'ACTIONS.DELETE',
@@ -129,7 +124,7 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
dialogRef.afterClosed().subscribe((resp) => {
if (resp) {
if (factor.otp) {
if (factor.type.case === 'otp') {
this.service
.removeMyMultiFactorOTP()
.then(() => {
@@ -141,9 +136,9 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
.catch((error) => {
this.toast.showError(error);
});
} else if (factor.u2f) {
} else if (factor.type.case === 'u2f') {
this.service
.removeMyMultiFactorU2F(factor.u2f.id)
.removeMyMultiFactorU2F(factor.type.value.id)
.then(() => {
this.toast.showInfo('USER.TOAST.U2FREMOVED', true);
@@ -153,7 +148,7 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
.catch((error) => {
this.toast.showError(error);
});
} else if (factor.otpEmail) {
} else if (factor.type.case === 'otpEmail') {
this.service
.removeMyAuthFactorOTPEmail()
.then(() => {
@@ -165,7 +160,7 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
.catch((error) => {
this.toast.showError(error);
});
} else if (factor.otpSms) {
} else if (factor.type.case === 'otpSms') {
this.service
.removeMyAuthFactorOTPSMS()
.then(() => {
@@ -181,4 +176,22 @@ export class AuthUserMfaComponent implements OnInit, OnDestroy {
}
});
}
private cleanupList(): void {
this.dataSource.data = this.dataSource.data.filter((mfa: AuthFactor) => {
return mfa.type.case;
});
}
private disableAuthFactor(mfas: AuthFactor[], key: string, subject: BehaviorSubject<boolean>): void {
subject.next(mfas.some((mfa) => mfa.type.case === key));
}
private displayAuthFactorBasedOnPolicy(
factors: SecondFactorType[],
factor: SecondFactorType,
subject: BehaviorSubject<boolean>,
): void {
subject.next(factors.some((f) => f === factor));
}
}
@@ -2,7 +2,7 @@ import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { WarnDialogComponent } from 'src/app/modules/warn-dialog/warn-dialog.component';
import { GrpcAuthService } from 'src/app/services/grpc-auth.service';
import { NewAuthService } from 'src/app/services/new-auth.service';
import { CodeDialogComponent } from '../auth-user-detail/code-dialog/code-dialog.component';
import { EditDialogType } from '../auth-user-detail/edit-dialog/edit-dialog.component';
import { HumanUser, UserState } from '@zitadel/proto/zitadel/user/v2/user_pb';
@@ -28,12 +28,12 @@ export class ContactComponent {
public EditDialogType: any = EditDialogType;
constructor(
private dialog: MatDialog,
private authService: GrpcAuthService,
private authService: NewAuthService,
) {}
async emitDeletePhone(): Promise<void> {
const { resultList } = await this.authService.listMyMultiFactors();
const hasSMSOTP = !!resultList.find((mfa) => mfa.otpSms);
const { result } = await this.authService.listMyMultiFactors();
const hasSMSOTP = !!result.some((mfa) => mfa.type.case === 'otpSms');
const dialogRef = this.dialog.open(WarnDialogComponent, {
data: {
@@ -1,19 +1,19 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { DetailFormComponent } from './detail-form.component';
import { DetailFormMachineComponent } from './detail-form-machine.component';
describe('DetailFormComponent', () => {
let component: DetailFormComponent;
let fixture: ComponentFixture<DetailFormComponent>;
let component: DetailFormMachineComponent;
let fixture: ComponentFixture<DetailFormMachineComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [DetailFormComponent],
declarations: [DetailFormMachineComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DetailFormComponent);
fixture = TestBed.createComponent(DetailFormMachineComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
@@ -1,19 +1,19 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { AuthPasswordlessComponent } from './auth-passwordless.component';
import { PasswordlessComponent } from './passwordless.component';
describe('AuthPasswordlessComponent', () => {
let component: AuthPasswordlessComponent;
let fixture: ComponentFixture<AuthPasswordlessComponent>;
let component: PasswordlessComponent;
let fixture: ComponentFixture<PasswordlessComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [AuthPasswordlessComponent],
declarations: [PasswordlessComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthPasswordlessComponent);
fixture = TestBed.createComponent(PasswordlessComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});