Login and Logout Users¶
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 easily change it.
To check if user is anonymous:
```java tab=”Android(Java)”
boolean anonymous = GetSocial.User.isAnonymous();
```kotlin tab="Android(Kotlin)"
val anonymous = GetSocial.User.isAnonymous()
```objc tab=”iOS(Objective-C)”
BOOL anonymous = [GetSocialUser isAnonymous];
```swift tab="iOS(Swift)"
let anonymous = GetSocialUser.isAnonymous
```c# tab=”Unity”
var anonymous = GetSocial.User.IsAnonymous;
```javascript tab="React Native"
GetSocial.User.isAnonymous().then((isAnonymous) => {
console.log('User is anonymous? ' + 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:
```java tab=”Android(Java)”
// Create Facebook identity
AuthIdentity fbIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken);
// Create Custom Identity
AuthIdentity customIdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken);
```kotlin tab="Android(Kotlin)"
// Create Facebook identity
val authIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken)
// Create Custom Identity
val customUdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken)
```objc tab=”iOS(Objective-C)”
// Create Facebook identity
GetSocialAuthIdentity *fbIdentity = [GetSocialAuthIdentity facebookIdentityWithAccessToken:fbAccessToken];
// Create Custom Identity
GetSocialAuthIdentity *customIdentity = [GetSocialAuthIdentity customIdentityForProvider:providerId userId:userId accessToken:accessToken];
```swift tab="iOS(Swift)"
// Create Facebook identity
let fbIdentity = GetSocialAuthIdentity.facebookIdentityWithAccessToken(fbAccessToken)
// Create Custom Identity
let customIdentity = GetSocialAuthIdentity.customIdentityForProvider(providerId, userId:userId, accessToken:accessToken)
```c# tab=”Unity”
// Create Facebook identity
var fbIdentity = AuthIdentity.CreateFacebookIdentity(fbAccessToken);
// Create Custom Identity
var customIdentity = AuthIdentity.CreateCustomIdentity(providerId, userId, accessToken);
```javascript tab="React Native"
// Create Facebook identity
const fbIdentity = AuthIdentity.createFacebookIdentity(fbAccessToken);
// Create custom identity
const customIdentity = AuthIdentity.createCustomIdentity(providerId, userId, accessToken);
providerId
is a uniquestring
defined by you for each provider (twitter
,my_auth_system
,gamecenter
, etc).userId
is a uniquestring
for each user in the provided authentication system. So pairproviderId
-userId
is unique for each user and helps GetSocial identify a user if them try to login from another device.accessToken
is astring
for security check, that could be some internal hash function in your app based onuserId
. If user is trying to authenticate again with the sameproviderId
anduserId
, but differentaccessToken
- 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.
```java tab=”Android(Java)”
public void onLoginSuccess() {
String userId = getCurrentUserId(); // get user ID on your login provider
String accessToken = … // access token
final AuthIdentity identity = AuthIdentity.createCustomIdentity(“my_auth_system”, userId, accessToken);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
}
kotlin tab=”Android(Kotlin)”
fun onLoginSuccess() {
val userId = getCurrentUserId() // get user ID on your login provider
val accessToken = … // access token
val identity = AuthIdentity.createCustomIdentity(“my_auth_system”, userId, accessToken)
GetSocial.User.addAuthIdentity(identity, object : AddAuthIdentityCallback {
override fun onComplete() {
println(“Successfully logged into ${userId}”)
}
override fun onFailure(exception: GetSocialException) {
println(“Failed to log into ${userId}, error: ${exception.message}”)
}
override fun onConflict(conflictUser: ConflictUser) {
handleConflict(identity, conflictUser)
}
})
}
```
```objc tab=”iOS(Objective-C)”
- (void)onLoginSuccess {
NSString *userId = [self getCurrentUserId]; // get user ID on your login provider
NSString *accessToken = … // access token
GetSocialAuthIdentity *identity = [GetSocialAuthIdentity customIdentityForProvider:@”my_auth_system” userId:userId accessToken:accessToken];
1 2 3 4 5 6 7 8 9 10 |
|
}
swift tab=”iOS(Swift)”
func onLoginSuccess() {
let userId = getCurrentUserId() // get user ID on your login provider
let accessToken = … // access token
let identity = GetSocialAuthIdentity.customIdentity(forProvider: “my_auth_system”, userId: userId, accessToken: accessToken)
GetSocialUser.addAuthIdentity(identity, success: {
print(“Successfully logged into (userId)”)
}, conflict: { conflictUser in
self.handleConflict(forIdentity: identity, conflictUser: conflictUser)
}, failure: { error in
print(“Failed to log into (userId)”)
})
}
```
```c# tab=”Unity”
public void OnLoginSuccess() {
string userId = GetCurrentUserId(); // get user ID on your login provider
string accessToken = … // access token
AuthIdentity identity = AuthIdentity.CreateCustomIdentity(“my_auth_system”, userId, accessToken);
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
}
javascript tab=”React Native”
void onLoginSuccess = async() => {
const userId = getCurrentUserId(); // get user ID on your login provider
const accessToken = … // access token
const authIdentity = AuthIdentity.createCustomIdentity(‘my_auth_system’, userId, accessToken);
GetSocialUser.addAuthIdentity(authIdentity, () => {
console.log(“Successfully logged into user ” + userId);
}, (conflictUser) => {
this.handleConflict(identity, conflictUser);
}, (error) => {
console.log(“Failed to log into user ” + userId + “, error:” + error);
});
}
```
Add Facebook Identity¶
To add Facebook identity, you should provide the token you got from Facebook SDK after user’s authentication.
-
Integrate Facebook SDK into your app as described in the Official Guide for iOS, Android or Unity.
-
Add Facebook identity to GetSocial user. Sample code is below:
```java tab=”Android(Java)”
final AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
stopTracking(); // stop tracking facebook access token changes as we don’t need it anymore1 2 3
AuthIdentity authIdentity = AuthIdentity.createFacebookIdentity(newAccessToken.getToken()); GetSocial.User.addAuthIdentity(authIdentity, completionCallback); }
};
accessTokenTracker.startTracking();LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList(“email”, “user_friends”)); // we need “user_friends” permission to import list of Facebook friends to GetSocial Social Graph
```kotlin tab="Android(Kotlin)" val accessTokenTracker = object: AccessTokenTracker() { override fun onCurrentAccessTokenChanged(oldAccessToken: AccessToken, currentAccessToken: AccessToken) { stopTracking() // stop tracking facebook access token changes as we don't need it anymore val authIdentity = AuthIdentity.createFacebookIdentity(currentAccessToken.token) GetSocial.User.addAuthIdentity(authIdentity, completionCallback) } } accessTokenTracker.startTracking() LoginManager.getInstance().logInWithReadPermissions(this@MainActivity, listOf("email", "user_friends")) // we need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph
```objc tab=”iOS(Objective-C)”
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorBrowser;[login
logInWithReadPermissions:@[@”email”, @”user_friends”] // we need “user_friends” permission to import list of Facebook friends to GetSocial Social Graph
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *loginError) {
if (!loginError && !result.isCancelled)
{
GetSocialAuthIdentity *identity = [GetSocialAuthIdentity facebookIdentityWithAccessToken:result.token.tokenString];1 2 3 4 5 6 7 8 9 10 11
[GetSocialUser addAuthIdentity:identity success:^{ NSLog(@"Successfully logged into FB"); } conflict:^(GetSocialConflictUser *conflictUser) { [self handleConflictForIdentity:identity conflictUser:conflictUser]; } failure:^(NSError *error) { NSLog(@"Failed to log into FB"); }]; }
}];
swift tab=”iOS(Swift)”
let login = FBSDKLoginManager()
login.loginBehavior = FBSDKLoginBehaviorBrowser
/* we need “user_friends” permission to import list of Facebook friends to GetSocial Social Graph */
login.logIn(withReadPermissions: [“email”, “user_friends”], fromViewController: self, handler: { result, loginError in
if loginError == nil && result?.isCancelled == nil {
let identity = GetSocialAuthIdentity.facebookIdentity(withAccessToken: result?.token.tokenString)
GetSocialUser.add(identity, success: {
print(“Successfully logged into FB”)
}, conflict: { conflictUser in
self.handleConflict(for: identity, conflictUser: conflictUser)
}, failure: { error in
print(“Failed to log into FB”)
})
}
})
``````c# tab=”Unity”
FB.Init(() => {
var permissions = new List(){“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”);
}
});
});
```javascript tab="React Native" // We need "user_friends" permission to import list of Facebook friends to GetSocial Social Graph LoginManager.logInWithReadPermissions(['email', 'user_friends', 'public_profile']).then((result) => { if (result.isCancelled) { console.log('FB Login cancelled'); } else { AccessToken.getCurrentAccessToken().then((token) => { if (token != null) { const fbIdentity = AuthIdentity.createFacebookIdentity(token.accessToken); GetSocial.User.AddAuthIdentity (authIdentity, () => {}, (conflictUser) => {}, (error) => {}); } }); } }, (error) => { console.log('FB login failed with error: ' + error); });
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 success
and failure
callbacks, addAuthIdentity
has conflict
. 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:
```java tab=”Android(Java)”
public void handleConflict(AuthIdentity identity, ConflicUser conflictUser) {
// Do nothing in onConflict and user will stay the same.
// Identity won’t be added to any of the users.
}
```kotlin tab="Android(Kotlin)"
fun handleConflict(identity: AuthIdentity, conflictUser: ConflictUser) {
// Do nothing in onConflict and user will stay the same.
// Identity won't be added to any of the users.
}
```objc tab=”iOS(Objective-C)”
- (void)handleConflictForIdentity:(GetSocialAuthIdentity *)identity conflictUser:(GetSocialConflictUser *)conflictUser {
// Do nothing in onConflict and user will stay the same.
// Identity won’t be added to any of the users.
}
```swift tab="iOS(Swift)"
func handleConflict(for identity: GetSocialAuthIdentity, conflictUser: GetSocialConflictUser) {
// Do nothing in onConflict and user will stay the same.
// Identity won't be added to any of the users.
}
```c# tab=”Unity”
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.
}
```javascript tab="React Native"
handleConflict(authIdentity, 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:
```java tab=”Android(Java)”
public void handleConflict(AuthIdentity identity, ConflicUser 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);
}
```kotlin tab="Android(Kotlin)"
fun handleConflict(identity: AuthIdentity, 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)
}
```objc tab=”iOS(Objective-C)”
- (void)handleConflictForIdentity:(GetSocialAuthIdentity *)identity conflictUser:(GetSocialConflictUser *)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.
[GetSocialUser switchUserToIdentity:identity
success:^{
NSLog(@”Successfully switched user”);
}
failure:^(NSError *error) {
NSLog(@”Failed to switch user”);
}];];
}
```swift tab="iOS(Swift)"
func handleConflict(for identity: GetSocialAuthIdentity, conflictUser: GetSocialConflictUser) {
// 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.
GetSocialUser.switch(identity, success: {
print("Successfully switched user")
}, failure: { error in
print("Failed to switch user")
})
}
```c# tab=”Unity”
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);
}
```javascript tab="React Native"
handleConflict(authIdentity, 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.
GetSocialUser.switchUser(authIdentity);
}
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.
```java tab=”Android(Java)”
public void onLogoutSuccess() {
// New anonymous will be created. If your current user is anonymous - it will be lost.
GetSocial.User.reset(completionCallback);
}
```kotlin tab="Android(Kotlin)"
fun onLogoutSuccess() {
// New anonymous will be created. If your current user is anonymous - it will be lost.
GetSocial.User.reset(completionCallback)
}
```objc tab=”iOS(Objective-C)”
- (void)onLogoutSuccess {
// New anonymous user will be created. If your current user is anonymous - it will be lost.
[GetSocialUser resetWithSuccess:success failure:failure];
}
```swift tab="iOS(Swift)"
func onLogoutSuccess() {
// New anonymous user will be created. If your current user is anonymous - it will be lost.
GetSocialUser.reset(success: success, failure: failure)
}
```c# tab=”Unity”
void OnLogoutSuccess()
{
// New anonymous will be created. If your current user is anonymous - it will be lost.
GetSocial.User.reset(OnSuccess, OnError);
}
```javascript tab="React Native"
onLogoutSuccess() {
// New anonymous will be created. If your current user is anonymous - it will be lost.
GetSocialUser.reset();
}
Subscribe to GetSocial user changes to be notified about logout events too.
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.
You already know how to add identity. Once it is successfully added, you can log in using that identity.
To remove identity from user:
```java tab=”Android(Java)”
String providerId = “my_auth_system”;
GetSocial.User.removeAuthIdentity(providerId, new CompletionCallback() {
@Override
public void onSuccess() {
Log.d(“GETSOCIAL”, “Identity successfully removed.”);
}
1 2 3 4 |
|
});
kotlin tab=”Android(Kotlin)”
val providerId = “my_auth_system”
GetSocial.User.removeAuthIdentity(providerId, object : CompletionCallback{
override fun onSuccess() {
println(“Identity successfully removed.”)
}
override fun onFailure(exception: GetSocialException) {
println(“Failed to remove identity, error: ${exception.message}”)
}
})
```
```objc tab=”iOS(Objective-C)”
NSString *providerId = “my_auth_system”;
[GetSocialUser removeAuthIdentityWithProviderId:providerId success:success failure:failure];
```swift tab="iOS(Swift)"
let providerId = "my_auth_system"
GetSocialUser.removeAuthIdentity(withProviderId: providerId, success: success, failure: failure)
```c# tab=”Unity”
string providerId = “my_auth_system”;
GetSocial.User.RemoveAuthIdentity(providerId,
() =>
{
Debug.Log(“Successfully remove identity”);
},
error =>
{
Debug.Log(“Failed remove identity, error:” + error);
});
```javascript tab="React Native"
const providerId = 'my_auth_system';
GetSocialUser.removeAuthIdentity(providerId).then(() => {
console.log('Successfully remove identity');
}, (error) => {
console.log('Failed remove identity, error:' + error);
});
To get all user identities:
```java tab=”Android(Java)”
Map
```kotlin tab="Android(Kotlin)"
val identities = GetSocial.User.getAuthIdentities()
```objc tab=”iOS(Objective-C)”
NSDictionary *identities = [GetSocialUser authIdentities];
```swift tab="iOS(Swift)"
let identities = GetSocialUser.authIdentities
```c# tab=”Unity”
var identities = GetSocial.User.AuthIdentities;
```javascript tab="React Native"
GetSocialUser.getAuthIdentities().then((authIdentities) => {});
where key
is providerId
and value
is userId
for that provider.
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.
Subscribe to User Lifecycle Changes¶
User change handler is invoked when:
- SDK got initialized;
- You successfully switched user as in Strategy 2 of Handle Conflict section;
- You successfully reset user.
Set your custom event handler somewhere on the start of your application:
```java tab=”Android(Java)”
public class MainActivity extends Activity implements OnUserChangedListener {
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
}
kotlin tab=”Android(Kotlin)”
class MainActivity : AppCompatActivity(), OnUserChangedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup GetSocial
GetSocial.User.setOnUserChangedListener(this)
…
}
override fun onUserChanged() {
println(“Is SDK initialized? ${GetSocial.isInitialized()}”)
println(“Is user anonymous? ${GetSocial.User.isAnonymous()}”)
println(“What’s user’s avatar? ${GetSocial.User.getAvatarUrl()}”)
println(“What’s user’s name? ${GetSocial.User.getDisplayName()}”)
println(“List of user’s identities: ${GetSocial.User.getAuthIdentities()}”)
}
}
```
```objc tab=”iOS(Objective-C)”
@implementation MainViewController
…
- (void)viewDidLoad {
[super viewDidLoad];
…
[GetSocialUser setOnUserChangedHandler:^() {
NSLog(@”User is anonymous: %@”, GetSocialUser.isAnonymous ? @”Yes” : @”No”);
NSLog(@”User’s displayName: %@”, GetSocialUser.displayName);
NSLog(@”User’s avatarURL: %@”, GetSocialUser.avatarUrl);
NSLog(@”User’s identites: %@”, GetSocialUser.authIdentities);
}];
…
}
…
@end
```swift tab="iOS(Swift)"
class ViewController: UIViewController {
...
func viewDidLoad() {
super.viewDidLoad()
...
GetSocialUser.setOnUserChangedHandler {
print("User is anonymous: \(GetSocialUser.isAnonymous ? "Yes" : "No")")
print("User's displayName: \(GetSocialUser.displayName)")
print("User's avatarURL: \(GetSocialUser.avatarUrl)")
print("User's identites: \(GetSocialUser.authIdentities)")
}
...
}
}
```c# tab=”Unity”
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);
});
}
```javascript tab="React Native"
componentWillMount() {
// Listen for events to set the proper information
GetSocialUser.onUserChanged(() => {
GetSocialUser.isAnonymous().then((isAnonymous) => {
console.log('User is anonymous: ' + isAnonymous);
});
GetSocialUser.getDisplayName().then((displayName) => {
console.log('Users display name: ' + displayName);
});
GetSocialUser.getAvatarUrl().then((avatarUrl) => {
console.log('Users avatar url: ' + avatarUrl);
});
GetSocialUser.getAuthIdentities().then((authIdentities) => {
console.log('Users identities: ' + JSON.stringify(authIdentities));
});
});
}
Next Steps¶
Well-done! Your user is set up, see what to do next: