Generate TagID with 8 bytes in Hex
MODIFY
src/server/rest/v1/service/AuthService.ts
src/server/rest/v1/service/AuthService.ts
@@ -194,7 +194,7 @@ export default class AuthService {
// Create default Tag
if (tenant.id !== Constants.DEFAULT_TENANT_ID) {
const tag: Tag = {
- id: Utils.generateTagID(newUser.name, newUser.firstName),
+ id: await TagStorage.findAvailableID(tenant),
active: true,
issuer: true,
userID: newUser.id,

MODIFY
src/storage/mongodb/TagStorage.ts
src/storage/mongodb/TagStorage.ts
@@ -7,6 +7,7 @@ import DatabaseUtils from './DatabaseUtils';
import DbParams from '../../types/database/DbParams';
import Logging from '../../utils/Logging';
import { ObjectId } from 'mongodb';
+import { ServerAction } from '../../types/Server';
import Tenant from '../../types/Tenant';
import Utils from '../../utils/Utils';
import moment from 'moment';
@@ -14,6 +15,28 @@ import moment from 'moment';
const MODULE_NAME = 'TagStorage';
export default class TagStorage {
+ public static async findAvailableID(tenant: Tenant): Promise<string> {
+ const startTime = Logging.traceDatabaseRequestStart();
+ DatabaseUtils.checkTenantObject(tenant);
+ let existingTag: Tag;
+ do {
+ // Generate new transaction ID
+ const id = Utils.generateTagID();
+ existingTag = await TagStorage.getTag(tenant, id);
+ if (existingTag) {
+ await Logging.logWarning({
+ tenantID: tenant.id,
+ module: MODULE_NAME, method: 'findAvailableID',
+ action: ServerAction.TAG_CREATE,
+ message: `Tag ID '${id}' already exists, generating a new one...`
+ });
+ } else {
+ return id;
+ }
+ } while (existingTag);
+ await Logging.traceDatabaseRequestEnd(tenant, MODULE_NAME, 'findAvailableID', startTime, {});
+ }
+
public static async saveTag(tenant: Tenant, tag: Tag): Promise<void> {
const startTime = Logging.traceDatabaseRequestStart();

MODIFY
src/utils/Utils.ts
src/utils/Utils.ts
@@ -279,20 +279,8 @@ export default class Utils {
return data.slice(data.length - 5, data.length);
}
- public static generateTagID(name: string, firstName: string): string {
- let tagID = '';
- if (name && name.length > 0) {
- tagID = name[0].toUpperCase();
- } else {
- tagID = 'S';
- }
- if (firstName && firstName.length > 0) {
- tagID += firstName[0].toUpperCase();
- } else {
- tagID += 'F';
- }
- tagID += Utils.getRandomIntSafe();
- return tagID;
+ public static generateTagID(size = 8): string {
+ return [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('').toUpperCase();
}
public static isIterable(obj: any): boolean {

Generate TagID with 8 bytes in Hex