KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Creating a New User Programmatically
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: March 26, 2018

4D allows for the programmatic creation of a new user, which can be very useful when designing a database. Tracking of the logged in user is vital to maintain data integrity so that updates to the data are logged with the correct user, allowing for back-tracking of changes and proper audits.

The 4D command Set user properties, documentation here, is the command to look at for this task. For example, say there is a user "Jake_Blake", who does not have a login and needs to have a new user created. Creating the user is as simple as calling the Set user properties command and passing in the name and password.

For example, creating this user from Administrator would go something like this:

Set user properties(-2;$Username;"";$Password;1;Current date(*))

Often then, after creating a new user, it will be necessary (or desired) to immediately log in as that new user. It would seem obvious that this could be done simply as:

Set user properties(-2;$Username;"";$Password;1;Current date(*))
CHANGE CURRENT USER($Username;$Password)

However, this will not work! Due to a slight timing issue, creating the new user and then logging in as the new user immediately after will present with an error if done in the above manner. The error looks something like this:



This is not a bug in 4D, rather it reflects the timing of the creation of the new user. The server has to add the new user to the list, then return the full list of users back which, although very fast, is not as fast as moving to the next line in the code.

To get around this, the DELAY PROCESS command can be used to add a small delay between the creation and logging in of the new user, for example:

Set user properties(-2;$Username;"";$Password;1;Current date(*))
DELAY PROCESS(Current process;30)
CHANGE CURRENT USER($Username;$Password)

This will work because the process is given enough time for the newly added user to be added, but timing needs to be taken into account and the "30" in the above code may need to be adjusted to best fit the database where the code lives, as "30" may be either too short (which will still then cause the error) or too long (which just wastes time).