How to add new users to different roles on the fly
Sometimes there might be a need to add your users to different roles, depending on certain invitations, at registration time. Is that possible in Community Server (CS)?
Well, in this case CSModules can be your friend as in many other situations. The other day there was a request for this functionality in the CSOrg Forums. I thought it would be an interesting case to do some sample code for a CSModule that did this by reading an argument from the query string.
You might think that this could be done with a new drop down field on the registration page. Well , you're right, but in this case that was requested the user should not be able to choose their own role. The role should be decided by a person that invited the user. So it should probably be a link in an e-mail or similar.
My thinking was that you would put an RoleID as an argument in the query string, like:
http://<your server>/CreateUser.aspx?roleid=<RoleID>
Then design a CSModule that would read the QueryString and add the user to that role within the PreUserUpdate event.
First register for the PreUserUpdate event. (Sorry for the pictures not looking as good or acting as they should, but my QGyen Flickr CSModule has suddenly stopped working. Click on the pictures to see them in original size.)
Visual Basic
C#
After that we handle the reading of the querystring, check if it is an existing role that is not one of the built-in roles. We wouldn't want anyone guessing the roleID of the Administrators role and register themselves as Admins. Lastly if all validations are ok, add the user to the desired role.
Visual Basic
C#
This is a sample on how you could do it. I haven't put much more thought on the security aspects of it, more that making sure no one adds himself to the admin (or other high permission) role. If you have feedback on how the security could be increased on this CSModule please post a comment.
Download it from here and try it out! I have included the source code in this download (VB and C#).
If you enjoyed this post Subscribe to my feed via RSS or e-mail!