generatePassword method
Generate a new password.
length
is by default equal to 15
distribution
define the number of characters per collection
It can throw StateError if the list of collection is empty
Implementation
Password generatePassword(
{num length = 15,
Map<String, int>? distribution,
List<String>? excludeItems}) {
final buffer = <String>[];
final tmpCollectionsPasswordItem = _removeExcludedItems(excludeItems);
final num collectionsLength = tmpCollectionsPasswordItem.length;
if (tmpCollectionsPasswordItem.isEmpty) {
throw Exception(
'To generate a password, instance needs at least one collection of '
'password items. You may use PasswordService.latinBase() or '
'addCollectionOfPasswordItems().');
}
final slice = length ~/ collectionsLength;
var reminder = length % collectionsLength;
tmpCollectionsPasswordItem.forEach((key, collection) => {
if (distribution != null && distribution.isNotEmpty)
{
buffer.addAll(_buildPassword(collection,
distribution.containsKey(key) ? distribution[key]! : 0))
}
else
{
buffer.addAll(_buildPassword(collection, slice + reminder)),
reminder = 0
}
});
buffer.shuffle(_rand);
final password = Password(
buffer,
tmpCollectionsPasswordItem.values.fold(
0, (previousValue, element) => previousValue += element.length));
if (buffer.any((e) => 1 < e.length)) {
// Set default separator to be a space, since password is not just made
// up of single letters.
//
// For this to work consistently, collections must always entirely
// contain only single letters, or entirely contain strings with
// two or more characters. Never a mixture of single character strings
// and multiple character strings. A better solution is to track
// characters vs words as a property of each collection.
password.separator = ' ';
}
return password;
}