Automatically selecting a role in User Management

I’d like to add a function to the user management component to automatically select the “Viewer” role of a user if it wasn’t selected during creation. “Viewer” is the minimum required role for users to interact with our windows, but in the case that someone forgot to select that box, I still want it to append that role to the new user. I’m assuming this can be done with the onCreateUser or onSaveUser function in component scripting but I’ve tried a few things and can’t get it to work. Any ideas?

This is what I have right now that isn’t working:

def onCreateUser(self, saveContext):
	user = saveContext.getUser()
	roles = list(user.getRoles())
	if "Viewer" not in roles:
		roles.append("Viewer")
		user.setRoles(roles)
	saveContext.setUser(user)

Exactly like that?

The Python language uses "semantic whitespace", meaning that the way your code is indented is critical to its functionality (instead of adding curly braces around blocks as other languages do).

Your snippet won't do anything because it's not valid code unindented, but with the indentation fixed it looks plausible:

def onCreateUser(self, saveContext):
	user = saveContext.getUser()
	roles = list(user.getRoles())
	if "Viewer" not in roles:
		roles.append("Viewer")
	user.setRoles(roles)

	saveContext.setUser(user)

But now I'm further confused, because the saveContext does not have any get or set user function.

I'm going to go with a hunch here and say as a preemptive word of advice - don't trust LLMs for help with Ignition scripting, because they lack sufficient context to be helpful.
You'll get, at best, way too much code (because they really like to write code) that might accomplish your immediate goal but is going to lead you to problems down the line, and at worst outright hallucinations that make you spin your wheels wasting your time.

The only capability you have within the onCreateUser extension function is to prevent the creation of the user. If you want to modify the user before it's created silently, you need to use onSaveUser.
Your function becomes as simple as this:

def onSaveUser(self, saveContext, user):
	if "Viewer" not in user.roles:
		user.addRole("Viewer")
2 Likes

Oops, I did have the indentation right on my end. It just didnt carry over when I did the preformatted text option on here. It’s now reflecting what I had in ignition. As far as LLMs go, they definitely lack a lot of context regarding ignition but have been extremely helpful with getting the skeletal functionality of what I'm looking for. Then I can usually figure it out from there. I always struggle to find proper documentation that can show what exactly can be done to a certain function.

As far as the function goes, I added the one you included and it worked. Thank you so much