Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Daniela 2 posts 72 karma points
    Feb 26, 2020 @ 08:48
    Daniela
    0

    Can't access user's groups in the code

    Hi guys, I'm new on the forum and so glad to be here :) I'm building an application in Umbraco 8, I implemented a user events handler as I must do something after the user has been created and I need to retrieve the groups the user belongs to. I implemented a userSaved event handler so that I can get its info immediately after it has been created, when I check the groups though, they are not there: user.Groups is empty but the User has been added to at least one group (and I can see the data stored in the db and in the User details page). So I thought maybe there was some method I could use in the sender (IUserService) but I could not find anything, so I thought maybe I could find info in the role itself, so I get the list of roles and loop through them but no, in the role there only is the user count property. Any idea on how I can get this info? I will have to make a call directly to the db to overcome this issue but I would much more prefer to avoid it. Any help is very welcome, thank you :)

    --------------- update --------------

    I just found this method "sender.GetAllInGroup", so loaded all the groups, looped through them, invoked that method for each group and check my User belongs to it, the user does not belong (yet) to any of them. While still debugging I checked the db and the user is not there, this means there's something updating the "umbracoUser2UserGroup" table in the db after the "user saved" event. Any idea?

  • Daniela 2 posts 72 karma points
    Feb 26, 2020 @ 12:20
    Daniela
    0

    Ok I reply to my own question in case anybody has the same need as I found a way to get the Roles at the user saved event (although I hope there's a better way to do it). The event handler is hit 3 times, I think there are other jobs running updating the user other two times, I think the third update is about the Roles as at that point I can see them. So this is what I did: I check the user is new in this way:

    var dirty = (IRememberBeingDirty)user;
    var isNew = dirty.WasPropertyDirty("Id");
    

    The second and third time the User will no more be "new" so I can check that it's still "Inactive" and "has groups":

    if(isNew)
    {
    ...dosomething
    }
     else if(user.UserState == UserState.Inactive && user.Groups.Any())
    {
    ...do something else
    }
    

    So this is "a" way, if anybody has a better way to do it, I'd be more than happy to learn it, ideally by catching one of the other two events maybe?

Please Sign in or register to post replies

Write your reply to:

Draft