private ActionResult SetConfiguration(string message, Guid projectGuid, DateTime?endAt, bool isNew)
        {
            try
            {
                _selfConfigManager.SetProjectIdAndExpirationAsync(projectGuid, endAt?.ToUniversalTime());

                if (isNew)
                {
                    return(View("Wait"));
                }

                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                    Caption = null, Message = message, MessageType = MessageType.Info
                }));
            }
            catch (ConfigurationErrorsException ex)
            {
                return(View("Error", new MessageModel {
                    Caption = CAPTION_CONFIGURATION_WRITE_ERROR, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
            catch (JsonSerializationException ex)
            {
                return(View("Error", new MessageModel {
                    Caption = CAPTION_DESERIALIZATION_ERROR, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
        }
        public async Task <ActionResult> Free()
        {
            string token = GetToken();

            try
            {
                var subscription = await _subscriptionProvider.ConvertToFreeAsync(token);

                if (subscription != null)
                {
                    return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                        Caption = null, Message = $"You've converted your subscription {subscription.SubscriptionId} to a free plan.", MessageType = MessageType.Info
                    }));
                }
                else
                {
                    return(View("Error", new MessageModel {
                        Caption = "Too Many Resources", Message = "We couldn't convert your subscription to the free plan. Please make sure you've lowered your resources in Kentico Cloud to meet the limits of the free plan.", MessageType = MessageType.Error
                    }));
                }
            }
            catch (ConfigurationErrorsException ex)
            {
                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                    Caption = null, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
            catch (JsonSerializationException ex)
            {
                return(GetDeserializationErrorResult(ex));
            }
        }
        private ActionResult SetConfiguration(string message, Guid projectGuid, DateTime?endAt, bool isNew)
        {
            try
            {
                Options.Update(opt => { opt.ProjectId = projectGuid.ToString(); });

                if (endAt.HasValue)
                {
                    AppConfig.Update(opt => { opt.SubscriptionExpiresAt = endAt.Value.ToUniversalTime(); });
                }

                if (isNew)
                {
                    return(View("~/Areas/Admin/Views/SelfConfig/Wait.cshtml"));
                }

                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                    Caption = null, Message = message, MessageType = MessageType.Info
                }));
            }
            catch (JsonSerializationException ex)
            {
                return(View("~/Areas/Admin/Views/Shared/Error.cshtml", new MessageModel {
                    Caption = CAPTION_DESERIALIZATION_ERROR, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
            catch (Exception ex)
            {
                return(View("~/Areas/Admin/Views/Shared/Error.cshtml", new MessageModel {
                    Caption = CAPTION_CONFIGURATION_WRITE_ERROR, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
        }
        public async Task <ActionResult> SelectProject(SelectProjectViewModel model)
        {
            try
            {
                if (model.ProjectId.HasValue)
                {
                    DateTime?endAt = null;

                    if (model.ManualInput.HasValue && model.ManualInput.Value)
                    {
                        string token = GetToken();

                        if ((await _userProvider.GetUserAsync(token)) != null)
                        {
                            var subscriptions = await _subscriptionProvider.GetSubscriptionsAsync(token);

                            // The user does not have to be logged in and projects may not always be owned by the user. Getting subscription EndAt date might not be possible. Hence the allowed null outcome.
                            endAt = subscriptions.FirstOrDefault(s => s.Projects.Any(p => p.Id == AppSettingProvider.ProjectId))?.CurrentPlan?.EndAt;
                        }
                    }

                    try
                    {
                        _selfConfigManager.SetProjectIdAndExpirationAsync(model.ProjectId.Value, endAt);
                    }
                    catch (ConfigurationErrorsException ex)
                    {
                        return(View("Error", new MessageModel {
                            Caption = CAPTION_CONFIGURATION_WRITE_ERROR, Message = ex.Message, MessageType = MessageType.Error
                        }));
                    }

                    return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                        Caption = null, Message = $"You've configured your app with a project ID \"{model.ProjectId}\".", MessageType = MessageType.Info
                    }));
                }
                else
                {
                    try
                    {
                        _selfConfigManager.SetSharedProjectIdAsync();

                        return(View("Error", new MessageModel {
                            Caption = "Missing project ID", Message = "The submitted project ID was an empty GUID. The app was configured with the shared project ID instead. You may wish to reconfigure the project ID in your environment settings (Azure application settings, web.config, etc.).", MessageType = MessageType.Error
                        }));
                    }
                    catch (ConfigurationErrorsException ex)
                    {
                        return(View("Error", new MessageModel {
                            Caption = CAPTION_CONFIGURATION_WRITE_ERROR, Message = ex.Message, MessageType = MessageType.Error
                        }));
                    }
                }
            }
            catch (JsonSerializationException ex)
            {
                return(GetDeserializationErrorResult(ex));
            }
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var       token = filterContext.HttpContext.Request.Cookies["kcToken"]?.Value;
            UserModel user  = null;

            if (!string.IsNullOrEmpty(token))
            {
                user = Task.Run(() => (new UserProvider(new HttpClient())).GetUserAsync(token)).Result;
            }

            if (user == null)
            {
                DateTime?subscriptionExpiresAt = AppSettingProvider.SubscriptionExpiresAt;
                var      message = new MessageModel {
                    Caption = null, Message = "You haven't authenticated with proper Kentico Cloud credentials. Please close the browser window and log in.", MessageType = MessageType.Error
                };
                filterContext.Result = subscriptionExpiresAt == null?RedirectHelpers.GetSelfConfigIndexResult(message) : RedirectHelpers.GetSelfConfigRecheckResult(message);
            }
        }
        private ActionResult UseSharedPrivate()
        {
            try
            {
                _selfConfigManager.SetProjectIdAndExpirationAsync(AppSettingProvider.DefaultProjectId.Value);

                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                    Caption = null, Message = MESSAGE_SHARED_PROJECT, MessageType = MessageType.Info
                }));
            }
            catch (ConfigurationErrorsException ex)
            {
                return(View("Error", new MessageModel {
                    Caption = CAPTION_CONFIGURATION_WRITE_ERROR, Message = ex.Message, MessageType = MessageType.Error
                }));
            }
            catch (JsonSerializationException ex)
            {
                return(GetDeserializationErrorResult(ex));
            }
        }
        public async Task <ActionResult> DeploySample()
        {
            string token = GetToken();

            try
            {
                var user = await _userProvider.GetUserAsync(token);

                if (user != null)
                {
                    try
                    {
                        var projectId = await _selfConfigManager.DeployAndSetSampleProject(token, user);

                        return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                            Caption = null, Message = string.Format(MESSAGE_NEW_SAMPLE_PROJECT, projectId), MessageType = MessageType.Info
                        }));
                    }
                    catch (ConfigurationErrorsException ex)
                    {
                        return(await HandleSampleDeploymentExceptions(token, ex));
                    }
                    catch (DeliveryException ex)
                    {
                        return(await HandleSampleDeploymentExceptions(token, ex));
                    }
                }
                else
                {
                    return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                        Caption = null, Message = MESSAGE_UNAUTHENTICATED, MessageType = MessageType.Error
                    }));
                }
            }
            catch (JsonSerializationException ex)
            {
                return(GetDeserializationErrorResult(ex));
            }
        }
 public ActionResult Done()
 {
     return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
         Caption = null, Message = string.Format(MESSAGE_SELECTED_PROJECT, AppSettingProvider.ProjectId.Value), MessageType = MessageType.Info
     }));
 }
        public async Task <ActionResult> Index(string token)
        {
            string actualToken = token ?? GetToken();

            if (!string.IsNullOrEmpty(actualToken))
            {
                try
                {
                    if (!string.IsNullOrEmpty(token))
                    {
                        AddAuthenticationCookie(token);
                    }

                    var user = await _userProvider.GetUserAsync(actualToken);

                    IEnumerable <SubscriptionModel> subscriptions;

                    if (user != null)
                    {
                        subscriptions = await _subscriptionProvider.GetSubscriptionsAsync(actualToken);
                    }
                    else
                    {
                        return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                            Caption = null, Message = MESSAGE_UNAUTHENTICATED, MessageType = MessageType.Error
                        }));
                    }

                    if (subscriptions == null || !subscriptions.Any())
                    {
                        SubscriptionModel subscription = await _subscriptionProvider.StartTrial(actualToken);

                        ProjectModel project = null;

                        try
                        {
                            if (subscription != null)
                            {
                                project = await _projectProvider.DeploySampleAsync(token, subscription.SubscriptionId);
                            }
                        }
                        catch (DeliveryException)
                        {
                            return(UseSharedPrivate());
                        }

                        if (subscription != null && project != null)
                        {
                            try
                            {
                                _selfConfigManager.SetProjectIdAndExpirationAsync(project.ProjectId.Value, subscription.EndAt);
                                await _projectProvider.RenameProjectAsync(token, project.ProjectId.Value);

                                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                                    Caption = null, Message = string.Format(MESSAGE_NEW_SAMPLE_PROJECT, project.ProjectId.Value), MessageType = MessageType.Info
                                }));
                            }
                            catch (ConfigurationErrorsException ex)
                            {
                                return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                                    Caption = null, Message = ex.Message, MessageType = MessageType.Error
                                }));
                            }
                        }
                        else
                        {
                            try
                            {
                                _selfConfigManager.SetSharedProjectIdAsync();

                                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                                    Caption = null, Message = MESSAGE_SHARED_PROJECT, MessageType = MessageType.Info
                                }));
                            }
                            catch (ConfigurationErrorsException ex)
                            {
                                return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                                    Caption = null, Message = ex.Message, MessageType = MessageType.Error
                                }));
                            }
                        }
                    }
                    else
                    {
                        SubscriptionStatusResults results = await _subscriptionProvider.GetSubscriptionsStatusAsync(actualToken, subscriptions);

                        if (results.Status == SubscriptionStatus.Active)
                        {
                            if (results.Projects.Any(p => p.Inactive == false))
                            {
                                AddSecurityInfoToViewBag();

                                return(View("SelectOrCreateProject", new SelectProjectViewModel {
                                    Projects = results.Projects.Where(p => p.Inactive == false)
                                }));
                            }
                            else
                            {
                                try
                                {
                                    var projectId = await _selfConfigManager.DeployAndSetSampleProject(actualToken, user);

                                    return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                                        Caption = null, Message = string.Format(MESSAGE_NEW_SAMPLE_PROJECT, projectId), MessageType = MessageType.Info
                                    }));
                                }
                                catch (ConfigurationErrorsException ex)
                                {
                                    return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                                        Caption = null, Message = ex.Message, MessageType = MessageType.Error
                                    }));
                                }
                                catch (DeliveryException ex)
                                {
                                    return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                                        Caption = null, Message = ex.Message, MessageType = MessageType.Error
                                    }));
                                }
                            }
                        }
                        else
                        {
                            ViewBag.EndAt = results.EndAt;

                            return(View(results.Status.ToString(), new SelectProjectViewModel {
                                Projects = results.Projects.Where(p => p.Inactive == false)
                            }));
                        }
                    }
                }
                catch (JsonException ex)
                {
                    return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                        Caption = null, Message = $"{CAPTION_DESERIALIZATION_ERROR}: {ex.Message}", MessageType = MessageType.Error
                    }));
                }
            }
            else
            {
                return(RedirectHelpers.GetSelfConfigIndexResult(new MessageModel {
                    Caption = null, Message = MESSAGE_UNAUTHENTICATED, MessageType = MessageType.Error
                }));
            }
        }
        public async Task <ActionResult> Recheck(string token)
        {
            string actualToken = token ?? GetToken();

            if (!string.IsNullOrEmpty(actualToken))
            {
                try
                {
                    if (!string.IsNullOrEmpty(token))
                    {
                        AddAuthenticationCookie(token);
                    }

                    IEnumerable <SubscriptionModel> subscriptions;

                    try
                    {
                        subscriptions = await _subscriptionProvider.GetSubscriptionsAsync(actualToken);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        return(RedirectHelpers.GetSelfConfigRecheckResult(new MessageModel {
                            Caption = null, Message = MESSAGE_UNAUTHENTICATED, MessageType = MessageType.Error
                        }));
                    }

                    if (subscriptions == null || !subscriptions.Any())
                    {
                        return(View("NoSubscriptions"));
                    }
                    else
                    {
                        SubscriptionStatusResults results = await _subscriptionProvider.GetSubscriptionsStatusAsync(actualToken, subscriptions);

                        if (results.Status == SubscriptionStatus.Active)
                        {
                            if (results.Projects.Any(p => p.ProjectId == AppSettingProvider.ProjectId && p.Inactive == false))
                            {
                                try
                                {
                                    AppSettingProvider.SubscriptionExpiresAt = subscriptions.FirstOrDefault(s => s.Projects.Any(p => p.Id == AppSettingProvider.ProjectId))?.CurrentPlan?.EndAt;
                                }
                                catch (ConfigurationErrorsException ex)
                                {
                                    return(RedirectHelpers.GetSelfConfigRecheckResult(new MessageModel {
                                        Caption = null, Message = ex.Message, MessageType = MessageType.Error
                                    }));
                                }

                                return(RedirectHelpers.GetHomeRedirectResult(new MessageModel {
                                    Caption = null, Message = "The previously known expiration date of your subscription does not apply anymore. You can run your sample app as before.", MessageType = MessageType.Info
                                }));
                            }
                            else
                            {
                                AddSecurityInfoToViewBag();

                                return(View("SelectOrCreateProject", new SelectProjectViewModel {
                                    Projects = results.Projects.Where(p => p.Inactive == false)
                                }));
                            }
                        }
                        else
                        {
                            ViewBag.EndAt = results.EndAt;

                            return(View(results.Status.ToString(), new SelectProjectViewModel {
                                Projects = results.Projects.Where(p => p.Inactive == false)
                            }));
                        }
                    }
                }
                catch (JsonException ex)
                {
                    return(RedirectHelpers.GetSelfConfigRecheckResult(new MessageModel {
                        Caption = null, Message = $"{CAPTION_DESERIALIZATION_ERROR}: {ex.Message}", MessageType = MessageType.Error
                    }));
                }
            }
            else
            {
                return(RedirectHelpers.GetSelfConfigRecheckResult(new MessageModel {
                    Caption = null, Message = MESSAGE_UNAUTHENTICATED, MessageType = MessageType.Error
                }));
            }
        }