Créez un service de générateur de mot de passe appelé PassswordGeneratorService
import { Injectable } from '@angular/core';
@Injectable()
export class PasswordGeneratorService {
generatePassword(length:number,upper:boolean,numbers:boolean,symbols:boolean) {
const passwordLength = length || 12;
const addUpper = upper;
const addNumbers = numbers;
const addSymbols = symbols;
const lowerCharacters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const upperCharacters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const symbols = ['!', '?', '@'];
const getRandom = array => array[Math.floor(Math.random() * array.length)];
let finalCharacters = '';
if (addUpper) {
finalCharacters = finalCharacters.concat(getRandom(upperCharacters));
}
if (addNumbers) {
finalCharacters = finalCharacters.concat(getRandom(numbers));
}
if (addSymbols) {
finalCharacters = finalCharacters.concat(getRandom(symbols));
}
for (let i = 1; i < passwordLength - 3; i++) {
finalCharacters = finalCharacters.concat(getRandom(lowerCharacters));
}
return finalCharacters.split('').sort(() => 0.5 - Math.random()).join('');
}
}
n'oubliez pas d'ajouter le service sur le module que vous utilisez
@NgModule({
imports: [
CommonModule,
SharedModule,
CommonModule,
RouterModule.forChild(routes),
FormsModule,
ReactiveFormsModule,
FlexLayoutModule,
TranslateModule,
ExistingUserDialogModule,
UserDocumentsUploadDialogModule
],
declarations: [
UserListComponent,
EditUserDialogComponent,
UserEditorComponent
],
entryComponents: [
EditUserDialogComponent
],
providers: [
AuthService,
PasswordGeneratorService
]
})
export class UsersModule {
}
Sur votre contrôleur, ajoutez une méthode qui appelle la méthode de génération de mot de passe dans le service et définissez le résultat dans le champ de mot de passe
constructor(
private passwordGenerator: PasswordGeneratorService,
)
get newPassword() {
return this.password.get('newPassword');
}
generatePassword() {
this.newPassword.setValue(this.passwordGenerator.generatePassword(8,true,true,true));
}