Search code examples
c#.netservicestackhttpserver

ServiceStack Service OnUnsubscribe\OnSubscribe\OnConnect user DisplayName is wrong


In my service stack I have the following AuthRepository initialization:

var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);

string hash;
string salt;
var pwd = "ValidPassword";

new SaltedHash().GetHashAndSaltString(pwd, out hash, out salt);
userRep.CreateUserAuth(new UserAuth
{
    Id = 1,
    DisplayName = "CustomDisplayName",
    Email = "test@gmail.com",
    UserName = "CustomUserName",
    FirstName = "FirstName",
    LastName = "LastName",
    PasswordHash = hash,
    Salt = salt,
}, pwd);

And in the same service I have some Event handlers:

private void OnUnsubscribe(IEventSubscription obj)
{
    Console.WriteLine(obj.DisplayName + " has unsubbed\n");
}

private void OnSubscribe(IEventSubscription obj)
{
    Console.WriteLine(obj.DisplayName + " has subbed\n");
}

private void OnConnect(IEventSubscription obj, Dictionary<string, string> dict)
{
    Console.WriteLine(obj.DisplayName + " has connected\n");
}

The thing is that my obj.DisplayName is CustomUserName instead of being CustomDisplayName (and obj.UserName is also CustomUserName). Is this how it should work? If yes - how can I change DisplayName? Currently I use default CredentialsAuthProvider


Solution

  • For Authenticated users the ServerEvents feature uses the session.UserName if it exists since it's unique, if one isn't defined it falls back to the users DisplayName.

    You can use the ServerEventsFeature.OnCreated() custom hook to change the custom metadata returned to Server Events client, e.g. You can change the displayName returned with:

    Plugins.Add(new ServerEventsFeature
    {
        OnCreated = (sub, req) => {
            sub.Meta["displayName"] = req.GetSession().DisplayName;
        }
    });