Skip to content

AccountClient Class

The AccountClient class provides methods to interact with account-related endpoints of the API. This client handles tasks such as account creation, login, logout, and token refresh operations, among others.

Methods

  • CreateAccountAsync(string email, string username, string password, bool use2Fa = false, CredentialsValidator? credentialsValidator = null): Asynchronously creates a new account.
  • LoginAsync(string id, string password): Asynchronously logs in to an account with the provided ID and password.
  • LoginTwoFactorAsync(uint code): Asynchronously completes two-factor authentication login.
  • RefreshTokenAsync(): Asynchronously refreshes the authentication token.
  • LogoutAsync(): Asynchronously logs out of the current session.
  • ChangeEmailAsync(string newEmail, string password): Asynchronously changes the account's email to a new one.
  • ChangePasswordAsync(string oldPassword, string newPassword): Asynchronously changes the account's password.
  • ForgotPasswordAsync(string id): Initiates a password reset process for the account specified by the ID.
  • GetRolesAsync(): Asynchronously retrieves the roles associated with the account.
  • GetUserAsync(): Asynchronously fetches details of the current user.

Refresh Token Mechanism

The class uses a Timer to handle automatic token refreshes. Methods StartRefreshTimer(TimeSpan refreshInterval) and StopRefreshTimer() control the timer based on the application's needs, ensuring tokens remain valid for the duration of the user's session.

Typically, you should start the timer right after the user successfully logs in, or after they've entered their two-factor authentication code, although it's not mandatory to use the timer. If you choose not to use it, the user's login session will end automatically once the token expires. The duration before a token expires is configured on the server side through environment variables.

Usage Example

This class is commonly accessed through the CobraAccounts class or the AccountService in Unity for a centralized approach. However, it's also designed to function independently, allowing direct usage without relying on a central class.

To use AccountClient, you'll need to instantiate it with an HttpClient instance configured with your API's base URL. After instantiation, you can call any of the provided asynchronous methods to perform operations against the account endpoints of the API.

var httpClient = new HttpClient { BaseAddress = new Uri("https://accounts.bytecobra.com") };
var accountClient = new AccountClient(httpClient);

// Create an account
var createAccountResult = await accountClient.CreateAccountAsync("email@example.com", "username", "password");

// Login
var loginResult = await accountClient.LoginAsync("username", "password");