WEB-233: Improve the OIDC integration with 2FA (#2616)

This commit is contained in:
AllsVeam
2025-09-01 13:55:35 -06:00
committed by GitHub
parent 801dd3fdfe
commit 6ee9f4d4d2
66 changed files with 4425 additions and 135 deletions
@@ -0,0 +1,205 @@
<div class="container">
<mat-card>
<form [formGroup]="userForm" (ngSubmit)="submit()">
<mat-card-content>
<div class="layout-row-wrap layout-lt-md-column gap-2percent">
<!-- Username -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Username' | translate }}</mat-label>
<input matInput required formControlName="username" />
<mat-error *ngIf="userForm.controls.username.hasError('required')">
{{ 'labels.inputs.Username' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.required' | translate }}</strong>
</mat-error>
</mat-form-field>
<!-- Email -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Email' | translate }}</mat-label>
<input matInput required formControlName="email" />
<mat-error *ngIf="userForm.controls.email.hasError('email')">
{{ 'labels.inputs.Email' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.invalid' | translate }}</strong>
</mat-error>
<mat-error *ngIf="userForm.controls.email.hasError('required')">
{{ 'labels.inputs.Email' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.required' | translate }}</strong>
</mat-error>
</mat-form-field>
<!-- First Name -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.First Name' | translate }}</mat-label>
<input matInput formControlName="firstName" required />
</mat-form-field>
<!-- Last Name -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Last Name' | translate }}</mat-label>
<input matInput formControlName="lastName" required />
</mat-form-field>
<!-- Preferred Language -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Language' | translate }}</mat-label>
<mat-select formControlName="preferredLanguage" required>
<mat-option *ngFor="let lang of languageCodes" [value]="lang.code">
{{ 'languages.' + lang.key | translate }}
</mat-option>
</mat-select>
</mat-form-field>
<!-- Gender -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Gender' | translate }}</mat-label>
<mat-select formControlName="gender" required>
<mat-option value="GENDER_MALE">{{ 'labels.catalogs.male' | translate }}</mat-option>
<mat-option value="GENDER_FEMALE">{{ 'labels.catalogs.female' | translate }}</mat-option>
<mat-option value="GENDER_OTHER">{{ 'labels.catalogs.other' | translate }}</mat-option>
</mat-select>
</mat-form-field>
<!-- Country code and phone -->
<div class="flex items-center gap-2">
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Code' | translate }}</mat-label>
<mat-select formControlName="countryCode" required>
<mat-option *ngFor="let country of countryCodes" [value]="country.code">
{{ 'countries.' + country.key | translate }} ({{ country.code }})
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Phone Number' | translate }}</mat-label>
<input matInput formControlName="phoneNumber" required maxlength="12" minlength="4" />
</mat-form-field>
</div>
<mat-form-field class="flex-20">
<mat-label>{{ 'labels.inputs.Office' | translate }}</mat-label>
<mat-select required formControlName="officeId">
<mat-option *ngFor="let office of officesData" [value]="office.id">
{{ office.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="userForm.controls.officeId.hasError('required')">
{{ 'labels.inputs.Office' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.required' | translate }}</strong>
</mat-error>
</mat-form-field>
<mat-form-field class="flex-20">
<mat-label>{{ 'labels.inputs.Staff' | translate }}</mat-label>
<mat-select formControlName="staffId">
<mat-option *ngFor="let staff of staffData" [value]="staff.id">
{{ staff.displayName }}
</mat-option>
</mat-select>
</mat-form-field>
<!-- Password -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Password' | translate }}</mat-label>
<input matInput type="password" formControlName="password" required />
<mat-error *ngIf="userForm.get('password')?.hasError('required')">
{{ 'labels.inputs.Password' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.required' | translate }}</strong>
</mat-error>
<mat-error *ngIf="userForm.get('password')?.hasError('minlength')">
{{ 'labels.commons.Password should be at least' | translate }}
<strong>{{ 'labels.commons.12 characters long' | translate }}</strong>
</mat-error>
<mat-error *ngIf="userForm.get('password')?.hasError('maxlength')">
{{ 'labels.commons.Password should not be more than' | translate }}
<strong>{{ 'labels.commons.50 characters long' | translate }}</strong>
</mat-error>
<mat-error
*ngIf="
userForm.get('password')?.hasError('pattern') &&
!userForm.get('password')?.hasError('minlength') &&
!userForm.get('password')?.hasError('maxlength')
"
>
{{ 'labels.commons.Password should include a' | translate }}
<strong>{{ 'labels.commons.numeral' | translate }}</strong>
{{ 'labels.commons.and at' | translate }}
<strong>{{ 'labels.commons.least one uppercase' | translate }}</strong
>,
<strong>{{ 'labels.commons.lowercase and special character' | translate }}</strong>
</mat-error>
</mat-form-field>
<!-- Repeat password -->
<mat-form-field class="flex-48">
<mat-label>{{ 'labels.inputs.Repeat Password' | translate }}</mat-label>
<input matInput type="password" formControlName="repeatPassword" required />
<mat-error *ngIf="userForm.get('repeatPassword')?.hasError('required')">
{{ 'labels.inputs.Password' | translate }} {{ 'labels.commons.is' | translate }}
<strong>{{ 'labels.commons.required' | translate }}</strong>
</mat-error>
</mat-form-field>
<!-- Passwords do not match -->
<p
class="flex-98 reset-password-error"
*ngIf="
userForm.errors?.passwordsDoNotMatch &&
!userForm.get('password')?.hasError('required') &&
!userForm.get('repeatPassword')?.hasError('required')
"
>
{{ 'labels.inputs.Passwords' | translate }}
<strong>{{ 'labels.commons.do not match' | translate }}</strong>
</p>
<!-- Roles -->
<mat-form-field class="flex-20">
<mat-label>{{ 'labels.inputs.Roles' | translate }}</mat-label>
<mat-select formControlName="roles" required multiple>
<mat-option *ngFor="let role of rolesData" [value]="role.id">
{{ role.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="userForm.controls.roles.hasError('required')">
{{ 'labels.commons.At least one role' | translate }}
<strong>{{ 'labels.commons.must be selected' | translate }}</strong>
</mat-error>
</mat-form-field>
</div>
</mat-card-content>
<mat-card-actions class="layout-row align-center gap-5px responsive-column">
<button type="button" mat-raised-button [routerLink]="['../']">
{{ 'labels.buttons.Cancel' | translate }}
</button>
<button mat-raised-button color="primary" [disabled]="userForm.invalid">
{{ 'labels.buttons.Submit' | translate }}
</button>
</mat-card-actions>
</form>
</mat-card>
</div>
<ng-template #templateUserFormRef let-popover="popover">
<h2>{{ 'labels.heading.Create User' | translate }}</h2>
<p class="mw400">
{{ 'labels.text.Filling Details' | translate }}:
<a href="https://mifosforge.jira.com/wiki/spaces/docs/pages/67141740/Users" target="_blank">{{
'labels.inputs.Users' | translate
}}</a>
</p>
<div class="layout-row align-end gap-2px responsive-column">
<button mat-raised-button color="warn" (click)="popover.close(); configurationWizardService.closeConfigWizard()">
{{ 'labels.buttons.Close' | translate }}
</button>
<button mat-raised-button color="primary" (click)="popover.close()">
{{ 'labels.buttons.Create User' | translate }}
</button>
<button mat-raised-button color="primary" (click)="popover.close(); previousStep()">
{{ 'labels.buttons.Back' | translate }}
</button>
<button mat-raised-button color="primary" (click)="popover.close(); nextStep()">
{{ 'labels.buttons.Next' | translate }}
</button>
</div>
</ng-template>
@@ -0,0 +1,13 @@
.password-never-expires-wrapper {
padding: 17.5px 0;
}
.send-password-to-email-wrapper {
padding: 17.5px 0;
}
.reset-password-error {
color: #f44336;
font-size: 80%;
margin: 0;
}
@@ -0,0 +1,24 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CreateUserComponent } from './create-user.component';
describe('CreateUserComponent', () => {
let component: CreateUserComponent;
let fixture: ComponentFixture<CreateUserComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CreateUserComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CreateUserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,353 @@
/** Angular Imports */
import { Component, OnInit, TemplateRef, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import {
UntypedFormGroup,
UntypedFormBuilder,
UntypedFormControl,
Validators,
ReactiveFormsModule
} from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
/** Custom Services */
//import { UsersService } from '../users.service';
import { UsersServiceZitadel } from '../usersZitadel.service';
import { PopoverService } from '../../../configuration-wizard/popover/popover.service';
/** Custom Dialog Component */
import { PasswordsUtility } from 'app/core/utils/passwords-utility';
import { confirmPasswordValidator } from 'app/login/reset-password/confirm-password.validator';
import { ConfigurationWizardService } from 'app/configuration-wizard/configuration-wizard.service';
import { ContinueSetupDialogComponent } from 'app/configuration-wizard/continue-setup-dialog/continue-setup-dialog.component';
import { UsersService } from 'app/users/users.service';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { COUNTRY_CODES } from 'app/zitadel/constants/coutry-codes';
import { ZITADEL_LANGUAGES } from 'app/zitadel/constants/languages';
/**
* Create user component.
*/
@Component({
selector: 'mifosx-create-user',
templateUrl: './create-user.component.html',
styleUrls: ['./create-user.component.scss'],
standalone: true,
imports: [
...STANDALONE_SHARED_IMPORTS
]
})
export class CreateUserComponent implements OnInit, AfterViewInit {
/** User form. */
userForm: UntypedFormGroup;
/** Offices data. */
officesData: any;
/** Roles data. */
rolesData: any;
/** Staff data. */
staffData: any;
/** Country Codes */
countryCodes = COUNTRY_CODES;
/** Language Codes */
languageCodes = ZITADEL_LANGUAGES;
/* Reference of create user form */
@ViewChild('userFormRef') userFormRef: ElementRef<any>;
/* Template for popover on create user form */
@ViewChild('templateUserFormRef') templateUserFormRef: TemplateRef<any>;
/**
* Retrieves the offices and roles data from `resolve`.
* @param {FormBuilder} formBuilder Form Builder.
* @param {UsersServiceZitadel} UsersService Users Service.
* @param {ActivatedRoute} route Activated Route.
* @param {Router} router Router for navigation.
* @param {ConfigurationWizardService} configurationWizardService ConfigurationWizard Service.
* @param {PopoverService} popoverService PopoverService.
*/
constructor(
private formBuilder: UntypedFormBuilder,
private usersService: UsersServiceZitadel,
private usersService2: UsersService,
private route: ActivatedRoute,
private router: Router,
private popoverService: PopoverService,
private configurationWizardService: ConfigurationWizardService,
private dialog: MatDialog,
private passwordsUtility: PasswordsUtility
) {
this.route.data.subscribe((data: { usersTemplate: any }) => {
this.officesData = data.usersTemplate.allowedOffices;
this.rolesData = data.usersTemplate.availableRoles;
});
}
/**
* Creates the user form, sets the staff data and conditional controls of the user form.
*/
ngOnInit() {
this.createUserForm();
this.setStaffData();
this.setConditionalControls();
}
/**
* Creates the user form.
*/
createUserForm(): void {
this.userForm = this.formBuilder.group(
{
username: [
'',
Validators.required
],
email: [
'',
[
Validators.required,
Validators.email
]
],
firstName: [
'',
Validators.required
],
lastName: [
'',
Validators.required
],
preferredLanguage: [
'',
Validators.required
],
gender: [
'',
Validators.required
],
countryCode: [
'+1',
Validators.required
],
phoneNumber: [
'',
[
Validators.required,
Validators.pattern(/^[0-9]{7,15}$/)]
],
password: [
'',
[
Validators.required,
Validators.minLength(12),
Validators.maxLength(50),
Validators.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).+$/)]
],
repeatPassword: [
'',
Validators.required
],
roles: [
'',
Validators.required
],
officeId: [
'',
Validators.required
],
staffId: ['']
},
{ validators: confirmPasswordValidator }
);
}
/**
* Sets the staff data each time the user selects a new office
*/
setStaffData() {
this.userForm.get('officeId').valueChanges.subscribe((officeId: string) => {
this.staffData = [];
this.usersService2.getStaff(officeId).subscribe((staff: any) => {
this.staffData = staff;
});
});
}
/**
* Sets the conditional controls of the user form
*/
setConditionalControls() {
this.userForm.get('sendPasswordToEmail').valueChanges.subscribe((sendPasswordToEmail: boolean) => {
const passwordControl = this.userForm.get('password');
const repeatPasswordControl = this.userForm.get('repeatPassword');
if (sendPasswordToEmail) {
passwordControl.disable();
repeatPasswordControl.disable();
this.userForm.get('email')?.setValidators([
Validators.required,
Validators.email
]);
} else {
passwordControl.enable();
repeatPasswordControl.enable();
this.userForm.get('email')?.setValidators([Validators.email]);
}
this.userForm.get('email')?.updateValueAndValidity();
});
}
/**
* Submits the user form and creates user,
* if successful redirects to view created user.
*/
submit() {
const fullForm = this.userForm.value;
const fullPhone = `${fullForm.countryCode}${fullForm.phoneNumber}`;
const password = `${fullForm.repeatPassword}`;
const givenName = `${fullForm.firstName}`;
const familyName = `${fullForm.lastName}`;
const nickName = `${fullForm.username}`;
const user = {
...fullForm,
phone: fullPhone,
password: password,
givenName: givenName,
familyName: familyName,
nickName: nickName,
displayName: `${fullForm.firstName} ${fullForm.lastName}`
};
const dataOffi = {
officeId: fullForm.officeId,
staffId: fullForm.staffId
};
const selectedRoleIds = this.userForm.get('roles')?.value;
delete user.officeId;
delete user.staffId;
delete user.roles;
delete user.countryCode;
delete user.phoneNumber;
delete user.repeatPassword;
delete user.firstName;
delete user.lastName;
this.usersService.createUser(user).subscribe((response: any) => {
const userId = response.object?.userId;
if (userId) {
const body = {
id: userId,
officeId: dataOffi.officeId,
staffId: dataOffi.staffId,
username: user.nickName,
firstname: user.givenName,
lastname: user.familyName,
roleIds: selectedRoleIds || []
};
this.usersService.createUserBd(body).subscribe(
(response: any) => {
if (selectedRoleIds?.length > 0) {
this.usersService.assignRolesToUser(userId, selectedRoleIds).subscribe(
() => {
if (this.configurationWizardService.showUsersForm === true) {
this.configurationWizardService.showUsersForm = false;
this.openDialog();
} else {
this.router.navigate(['/appusers']);
}
},
(error) => {
console.error('Failed to assign roles to user:', error);
}
);
} else {
console.warn('No roles were selected for this user.');
}
},
(error) => {
console.error('Failed to create user record in database:', error);
}
);
} else {
console.error('User creation failed: userId not returned by API.');
}
});
}
/**
* Popover function
* @param template TemplateRef<any>.
* @param target HTMLElement | ElementRef<any>.
* @param position String.
* @param backdrop Boolean.
*/
showPopover(
template: TemplateRef<any>,
target: HTMLElement | ElementRef<any>,
position: string,
backdrop: boolean
): void {
setTimeout(() => this.popoverService.open(template, target, position, backdrop, {}), 200);
}
/**
* To show popover.
*/
ngAfterViewInit() {
if (this.configurationWizardService.showUsersForm === true) {
setTimeout(() => {
this.showPopover(this.templateUserFormRef, this.userFormRef.nativeElement, 'top', true);
});
}
}
/**
* Next Step (Maker Checker Tasks System Page) Configuration Wizard.
*/
nextStep() {
this.configurationWizardService.showUsersForm = false;
this.configurationWizardService.showMakerCheckerTable = true;
this.router.navigate(['/system']);
}
/**
* Previous Step (Users page) Configuration Wizard.
*/
previousStep() {
this.configurationWizardService.showUsersForm = false;
this.configurationWizardService.showUsersList = true;
this.router.navigate(['/appusers']);
}
/**
* Opens dialog if the user wants to create more users.
*/
openDialog() {
const continueSetupDialogRef = this.dialog.open(ContinueSetupDialogComponent, {
data: {
stepName: 'user'
}
});
continueSetupDialogRef.afterClosed().subscribe((response: { step: number }) => {
if (response.step === 1) {
this.configurationWizardService.showUsersForm = false;
this.router.navigate(['../'], { relativeTo: this.route });
} else if (response.step === 2) {
this.configurationWizardService.showUsersForm = true;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate(['/organization/users/create']);
} else if (response.step === 3) {
this.configurationWizardService.showUsersForm = false;
this.configurationWizardService.showMakerCheckerTable = true;
this.router.navigate(['/system']);
}
});
}
}