Freemarker (ftl) access to KC database

Hello. Anyone know if its possible to access the (KC) user database from the theme’s registration.ftl page? Or to test for existing username from within that page?

I’m modifying the User Registration process so that the username field is set to a pre-assigned, server-generated value and not solicited from the user. This means the username field is to be
A) disabled (to user input) and pre-assigned with a value
B) that value to be generated by a simple algorithm/formula (on the server side) and
C) ensure the value doesn’t already exist as a registered username in KC (and if it does, then obtain another candidate value using B above and repeat)

I’ve achieved A&B with simple changes to theme/mytheme/register.ftl (with HTML, Freemarker and Javascript). But I’m scratching my head over how to do part-C.
I guess I’m looking for a way for the register.ftl page to test if a username is already taken.
It could check the database (of usernames) or perhaps invoke an existing validate() type function?
Thanks in advance.

PS. Bonus points if there is also a way to save this value in the HTTP Session associated with the registration process because I don’t want to pull the pre-assigned value back out of a submitted http form since that creates a vulnerability (allowing client to modify value).

In order to have access to the Keycloak database, you’d have to do it on the Java side. You should override RegistrationPage (keycloak/RegistrationPage.java at master · keycloak/keycloak · GitHub). You could generate your username there, check it against the database, and then put it in the .ftl scope via the LoginFormsProvider.

Let us know if you have specific questions as you get into it.