Skip to content

User Management

Introduction

If you have configured your application, you can start using GetSocial without any additional steps. GetSocial creates anonymous user by default, so you can access all the features right after SDK gets initialized.

Anonymous user is just a user, that has no identities added. User is created per device and stays there for next sessions. Anonymous users have default names like “User 12345678”, but you can change it using GetSocial.User.SetDisplayName method.

To check if user is anonymous use GetSocial.User.IsAnonymous.

Login

If you have internal login system or use any social authentication, you should connect your account to GetSocial user, so you can retrieve the same GetSocial user from another devices or recover it once app was reinstalled or user was logged out.

To connect GetSocial user with yours, you should add your identity to GetSocial user.

Identities

An identity is some unique user data to identify them among other users. You can use any auth provider to create an identity (your custom login, facebook, twitter, google, github, etc). Each user may have any number of different identities, but only one of the same provider. It means that you may attach one facebook, one twitter and one custom identity, but you can not attach two facebook identities. Read more how to attach multiple identities.

To create an identity, use AuthIdentity.CreateFacebookIdentity(fbAccessToken) for Facebook or AuthIdentity.CreateCustomIdentity(providerId, userId, accessToken) for any other provider, where:

  • providerId is a unique string defined by you for each provider (twitter, my_auth_system, gamecenter, etc).
  • userId is a unique string for each user in the provided authentication system. So pair providerId-userId is unique for each user and helps GetSocial identify a user if them try to login from another device.
  • accessToken is a string for security check, that could be some internal hash function in your app based on userId. If user is trying to authenticate again with the same providerId and userId, but different accessToken - GetSocial won’t allow to authenticate. accessToken can not be changed.

Add Identity

You have to add an identity to GetSocial user in the success callback of your authentication system.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void OnLoginSuccess() {
    string userId = GetCurrentUserId(); // get user ID on your login provider
    string accessToken = CalculateAccessTokenForUser(userId); // see the example of such a function below
    AuthIdentity identity = AuthIdentity.CreateCustomIdentity("my_auth_system", userId, accessToken);

    GetSocial.User.AddAuthIdentity(identity,
            () =>
            {
                Debug.Log("Successfully logged into user " + userId);
            },
            error =>
            {
                Debug.Log("Failed to log into user " + userId + ", error:" + error);
            },
            conflictUser =>
            {
                HandleConflict(identity, conflictUser);
            });
}

// it should be always the same for the same value, so GetHashCode method perfectly fits to this job, but you can introduce something more advanced
public static string CalculateAccessTokenForUser(string userId) {
    return userId.GetHashCode().ToString();
}

Add Facebook Identity

To add Facebook identity, you should provide the token you got from Facebook SDK after user’s authentication.

  1. Integrate Facebook Unity SDK into your app as described in the Official Guide.

  2. Add Facebook identity to GetSocial user. Sample code is below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
FB.Init(() => {
    var permissions = new List<string>(){"public_profile", "user_friends"}; // We need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
    FB.LogInWithReadPermissions(permissions, result => {
        if (FB.IsLoggedIn) {
            var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
            var authIdentity = AuthIdentity.CreateFacebookIdentity(aToken.TokenString);
            GetSocial.User.AddAuthIdentity (authIdentity, OnSuccess, OnError, OnConflict);
        } else {
            Debug.Log("User cancelled login");
        }
    });
});

For Facebook, we will retrieve the list of Facebook friends and import them to Social Graph, so you can get list of user’s friends through GetSocial.

GetSocial doesn’t automatically sync your Facebook profile info

Don’t forget to sync the display name and avatar of the GetSocial user with the values from Facebook. You can do it with a batch update to make it in one call.

Handle Conflicts

Besides onSuccess and onFailure callbacks, AddAuthIdentity has onConflict. Conflict happens when identity you’re trying to add is already attached to one of GetSocial users. It may happen when:

  • User has already logged in on another device.
  • User reinstalled the application.
  • User cleared application data.

Depending on the user intention and your application logic, you can choose one of the following strategies to resolve the conflict:

Strategy 1: stay with current user and don’t add identity:

1
2
3
4
5
void HandleConflict(AuthIdentity identity, ConflictUser conflictUser)
{
    // Do nothing in onConflict and user will stay the same.
    // Identity won't be added to any of the users.
}

Strategy 2: switch to conflict user:

1
2
3
4
5
6
7
void HandleConflict(AuthIdentity identity, ConflictUser conflictUser)
{
    // Call switchUser to replace current user with conflict one and add identity to conflict user.
    // After the successful switch, current user and his referral data will be lost. 
    // To save the data: 1. copy data to intermediate variables; 2. save in to the conflict user properties after the successful switch.
    GetSocial.User.SwitchUser(identity, completionCallback);
}

Logout

If your users can log out of your app, you should log out of GetSocial user too. Otherwise it will stay the same and will have connection with another user that will login after.

1
2
3
4
5
void OnLogoutSuccess()
{
    // New anonymous will be created. If your current user is anonymous - it will be lost.
    GetSocial.User.reset(OnSuccess, OnError);
}

If you’re subsribed to GetSocial user change then your callback will be invoked.

Change Logged In User

If you want to switch from one logged in user to another, do Logout first and then Login with a new user.

Warning

Don’t forget to do the logout, it is important to keep your user connected with proper GetSocial user, so you will receive correct analytics and referral data.

Manage User Profile

Display Name

Check current username with GetSocial.User.DisplayName method. To update display name use GetSocial.User.SetDisplayName(newDisplayName, OnSuccess, OnError).

Avatar

Get current avatar URL with GetSocial.User.AvatarUrl method. You can set a new avatar in two ways:

  • Set a URL - GetSocial.User.SetAvatarUrl(avatarUrl, OnSuccess, OnError).
  • Set a Texture2D object - GetSocial.User.SetAvatar(texture2dAvatar, OnSuccess, OnError). Recommended size is 300x300 px, bigger images will be automatically downscaled.

User Properties

Custom properties are string to string dictionary of any information your want to store.

There’re some limitations about properties:

  • Max key length is 32 symbols.
  • Max value length is 1024 symbols.
  • Min value length is 1 symbol, you can not set an empty property, it will just remove a current value if it exists.

There are Public and Private properties. Private properties are accessible only by current user with methods listed in GetSocial.User class, Public can be accessed by other users with methods from PublicUser object.

Private Properties

To set a private property:

1
2
3
4
5
6
7
8
9
GetSocial.User.SetPrivateProperty(key, value,
    () =>
    {
        Debug.Log("Successfully set private property");
    },
    error =>
    {
        Debug.Log("Failed to set private property, error:" + error);
    });

In case if user already had a value for a current key, it will be overriden. You can prevent it with checking if property already exists:

1
bool hasPrivateProperty = GetSocial.User.HasPrivateProperty(key);

You can get the current property value:

1
string currentValue = GetSocial.User.GetPrivateProperty(key);

If you’re not interesting in keeping property for a user, remove it:

1
2
3
4
5
6
7
8
9
GetSocial.User.RemovePrivateProperty(key, value,
    () =>
    {
        Debug.Log("Successfully removed private property");
    },
    error =>
    {
        Debug.Log("Failed to remove private property, error:" + error);
    });

You can get all properties as unmodifiable copy of origin map:

1
Dictionary<string, string> userProperties = GetSocial.User.AllPrivateProperties;

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Public Properties

You have similar methods to work with public properties, as for private ones:
SetPublicProperty, GetPublicProperty, HasPublicProperty and RemovePublicProperty.

In addition to this, Public properties are visible for other users, so if you have some PublicUser entity, you can get his public properties:

1
string value = user.GetPublicProperty(key);

Or, you can check does user have a property:

1
bool hasProperty = user.HasPublicProperty(key);

You can get all properties as unmodifiable copy of origin map:

1
Dictionary<string, string> userProperties = GetSocial.User.AllPublicProperties;

Note

You can not modify properties with this map. Also, changes in user properties won’t affect your copy, so you need to refresh it after any user changes. To have up-to-date information, we suggest to use GetSocial SDK methods.

Batch Properties Update

If you want to perform multiple updates of user data, you can do it with UserUpdate class. It allows you update few user properties(custom and not) in one request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
UserUpdate batchUpdate = UserUpdate.CreateBuilder()
    .UpdateAvatarUrl(newAvatarUrl)
    .UpdateDisplayName(newDisplayName)
    .SetPublicProperty(publicProperty1, newPublicValue)
    .RemovePublicProperty(publicProperty2)
    .SetPrivateProperty(privateProperty1, newPrivateValue)
    .RemovePrivateProperty(privateProperty2)
    .Build();

GetSocial.User.SetUserDetails(batchUpdate,
    () =>
    {
        Debug.Log("Successfully updated user details");
    },
    error =>
    {
        Debug.Log("Failed to update user details, error:" + error);
    });

Handle Multiple User Identities

You may want to connect multiple identities (login with Facebook and Google at the same time). It will allow to log into that user with different auth providers.

Your user may have any number of different identities attached for different login providers, but only one identity for each provider.

To add a new identity use GetSocial.User.AddAuthIdentity method. Once it is successfully added, you can log in using that identity.

To remove identity from user use GetSocial.User.RemoveAuthIdentity and pass the provider to be remove as first parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
string providerId = "my_auth_system";
GetSocial.User.RemoveAuthIdentity(providerId,
    () =>
    {
        Debug.Log("Successfully remove identity");
    },
    error =>
    {
        Debug.Log("Failed remove identity, error:" + error);
    });

To get all user identities call GetSocial.User.AuthIdentities, it will return a map of identities, where key is providerId and value is userId for that provider.

Subscribe to User Lifecycle Changes

If you want to be notified when SDK gets initialized or when Switch user occurs, you may subscribe to these events.

In order to do this, subscribe to the updates in the Awake() method of your MonoBehaviour implementation:

1
2
3
4
5
6
7
8
9
void Awake()
{
    GetSocial.User.SetOnUserChangedListener(() => {
        Debug.Log ("User is anonymous:  " + GetSocial.User.IsAnonymous);
        Debug.Log ("User's displayName: " + GetSocial.User.DisplayName);
        Debug.Log ("User's avatarURL:   " + GetSocial.User.AvatarUrl);
        Debug.Log ("User's identites:   " + GetSocial.User.AuthIdentities.ToDebugString());
    });
}

Get Users

Get Current User

It is not possible to obtain the instance of a current user object, but SDK provides methods to read and update user properties via static GetSocial.User class.

Get User By ID

Public user profile is represented by PublicUser class. Object is read-only and provide access to name, avatar url, list of identities and public properties.

The easiest way to get instance of PublicUser is by GetSocial User Id:

1
2
3
4
5
6
7
8
9
GetSocial.GetUserById("GetSocial User Id",
    user =>
    {
        // process user data
    },
    error =>
    {
        // Ooops. There was some exception while getting other user details.
    });

Also you can get users by their identities:

Find Users

You can find users by their display name using GetSocial.FindUsers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
UsersQuery query = UsersQuery.UsersByDisplayName("John Doe").WithLimit(10);
GetSocial.FindUsers(query,
    users =>
    {
        // Show list of users
    },
    error =>
    {
        // Error occured
    });

Next Steps

Well-done! Your user is set up, see what to do next:

  • Connect your user with others using our Social Graph.
  • Post to global or custom news feeds and communicate with others with Activity Feed.

Give us your feedback! Was this article helpful?

πŸ˜€ πŸ™