Skip to content

Tutorials ‐ CPlusPlus ‐ Authenticating

Michael K edited this page Nov 21, 2023 · 7 revisions

Authentication is done using the UserSystem singleton. System singleton instances are managed by the static SystemsManager class. The code snippet below shows how to retrieve the singleton instance for UserSystem.

#include "CSP/Systems/Users/UserSystem.h"
#include "CSP/Systems/SystemsManager.h"

csp::systems::SystemsManager& systemManager = csp::systems::SystemsManager::Get();
csp::systems::UserSystem* userSystem = systemManager.GetUserSystem();

You can then proceed to log in using an account or as a guest user. Most endpoints in CSP are asynchronous and you will need to pass a callback to them. This callback will be called once for each progress update, and once more when the request has completed.

void OnLogin(const csp::systems::LoginStateResult& result) {
  csp::services::EResultCode resCode = result.GetResultCode();

  // Some endpoints (like AssetSystem::UploadAssetData()) report progress status.
  // This endpoint does not, so it can be ignored.
  if (resCode == csp::services::EResultCode::InProgress)
    return;

  // If the request fails, ResultCode will be set to EResultCode::Failed
  if (resCode == csp::services::EResultCode::Failed) {
    // ResultBase::FailureReason will be set if the request failed and should
    // be used to determine the cause of the failure.
    auto reason = static_cast<csp::systems::ELoginStateFailureReason>(result.GetFailureReason());

    switch (reason) {
      case csp::systems::ELoginStateFailureReason::EmailNotConfirmed:
        std::cout << "User email not verified! Please follow the link in the verification email sent to you after registering an account." << std::endl;
        break;
      case csp::systems::ELoginStateFailureReason::AgeNotVerified:
        std::cout << "User has not confirmed they are over 18! Either you are too young or should re-enter your DoB on the sign in page." << std::endl;
        break;
      case csp::systems::ELoginStateFailureReason::Unknown:
        // If FailureReason is unknown, check the HTTP response code.
        // If it is 403, the provided account credentials were incorrect.
        std::cout << "Request failed with HTTP response code " << result.GetHttpResultCode() << std::endl;
        break;
    }
  }
}

// Log in using a registered account
// The 4th parameter is a boolean indicating whether the user has verified their age or not,
// and can be null to use the value supplied during a previous call to Login() or CreateUser()
userSystem->Login("<username - leave empty>", "<account email>", "<account password>", true, OnLogin);

// Log in as a guest user
// The 1st parameter is the same boolean as above
userSystem->LoginAsGuest(true, OnLogin);




Clone this wiki locally