private static async Task <PermissionToken> GetPermissionAsync(string userId, CosmosDBRepository repo, string permissionId, PermissionMode permissionMode = PermissionMode.Read) { Permission permission = null; User user = await CreateUserIfNotExistAsync(userId, repo); string userStr = userId; string[] userArr = userStr.Split('@'); userStr = userArr[0]; try { permission = await repo.GetPermissionAsync(user, permissionId, new RequestOptions { ResourceTokenExpirySeconds = (int)TOKEN_EXPIRY.TotalSeconds }); // System.Diagnostics.Debug.WriteLine($"Retreived Existing Permission. {permission.Id}"); } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { DocumentCollection collection = await repo.GetDocumentCollectionAsync(); permission = new Permission { PermissionMode = permissionMode, ResourceLink = collection.SelfLink, // Permission restricts access to this partition key ResourcePartitionKey = new PartitionKey(userStr), // Unique per user Id = permissionId }; try { permission = await repo.UpsertPermissionAsync(user, permission, new RequestOptions { ResourceTokenExpirySeconds = (int)TOKEN_EXPIRY.TotalSeconds }); } catch (Exception ex) { throw ex; } } else { throw e; } } var expires = DateTimeOffset.Now.Add(TOKEN_EXPIRY).ToUnixTimeSeconds(); return(new PermissionToken() { Token = permission.Token, Expires = expires, UserId = userId }); }