using LeanCloud.Storage.Internal; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace LeanCloud { /// /// Represents a session of a user for a LeanCloud application. /// [AVClassName("_Session")] public class AVSession : AVObject { private static readonly HashSet readOnlyKeys = new HashSet { "sessionToken", "createdWith", "restricted", "user", "expiresAt", "installationId" }; protected override bool IsKeyMutable(string key) { return !readOnlyKeys.Contains(key); } /// /// Gets the session token for a user, if they are logged in. /// [AVFieldName("sessionToken")] public string SessionToken { get { return GetProperty(null, "SessionToken"); } } /// /// Constructs a for AVSession. /// public static AVQuery Query { get { return new AVQuery(); } } internal static IAVSessionController SessionController { get { return AVPlugins.Instance.SessionController; } } /// /// Gets the current object related to the current user. /// public static Task GetCurrentSessionAsync() { return GetCurrentSessionAsync(CancellationToken.None); } /// /// Gets the current object related to the current user. /// /// The cancellation token public static Task GetCurrentSessionAsync(CancellationToken cancellationToken) { return AVUser.GetCurrentUserAsync().OnSuccess(t1 => { AVUser user = t1.Result; if (user == null) { return Task.FromResult((AVSession)null); } string sessionToken = user.SessionToken; if (sessionToken == null) { return Task.FromResult((AVSession)null); } return SessionController.GetSessionAsync(sessionToken, cancellationToken).OnSuccess(t => { AVSession session = AVObject.FromState(t.Result, "_Session"); return session; }); }).Unwrap(); } internal static Task RevokeAsync(string sessionToken, CancellationToken cancellationToken) { if (sessionToken == null || !SessionController.IsRevocableSessionToken(sessionToken)) { return Task.FromResult(0); } return SessionController.RevokeAsync(sessionToken, cancellationToken); } internal static Task UpgradeToRevocableSessionAsync(string sessionToken, CancellationToken cancellationToken) { if (sessionToken == null || SessionController.IsRevocableSessionToken(sessionToken)) { return Task.FromResult(sessionToken); } return SessionController.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken).OnSuccess(t => { AVSession session = AVObject.FromState(t.Result, "_Session"); return session.SessionToken; }); } } }