undefined

Authentication and Users

Every user has to authenticate with ConnectyCube before using any ConnectyCube functionality.

When someone connects with an application using ConnectyCube, the application will need to obtain a session token which provides temporary, secure access to ConnectyCube APIs.

A session token is an opaque string that identifies a user and an application.

Session token rights

There are different types of session tokens to support different use cases:

Session Token Type Description
Application session token This kind of access token is needed to read the app data. Has only READ access to resources
User session token The user token is the most commonly used type of token. This kind of access token is needed any time the app calls an API to read, modify or write a specific user's data on their behalf. Has READ/WRITE access to resources

Create session token

To create an application session use the following code:

createSession()
  .then((cubeSession) {})
  .catchError((error) {});

To create a user session use the following code:

CubeUser user = CubeUser(login: "user_login", password: "super_sequre_password");

createSession(user)
    .then((cubeSession) {})
    .catchError((error){});

Upgrade session token (user login)

If you have an application session, you can upgrade it to a user session by calling signIn method:

CubeUser user = CubeUser(login: "user_login", password: "super_sequre_password");
// CubeUser user = CubeUser(email: "cubeuser@gmail.com", password: "super_sequre_password");

signIn(user)
    .then((cubeUser) {})
    .catchError((error){});

Authentication via social provider

Flutter SDK provides support for next social providers:

  • CubeProvider.FACEBOOK;
  • CubeProvider.TWITTER;
String socialProvider; // possible providers CubeProvider.FACEBOOK, CubeProvider.TWITTER
String accessToken;
String accessTokenSecret; // required only for CubeProvider.TWITTER provider

signInUsingSocialProvider(socialProvider, accessToken, accessTokenSecret)
  .then((cubeUser) {})
  .catchError((error){});

Authentication via phone number

Sign In with phone number is supported with (Firebase Authenntication).

For Authentication via the phone number on the ConnectyCube server you need:

  • Project ID;
  • JSON Web Token (JWT) for identifying the user on Firebase service.

How to get Project ID?

You can found Project ID in the Firebase developer console, see the screenshot below: Get your Project ID

How to get JWT:

Firebase provides special plugin (firebase_auth) for managing authentication via Firebase services. Follow their guides on how to connect and use their services.

For getting JWT you can use next code snippet:

FirebaseAuth.instance.idTokenChanges().listen((firebaseUser) async {
   if(firebaseUser != null){
       // Get JWT from Firebase
       String token = await firebaseUser.getIdToken();

       if(!isEmpty(token)){
           //Call ConnectyCube Flutter SDK method for auth via phone number
           signInUsingFirebase(projectId, token).then((cubeUser) {

           }).catchError((onError){

           });
       }
   }
});

Code below will be called after the success validation code from SMS.

You can use firebase_auth_ui plugin for simple integrartion UI for phone verification. After simple configuration just call next code snippet for running flow for verification your phone number:

FirebaseAuthUi.instance().launchAuth([
    AuthProvider.phone(),
]).then((firebaseUser) async {
    // Success phone verification
}).catchError((error) {
    // Error occurs during phone verification
    if (error is PlatformException) {
        if (error.code == FirebaseAuthUi.kUserCancelledError) {
            logTime("ERROR: 'User cancelled login'");
        } else {
            logTime("ERROR: 'Unknown error!'");
        }
    }
});

These plugins (firebase_auth and firebase_auth_ui) are compatible and you can use them at the same time in your project.

Authentication via external identity provider

Custom Identity Provider (CIdP) feature is necessary if you need to use an external database to authenticate ConnectyCube application users. It allows you to integrate your existing users base with ConnectyCube easily and works the same way as Facebook/Twitter SSO.

With Custom Identity Provider feature you can continue using your user database instead of storing/copying user data to ConnectyCube database.

More info available on a dedicated Custom Identity Provider guide page.

After the Custom Identity Provider configuration, you can use same ConnectyCube user login API to authenticate ConnectyCube users against an external identity provider base.

Downgrade session token (user logout)

If you have a user session, you can downgrade it to an application session by calling signOut method:

signOut()
  .then((voidResult) {})
  .catchError((error) {});

Session expiration

Expiration time for session token is 2 hours after last request to API. If you perform query with expired token,
you will receive the error Required session does not exist. In this case you need to recreate a session token.

Use CubeSessionManager to get information about current session state.

bool isValid = CubeSessionManager.instance.isActiveSessionValid();
/// isValid == true - you have an active session
/// isValid == false - you have an expired session and you should create new one

ConnectyCube Flutter SDK has the special callbĐ°ck for automatic session restoring. Just set it during the initialization ConnectyCube Flutter SDK in your project.

initConnectyCube() {
    init("XXX", "XXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXX", onSessionRestore: restoreSession);
}

Future<CubeSession> restoreSession() {
  CubeUser savedUser; //some CubeUser, which was saved before

  return createSession(savedUser);
}

Destroy session token

To destroy a session use the following code:

int sessionId = 12345; // skip this parameter to delete current session

deleteSession(sessionId)
    .then((voidResult) {})
    .catchError((error){});

// used to delete all session except current  
deleteSessionsExceptCurrent()
    .then((voidResult) {})
    .catchError((error){});

User signup

CubeUser user = CubeUser(
    login: 'marvin18',
    password: 'supersecurepwd',
    email: 'awesomeman@gmail.com',
    fullName: 'Marvin Simon',
    phone: '47802323143',
    website: 'https://dozensofdreams.com',
    customData: "{middle_name: 'Bartoleo'}");

signUp(user)
    .then((cubeUser) {})
    .catchError((error){});

Only login (or email) + password are required.

User profile update

CubeUser user = CubeUser(
    login: 'marvin18',
    fullName: 'Marvin Simon');

updateUser(user)
      .then((updatedUser) {})
      .catchError((error) {});

If you want to change your password, you need to provide 2 fields: password and oldPassword. Updated user entity will be returned.

CubeUser user = CubeUser(
  login: 'marvin18',
  password: "newPassword",
  oldPassword: "oldPassword");

updateUser(user)
  .then((updatedUser) {})
  .catchError((error) {});

User avatar

You can set a user's avatar. You just need to upload it to the ConnectyCube cloud storage and then connect to user.

File file; //some file from device storage
CubeUser user; // some user to set avatar

uploadFile(file, false)
  .then((cubeFile) {
    user.avatar = cubeFile.uid;
    return updateUser(user);
  })
  .catchError((error) {});

Now, other users can get you avatar:

CubeUser user; // some user with avatar

String avatarUrl = getPrivateUrlForUid(user.avatar);

Password reset

It's possible to reset a password via email:

resetPassword("awesomeman@gmail.com")
    .then((voidResult) {})
    .catchError((error) {});

If provided email is valid - an email with password reset instruction will be sent to it.

Retrieve users

Retrieve user by ID

int userId = 22;

getUserById(userId)
    .then((cubeUser) {})
    .catchError((error) {});

Retrieve users by IDs

Set<int> ids = {22, 33};

getAllUsersByIds(ids)
    .then((pagedResult) {})
    .catchError((error) {});

Retrieve user by login

String login = "marvin18";

getUserByLogin(login)
    .then((cubeUser) {})
    .catchError((error) {});

Retrieve user by email

String email = "marvin18@example.com";

getUserByEmail(email)
    .then((cubeUser) {})
    .catchError((error) {});

Retrieve users by full name

String fullName = "Marvin Samuel";

getUsersByFullName(fullName)
    .then((pagedResult) {})
    .catchError((error) {});

Retrieve user by phone number

String phoneNumber = "47802323143";

getUserByPhoneNumber(phoneNumber)
  .then((cubeUser) {})
  .catchError((error) {});

Retrieve user by external ID

int externalId = 654321;

getUserByExternalId(externalId)
  .then((cubeUser) {})
  .catchError((error) {});

Retrieve users by tags

Set<String> tags = {"apple"};

getUsersByTags(tags)
    .then((pagedResult) {})
    .catchError((error) {});

Delete user

A user can delete himself from the platform:

int userId = 123456;

deleteUser(userId)
    .then((cubeUser) {})
    .catchError((error) {});