Random password on opportunity form

Today I had to generate a random password for new opportunities at a customer site. Basically it’s part of a free trial programme – when a sales guy adds a new opportunity they grant access to the services offered by the Company for a limited period of time. So we added a field to the opportunity form and pre-fill it with random chars on load.

The code below will set til field new_onetimepassword to a pseudo random string (lowercase, uppercase, numbers and specials) of a random length (14 to 20 chars total) and set the value of new_onetimepassword accordingly.

 

function OnLoad() {

   var formType = Xrm.Page.ui.getFormType();

   if (formType == 1) // create

    {

        Xrm.Page.getAttribute(“pa_onetimepassword”).setValue(GenerateRandomPassword());

    }

}

function GenerateRandomPassword() {

   var specials = ‘!@#$%&*()_-+{}:”<>?\[];,./’;

   var lowercase = ‘abcdefghijklmnopqrstuvwxyz’;

   var uppercase = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’;

   var numbers = ‘0123456789’;

   var all = specials + lowercase + uppercase + numbers;

   var password = ;

    password += specials.pick(1);

    password += lowercase.pick(1);

    password += uppercase.pick(1);

    password += numbers.pick(1);

    password += all.pick(10, 16);

    password = password.shuffle();

   return password;

}

String.prototype.pick = function (min, max) {

   var n, chars = ;

   if (typeof max === ‘undefined’) {

        n = min;

    }

 else {

        n = min + Math.floor(Math.random() * (max – min));

    }

 for (var i = 0; i < n; i++) {

        chars += this.charAt(Math.floor(Math.random() * this.length));

    }

   return chars;

};

// Credit to @Christoph: http://stackoverflow.com/a/962890/464744

String.prototype.shuffle = function () {

   var array = this.split();

   var tmp, current, top = array.length;

   if (top) while (–top) {

        current = Math.floor(Math.random() * (top + 1));

        tmp = array[current];

        array[current] = array[top];

        array[top] = tmp;

    }

   return array.join();

};

 

Credits to @Blender: http://stackoverflow.com/users/464744/blender for a nice random password implementation.