Beispiel #1
0
        private bool Login(string userName, string password)
        {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                PowerShellLog.Info($"User '{userName}' calling the Remoting Automation service.");

                if (!userName.Contains("\\"))
                {
                    userName = "******" + userName;
                }

                if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceRemoting, userName))
                {
                    PowerShellLog.Error($"User `{userName}` tried to access the service but was not permitted to do so.");
                    return(false);
                }

                var loggedIn = AuthenticationManager.Login(userName, password, false);
                if (!loggedIn)
                {
                    PowerShellLog.Error($"User '{userName}' was not recognized or provided wrong password.");
                }
                else
                {
                    PowerShellLog.Info($"User '{userName}' successfully logged in to the Remoting Automation service.");
                }
                return(loggedIn);
            }
            PowerShellLog.Info($"Unsuccessfuly login with empty username or password. Username: '******'.");
            return(false);
        }
Beispiel #2
0
        public override void Render(HtmlTextWriter output, Ribbon ribbon, Item button, CommandContext context)
        {
            if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name))
            {
                return;
            }
            var psButtons = button.GetChildren();

            foreach (Item psButton in psButtons)
            {
                var command  = (psButton.Fields["Click"] ?? psButton.Fields["Command"]).Value;
                var msg      = Message.Parse(this, command);
                var scriptDb = msg.Arguments["scriptDB"];
                var scriptId = msg.Arguments["script"];

                if (string.IsNullOrWhiteSpace(scriptDb) || string.IsNullOrWhiteSpace(scriptId))
                {
                    continue;
                }

                var scriptItem = Factory.GetDatabase(scriptDb).GetItem(scriptId);

                if (!scriptItem.IsPowerShellScript() ||
                    !RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.ShowRule], context.Items[0]))
                {
                    continue;
                }

                RenderButton(output, psButton.TemplateID, ribbon, Control.GetUniqueID("script"),
                             Translate.Text(psButton.DisplayName), scriptItem["__Icon"], scriptItem[TemplateFieldIDs.ToolTip],
                             command, RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], context.Items[0]), context,
                             psButton.Paths.Path);
            }
        }
Beispiel #3
0
 public override CommandState QueryState(CommandContext context)
 {
     return(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
                                                         false)
         ? CommandState.Enabled
         : CommandState.Hidden);
 }
Beispiel #4
0
        public override Control[] GetSubmenuItems(CommandContext context)
        {
            var controls = base.GetSubmenuItems(context);

            if (controls == null || context.Items.Length != 1 || context.Items[0] == null)
            {
                return(controls);
            }
            if (!
                ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
                                                             false))
            {
                return(controls);
            }


            var menuItems = new List <Control>();

            var roots = ModuleManager.GetFeatureRoots(IntegrationPoints.ContentEditorInsertItemFeature);

            foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.ContentEditorInsertItemFeature))
            {
                ScriptLibraryMenuItem.GetLibraryMenuItems(context.Items[0], menuItems, root);
            }

            if (roots.Count > 0 && controls.Length > 0)
            {
                menuItems.Add(new MenuDivider());
            }
            menuItems.AddRange(controls);
            return(menuItems.ToArray());
        }
Beispiel #5
0
        protected override void ProcessRecord()
        {
            LogErrors(() =>
            {
                if (!CheckSessionCanDoInteractiveAction())
                {
                    return;
                }

                object content;
                InputObject = InputObject.BaseObject();

                switch (InputObject)
                {
                case Stream inputObject:
                    {
                        using (var stream = inputObject)
                        {
                            var bytes = new byte[stream.Length];
                            stream.Seek(0, SeekOrigin.Begin);
                            stream.Read(bytes, 0, (int)stream.Length);
                            content = bytes;
                        }

                        break;
                    }

                case FileInfo _:
                case string _:
                case byte[] _:
                    content = InputObject;
                    break;

                case string[] strings:
                    content = strings.ToList().Aggregate((accumulated, next) =>
                                                         accumulated + "\n" + next);
                    break;

                default:
                    WriteError(typeof(FormatException), "InputObject must be of type string, string[], byte[], Stream or FileInfo",
                               ErrorIds.InvalidItemType, ErrorCategory.InvalidType, InputObject, true);
                    WriteObject(false);
                    return;
                }

                if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceHandleDownload, Sitecore.Context.User.Name))
                {
                    WriteError(typeof(FormatException), "Handle Download Service is disabled or user is not authorized.",
                               ErrorIds.InsufficientSecurityRights, ErrorCategory.PermissionDenied, InputObject, true);
                    WriteObject(false);
                    return;
                }

                LogErrors(() =>
                {
                    WriteObject(true);
                    PutMessage(new OutDownloadMessage(content, Name, ContentType));
                });
            });
        }
        public bool LoginUser(string userName, string password)
        {
            if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceClient, userName))
            {
                return(false);
            }

            if (!userName.Contains("\\"))
            {
                userName = "******" + userName;
            }

            if (Sitecore.Context.IsLoggedIn)
            {
                if (Sitecore.Context.User.Name.Equals(userName, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
                Sitecore.Context.Logout();
            }

            if (!LicenseManager.HasContentManager && !LicenseManager.HasExpress)
            {
                throw new AccessDeniedException("A required license is missing");
            }
            Assert.IsTrue(Membership.ValidateUser(userName, password), "Unknown username or password.");
            var user = Sitecore.Security.Accounts.User.FromName(userName, true);

            UserSwitcher.Enter(user);
            return(true);
        }
Beispiel #7
0
        protected override void OnLoad(EventArgs e)
        {
            Assert.CanRunApplication("PowerShell/PowerShellIse");
            Assert.IsTrue(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceClient, Context.User.Name, false), "Application access denied.");

            base.OnLoad(e);

            if (Monitor == null)
            {
                if (!Context.ClientPage.IsEvent)
                {
                    Monitor = new SpeJobMonitor {
                        ID = "Monitor"
                    };
                    Context.ClientPage.Controls.Add(Monitor);
                }
                else
                {
                    Monitor = (SpeJobMonitor)Context.ClientPage.FindControl("Monitor");
                }
            }
            Monitor.JobFinished += MonitorOnJobFinished;
            if (Context.ClientPage.IsEvent)
            {
                return;
            }

            var settings = ApplicationSettings.GetInstance(ApplicationNames.IseConsole);

            if (settings.SaveLastScript)
            {
                Editor.Value = settings.LastScript;
            }

            var itemId = WebUtil.GetQueryString("id");
            var itemDb = WebUtil.GetQueryString("db");

            if (itemId.Length > 0)
            {
                ScriptItemId = itemId;
                ScriptItemDb = itemDb;
                LoadItem(itemDb, itemId);
            }

            ContextItemDb = Context.ContentDatabase.Name;
            var contextItem = Context.ContentDatabase.GetItem(Context.Site.ContentStartPath) ??
                              UIUtil.GetHomeItem(Context.User);

            ContextItemId = contextItem?.ID.ToString() ?? String.Empty;

            CurrentSessionId = DefaultSessionName;
            CurrentUser      = DefaultUser;
            CurrentLanguage  = DefaultLanguage;
            ParentFrameName  = WebUtil.GetQueryString("pfn");
            UpdateRibbon();
        }
        public override void Process(GetChromeDataArgs args)
        {
            var isAuthorized = ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name);

            if (!isAuthorized)
            {
                return;
            }

            Assert.ArgumentNotNull(args, "args");
            var page = Sitecore.Context.Item;

            if (page == null)
            {
                // a bit of a hacky way to determine the caller so we can have page context
                var parameters = new UrlString("?" + Context.Items["SC_FORM"]);
                var itemId     = ID.Parse(parameters.Parameters["itemid"], args.Item.ID);
                var language   = string.IsNullOrWhiteSpace(parameters.Parameters["language"])
                    ? args.Item.Language
                    : LanguageManager.GetLanguage(parameters.Parameters["language"]);
                page = args.Item.Database.GetItem(itemId, language);
            }

            var chromeType = args.ChromeType;
            var chromeName = args.ChromeData.DisplayName;
            var click      = "webedit:script(scriptId={0}, scriptdB={1})";

            args.CommandContext.Parameters["pageId"]     = page.ID.ToString();
            args.CommandContext.Parameters["pageLang"]   = page.Language.Name;
            args.CommandContext.Parameters["pageVer"]    = page.Version.Number.ToString();
            args.CommandContext.Parameters["ChromeType"] = chromeType;
            args.CommandContext.Parameters["ChromeName"] = chromeName;
            var ruleContext = new RuleContext
            {
                Item = args.Item
            };

            foreach (var parameter in args.CommandContext.Parameters.AllKeys)
            {
                ruleContext.Parameters[parameter] = args.CommandContext.Parameters[parameter];
            }

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                if (!libraryItem.HasChildren)
                {
                    return;
                }

                AddButton(args, libraryItem, ruleContext, click);
            }
        }
        private static bool CheckIsUserAuthorized(HttpContext context, string authUserName, string serviceName)
        {
            var isAuthorized = ServiceAuthorizationManager.IsUserAuthorized(serviceName, authUserName);

            if (isAuthorized)
            {
                return(true);
            }

            context.Response.StatusCode        = 401;
            context.Response.StatusDescription = $"The specified user {authUserName} is not authorized for the service {serviceName}.";
            context.Response.SuppressFormsAuthenticationRedirect = true;
            PowerShellLog.Error($"Attempt to call the '{serviceName}' service failed as user '{authUserName}' was not authorized.");

            return(false);
        }
Beispiel #10
0
        internal static void GetLibraryMenuItems(Item contextItem, List <Control> menuItems, Item parent)
        {
            if (parent == null)
            {
                return;
            }

            if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name))
            {
                return;
            }


            foreach (var scriptItem in parent.Children.Where(p => p.IsPowerShellScript() || p.IsPowerShellLibrary()))
            {
                if (!RulesUtils.EvaluateRules(scriptItem[FieldNames.ShowRule], contextItem))
                {
                    continue;
                }

                if (contextItem == null && !RulesUtils.EvaluateRules(scriptItem[FieldNames.ShowRule], scriptItem))
                {
                    continue;
                }

                var menuItem = new MenuItem
                {
                    Header   = scriptItem.DisplayName,
                    Icon     = scriptItem.Appearance.Icon,
                    ID       = scriptItem.ID.ToShortID().ToString(),
                    Disabled = !RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], contextItem),
                    ToolTip  = scriptItem.Appearance.ShortDescription
                };
                menuItem.Attributes.Add(FieldIDs.Sortorder.ToString(), scriptItem[FieldIDs.Sortorder]);

                if (scriptItem.IsPowerShellScript())
                {
                    menuItem.Click = contextItem != null ? $"item:executescript(id={contextItem.ID},db={contextItem.Database.Name},script={scriptItem.ID},scriptDb={scriptItem.Database.Name})" : $"item:executescript(script={scriptItem.ID},scriptDb={scriptItem.Database.Name})";
                }
                else
                {
                    menuItem.Type  = MenuItemType.Submenu;
                    menuItem.Click = contextItem != null ? $"item:scriptlibrary(id={contextItem.ID},db={contextItem.Database.Name},scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})" : $"item:scriptlibrary(scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})";
                }
                menuItems.Add(menuItem);
            }
        }
Beispiel #11
0
        internal static void GetLibraryMenuItems(Item contextItem, List <Control> menuItems, Item parent)
        {
            if (parent == null)
            {
                return;
            }

            if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
                                                              false))
            {
                return;
            }


            var scriptTemplateId       = new ID("{DD22F1B3-BD87-4DB2-9E7D-F7A496888D43}");
            var scriptLibaryTemplateId = new ID("{AB154D3D-1126-4AB4-AC21-8B86E6BD70EA}");

            foreach (var scriptItem in parent.Children.Where(p => p.TemplateID == scriptTemplateId || p.TemplateID == scriptLibaryTemplateId))
            {
                if (!RulesUtils.EvaluateRules(scriptItem["ShowRule"], contextItem))
                {
                    continue;
                }

                var menuItem = new MenuItem
                {
                    Header   = scriptItem.DisplayName,
                    Icon     = scriptItem.Appearance.Icon,
                    ID       = scriptItem.ID.ToShortID().ToString(),
                    Disabled = !RulesUtils.EvaluateRules(scriptItem["EnableRule"], contextItem)
                };

                if (scriptItem.IsPowerShellScript())
                {
                    menuItem.Click = contextItem != null ? $"item:executescript(id={contextItem.ID},db={contextItem.Database.Name},script={scriptItem.ID},scriptDb={scriptItem.Database.Name})" : $"item:executescript(script={scriptItem.ID},scriptDb={scriptItem.Database.Name})";
                }
                else
                {
                    menuItem.Type  = MenuItemType.Submenu;
                    menuItem.Click = contextItem != null ? $"item:scriptlibrary(id={contextItem.ID},db={contextItem.Database.Name},scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})" : $"item:scriptlibrary(scriptPath={scriptItem.Paths.Path},scriptDB={scriptItem.Database.Name},menuItemId={menuItem.ID})";
                }
                menuItems.Add(menuItem);
            }
        }
Beispiel #12
0
        public void Process(GetMastersArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            try
            {
                if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name))
                {
                    return;
                }

                foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.ContentEditorInsertItemFeature))
                {
                    GetMasters(root, args);
                }
            }
            catch (Exception e)
            {
                PowerShellLog.Error("Exception while getting item Masters", e);
            }
        }
Beispiel #13
0
        private static bool CheckIsUserAuthorized(HttpContext context, string authUserName, string serviceName)
        {
            var isAuthorized = ServiceAuthorizationManager.IsUserAuthorized(serviceName, authUserName);

            if (isAuthorized)
            {
                return(true);
            }

            var errorMessage = $"The specified user {authUserName} is not authorized for the {serviceName} service.";

            context.Response.StatusCode        = 401;
            context.Response.StatusDescription = errorMessage;
            context.Response.SuppressFormsAuthenticationRedirect = true;
            context.Response.TrySkipIisCustomErrors = true;
            context.Response.ContentType            = "text/plain";
            PowerShellLog.Warn(errorMessage);

            return(false);
        }
        protected override void OnLoad(EventArgs e)
        {
            Assert.CanRunApplication("PowerShell/PowerShell Console");
            Assert.IsTrue(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceClient, Context.User.Name, false), "Application access denied.");
            base.OnLoad(e);
            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            HttpContext.Current.Response.AddHeader("X-UA-Compatible", "IE=edge");
            var settings = ApplicationSettings.GetInstance(ApplicationNames.AjaxConsole, false);

            if (!Context.ClientPage.IsEvent)
            {
                Options.Text = @"<script type='text/javascript'>" +
                               @"$ise(function() { cognifide.powershell.setOptions({ initialPoll: " +
                               WebServiceSettings.InitialPollMillis + @", maxPoll: " +
                               WebServiceSettings.MaxmimumPollMillis + @", fontSize: " +
                               settings.FontSize + $", fontFamily: '{settings.FontFamilyStyle}' }});}});</script>" +
                               @"<style>#terminal {" +
                               $"color: {OutputLine.ProcessHtmlColor(settings.ForegroundColor)};" +
                               $"background-color: {OutputLine.ProcessHtmlColor(settings.BackgroundColor)};" +
                               $"font-family: inherit;" + "}</style>";
            }
            SheerResponse.SetDialogValue("ok");
        }
Beispiel #15
0
        public override void Render(HtmlTextWriter output, Ribbon ribbon, Item button, CommandContext context)
        {
            if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name,
                                                              false))
            {
                return;
            }
            var psButtons = button.GetChildren();

            foreach (Item psButton in psButtons)
            {
                var msg      = Message.Parse(this, psButton["Click"]);
                var scriptDb = msg.Arguments["scriptDB"];
                var scriptId = msg.Arguments["script"];

                if (string.IsNullOrWhiteSpace(scriptDb) || string.IsNullOrWhiteSpace(scriptId))
                {
                    continue;
                }

                var scriptItem = Factory.GetDatabase(scriptDb).GetItem(scriptId);
                if (scriptItem == null || !RulesUtils.EvaluateRules(scriptItem["ShowRule"], context.Items[0]))
                {
                    continue;
                }

                RenderLargeButton(output, ribbon, Control.GetUniqueID("script"),
                                  Translate.Text(scriptItem.DisplayName),
                                  scriptItem["__Icon"], string.Empty,
                                  psButton["Click"],
                                  RulesUtils.EvaluateRules(scriptItem["EnableRule"], context.Items[0]),
                                  false, context);

                return;
            }
        }
Beispiel #16
0
        public void ProcessRequest(HttpContext context)
        {
            var request           = HttpContext.Current.Request;
            var userName          = request.Params.Get("user");
            var password          = request.Params.Get("password");
            var itemParam         = request.Params.Get("script");
            var pathParam         = request.Params.Get("path");
            var originParam       = request.Params.Get("scriptDb");
            var apiVersion        = request.Params.Get("apiVersion");
            var serviceMappingKey = request.HttpMethod + "/" + apiVersion;
            var isUpload          = request.HttpMethod.Is("POST") && request.InputStream.Length > 0;
            var unpackZip         = request.Params.Get("skipunpack").IsNot("true");
            var skipExisting      = request.Params.Get("skipexisting").Is("true");
            var serviceName       = apiVersionToServiceMapping.ContainsKey(serviceMappingKey)
                ? apiVersionToServiceMapping[serviceMappingKey]
                : string.Empty;

            // verify that the service is enabled
            if (!CheckServiceEnabled(apiVersion, request.HttpMethod))
            {
                PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled.");
                return;
            }

            // verify that the user is authorized to access the end point
            var authUserName = string.IsNullOrEmpty(userName) ? Context.User.Name : userName;

            if (!ServiceAuthorizationManager.IsUserAuthorized(serviceName, authUserName, false))
            {
                HttpContext.Current.Response.StatusCode = 401;
                PowerShellLog.Error($"Attempt to call the '{apiVersion}' service failed as user '{userName}' was not authorized.");
                return;
            }

            // login user if specified explicitly
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                var account = new AccountIdentity(userName);
                AuthenticationManager.Login(account.Name, password, false);
            }

            var isAuthenticated    = Context.IsLoggedIn;
            var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated || string.IsNullOrEmpty(originParam) || originParam.Is("current");
            var scriptDb           = useContextDatabase ? Context.Database : Database.GetDatabase(originParam);
            var dbName             = scriptDb.Name;

            if (!CheckServiceAuthentication(apiVersion, isAuthenticated))
            {
                PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as - user not logged in, authentication failed or no credentials provided.");
                return;
            }

            if (isUpload)
            {
                switch (apiVersion)
                {
                case "media":
                    if (ZipUtils.IsZipContent(request.InputStream) && unpackZip)
                    {
                        PowerShellLog.Debug("The uploaded asset will be extracted to Media Library.");
                        using (var packageReader = new Sitecore.Zip.ZipReader(request.InputStream))
                        {
                            foreach (var zipEntry in packageReader.Entries)
                            {
                                if (!zipEntry.IsDirectory)
                                {
                                    ProcessMediaUpload(zipEntry.GetStream(), scriptDb, itemParam, zipEntry.Name, skipExisting);
                                }
                            }
                        }
                    }
                    else
                    {
                        ProcessMediaUpload(request.InputStream, scriptDb, itemParam, null, skipExisting);
                    }
                    break;

                case "file":
                    ProcessFileUpload(request.InputStream, originParam, pathParam);
                    break;

                default:
                    PowerShellLog.Error($"Requested API/Version ({apiVersion}) is not supported.");
                    break;
                }
                return;
            }

            Item scriptItem;

            switch (apiVersion)
            {
            case "1":
                scriptItem = scriptDb.GetItem(itemParam) ??
                             scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam);
                break;

            case "media":
                ProcessMediaDownload(scriptDb, itemParam);
                return;

            case "file":
                ProcessFileDownload(originParam, pathParam);
                return;

            case "handle":
                ProcessHandle(originParam);
                return;

            default:
                UpdateCache(dbName);
                if (!apiScripts.ContainsKey(dbName))
                {
                    HttpContext.Current.Response.StatusCode = 404;
                    return;
                }
                var dbScripts = apiScripts[scriptDb.Name];
                if (!dbScripts.ContainsKey(itemParam))
                {
                    HttpContext.Current.Response.StatusCode = 404;
                    return;
                }
                scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id);
                apiScripts = null;
                break;
            }

            ProcessScript(context, scriptItem);
        }
        public void ProcessRequest(HttpContext context)
        {
            var request           = HttpContext.Current.Request;
            var userName          = request.Params.Get("user");
            var password          = request.Params.Get("password");
            var itemParam         = request.Params.Get("script");
            var pathParam         = request.Params.Get("path");
            var originParam       = request.Params.Get("scriptDb");
            var apiVersion        = request.Params.Get("apiVersion");
            var serviceMappingKey = request.HttpMethod + "/" + apiVersion;
            var isUpload          = request.HttpMethod.Is("POST") && request.InputStream.Length > 0;
            var unpackZip         = request.Params.Get("skipunpack").IsNot("true");
            var skipExisting      = request.Params.Get("skipexisting").Is("true");
            var scDB = request.Params.Get("sc_database");

            var serviceName = apiVersionToServiceMapping.ContainsKey(serviceMappingKey)
                ? apiVersionToServiceMapping[serviceMappingKey]
                : string.Empty;

            // verify that the service is enabled
            if (!CheckServiceEnabled(apiVersion, request.HttpMethod))
            {
                PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled.");
                return;
            }

            // verify that the user is authorized to access the end point
            var authUserName = string.IsNullOrEmpty(userName) ? Context.User.Name : userName;
            var identity     = new AccountIdentity(authUserName);

            if (!ServiceAuthorizationManager.IsUserAuthorized(serviceName, identity.Name))
            {
                HttpContext.Current.Response.StatusCode = 401;
                PowerShellLog.Error(
                    $"Attempt to call the '{serviceMappingKey}' service failed as user '{userName}' was not authorized.");
                return;
            }

            lock (loginLock)
            {
                // login user if specified explicitly
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    AuthenticationManager.Login(identity.Name, password, false);
                }
            }

            var isAuthenticated = Context.IsLoggedIn;

            // in some cases we need to set the database as it's still set to web after authentication
            if (!scDB.IsNullOrEmpty())
            {
                Context.Database = Database.GetDatabase(scDB);
            }

            var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated ||
                                     string.IsNullOrEmpty(originParam) || originParam.Is("current");
            var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam);
            var dbName   = scriptDb?.Name;

            if (!CheckServiceAuthentication(apiVersion, isAuthenticated))
            {
                PowerShellLog.Error(
                    $"Attempt to call the {serviceMappingKey} service failed as - user not logged in, authentication failed or no credentials provided.");
                return;
            }

            if (scriptDb == null && !apiVersion.Is("file") && !apiVersion.Is("handle"))
            {
                PowerShellLog.Error(
                    $"The '{serviceMappingKey}' service requires a database but none was found in parameters or Context.");
                return;
            }

            PowerShellLog.Info($"'{serviceMappingKey}' called by user: '******'");
            PowerShellLog.Debug($"'{request.Url}'");

            Item scriptItem;

            switch (apiVersion)
            {
            case "1":
                scriptItem = scriptDb.GetItem(itemParam) ??
                             scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam);
                break;

            case "media":
                if (isUpload)
                {
                    if (ZipUtils.IsZipContent(request.InputStream) && unpackZip)
                    {
                        PowerShellLog.Debug("The uploaded asset will be extracted to Media Library.");
                        using (var packageReader = new Sitecore.Zip.ZipReader(request.InputStream))
                        {
                            itemParam = Path.GetDirectoryName(itemParam.TrimEnd('\\', '/'));
                            foreach (var zipEntry in packageReader.Entries)
                            {
                                if (!zipEntry.IsDirectory && zipEntry.Size > 0)
                                {
                                    ProcessMediaUpload(zipEntry.GetStream(), scriptDb, $"{itemParam}/{zipEntry.Name}",
                                                       skipExisting);
                                }
                            }
                        }
                    }
                    else if (request.Files?.AllKeys?.Length > 0)
                    {
                        foreach (string fileName in request.Files.Keys)
                        {
                            var file = request.Files[fileName];
                            ProcessMediaUpload(file.InputStream, scriptDb, $"{itemParam}/{file.FileName}",
                                               skipExisting);
                        }
                    }
                    else
                    {
                        ProcessMediaUpload(request.InputStream, scriptDb, itemParam, skipExisting);
                    }
                }
                else
                {
                    ProcessMediaDownload(scriptDb, itemParam);
                }
                return;

            case "file":
                if (isUpload)
                {
                    ProcessFileUpload(request.InputStream, originParam, pathParam);
                }
                else
                {
                    ProcessFileDownload(originParam, pathParam);
                }
                return;

            case "handle":
                ProcessHandle(originParam);
                return;

            case "2":
                UpdateCache(dbName);
                if (!apiScripts.ContainsKey(dbName))
                {
                    HttpContext.Current.Response.StatusCode = 404;
                    return;
                }
                var dbScripts = apiScripts[dbName];
                if (!dbScripts.ContainsKey(itemParam))
                {
                    HttpContext.Current.Response.StatusCode = 404;
                    return;
                }
                scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id);
                apiScripts = null;
                break;

            default:
                PowerShellLog.Error($"Requested API/Version ({serviceMappingKey}) is not supported.");
                return;
            }

            var streams = new Dictionary <string, Stream>();

            if (request.Files?.AllKeys?.Length > 0)
            {
                foreach (string fileName in request.Files.AllKeys)
                {
                    streams.Add(fileName, request.Files[fileName].InputStream);
                }
            }
            else if (request.InputStream != null)
            {
                streams.Add("stream", request.InputStream);
            }

            ProcessScript(context, scriptItem, streams);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            Assert.IsTrue(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name, false), "Application access denied.");

            if (!Context.ClientPage.IsEvent)
            {
                ItemId   = WebUtil.GetQueryString("id");
                ItemDb   = WebUtil.GetQueryString("db");
                ItemLang = WebUtil.GetQueryString("lang");
                ItemVer  = WebUtil.GetQueryString("ver");

                PageId   = WebUtil.GetQueryString("pageId");
                PageLang = WebUtil.GetQueryString("pageLang");
                PageVer  = WebUtil.GetQueryString("pageVer");

                AppMode   = WebUtil.GetQueryString("AppMode") == "1";
                HasScript = WebUtil.GetQueryString("HasScript") == "1";

                ScriptId = WebUtil.GetQueryString("scriptId");
                ScriptDb = WebUtil.GetQueryString("scriptDb");

                RenderingId = WebUtil.GetQueryString("RenderingId");


                ResultsError.Text = Texts.PowerShellRunner_OnLoad_View_script_results_and_errors;
                ResultsOK.Text    = Texts.PowerShellRunner_OnLoad_View_script_results;
                Copyright.Alt     = Texts.PowerShellRunner_OnLoad_Show_copyright__;
                Title.Text        = Texts.PowerShellRunner_UpdateProgress_Running_script___;

                if (!string.IsNullOrEmpty(ScriptId) && !string.IsNullOrEmpty(ScriptId))
                {
                    var scriptItem = Factory.GetDatabase(ScriptDb).GetItem(new ID(ScriptId));
                    scriptItem.Fields.ReadAll();
                    Icon.Src = scriptItem.Appearance.Icon;

                    PersistentId = string.IsNullOrEmpty(WebUtil.GetQueryString("sessionKey"))
                        ? scriptItem[ScriptItemFieldNames.PersistentSessionId]
                        : WebUtil.GetQueryString("sessionKey");

                    ScriptContent     = scriptItem[ScriptItemFieldNames.Script];
                    DialogHeader.Text = scriptItem.DisplayName;
                }
                else
                {
                    PersistentId = string.IsNullOrEmpty(WebUtil.GetQueryString("sessionKey"))
                        ? string.Empty
                        : WebUtil.GetQueryString("sessionKey");
                    ScriptContent = ScriptSessionManager.GetSession(PersistentId).JobScript;
                }

                if (Monitor != null)
                {
                    return;
                }

                Monitor = new SpeJobMonitor {
                    ID = "Monitor"
                };
                Context.ClientPage.Controls.Add(Monitor);
            }
            else
            {
                if (Monitor == null)
                {
                    Monitor = Context.ClientPage.FindControl("Monitor") as SpeJobMonitor;
                }

                if (Context.ClientPage.ClientRequest.Parameters == "pstaskmonitor:check" &&
                    PreviousProgressValue.Text != CurrentProgressValue.Text)
                {
                    var percentComplete = Int32.Parse(CurrentProgressValue.Text);
                    SheerResponse.Eval($@"updateProgress('#progressbar',{percentComplete});");
                    PreviousProgressValue.Text = CurrentProgressValue.Text;
                }
            }
            Monitor.JobFinished += MonitorOnJobFinished;
        }
        protected override void ProcessRecord()
        {
            LogErrors(() =>
            {
                if (!CheckSessionCanDoInteractiveAction())
                {
                    return;
                }


                object content;
                InputObject = InputObject.BaseObject();

                if (InputObject is Stream)
                {
                    using (var stream = InputObject as Stream)
                    {
                        byte[] bytes = new byte[stream.Length];
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Read(bytes, 0, (int)stream.Length);
                        content = bytes;
                    }
                }
                else if (InputObject is FileInfo)
                {
                    content = InputObject;
                }
                else if (InputObject is string)
                {
                    content = InputObject;
                }
                else if (InputObject is string[])
                {
                    content = (InputObject as string[]).ToList().Aggregate((accumulated, next) =>
                                                                           accumulated + "\n" + next);
                }
                else if (InputObject is byte[])
                {
                    content = InputObject;
                }
                else
                {
                    WriteError(typeof(FormatException), "InputObject must be of type string, strings[], Stream byte[]",
                               ErrorIds.InvalidItemType, ErrorCategory.InvalidType, InputObject, true);
                    WriteObject(false);
                    return;
                }

                if (!WebServiceSettings.ServiceEnabledHandleDownload ||
                    !ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceHandleDownload,
                                                                  Sitecore.Context.User.Name, false))
                {
                    WriteError(typeof(FormatException), "Handle Download Service is disabled or user is not authorized.",
                               ErrorIds.InsufficientSecurityRights, ErrorCategory.PermissionDenied, InputObject, true);
                    WriteObject(false);
                    return;
                }

                LogErrors(() =>
                {
                    WriteObject(true);
                    PutMessage(new OutDownloadMessage(content, Name, ContentType));
                });
            });
        }
        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull(e, "e");
            Assert.IsTrue(ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceExecution, Context.User.Name, false), "Application access denied.");
            base.OnLoad(e);

            Context.ClientPage.ClientResponse.SetDialogValue(Hidden.Value);
            if (Context.ClientPage.IsEvent)
            {
                return;
            }

            UrlHandle handle = null;

            if (!UrlHandle.TryGetHandle(out handle))
            {
                FileNameLabel.Text =
                    "Invalid dialog invocation.";
                SizeLabel.Visible     = false;
                PathPrefix.Visible    = false;
                SizePrefix.Visible    = false;
                OK.Visible            = false;
                DownloadImage.Visible = false;
                ErrorImage.Visible    = true;
                return;
            }

            FileName = handle["fn"];

            ItemUri = handle["uri"];
            ItemDb  = handle["db"];

            bool showFullPath;

            if (!bool.TryParse(handle["fp"], out showFullPath))
            {
                showFullPath = false;
            }

            Text.Text = handle["te"];

            if (!string.IsNullOrEmpty(ItemUri))
            {
                var item = Factory.GetDatabase(ItemDb).GetItem(new DataUri(ItemUri));
                if (MediaManager.HasMediaContent(item))
                {
                    FileNameLabel.Text = (showFullPath ? item.GetProviderPath() : item.Name)
                                         + "." + item["Extension"];
                    long size;
                    SizeLabel.Text = Int64.TryParse(item["size"], out size) ? ToFileSize(size) : "unknown";
                }
                else
                {
                    SheerResponse.Alert("There is no file attached.");
                }
            }
            else if (!string.IsNullOrEmpty(FileName))
            {
                // check if file in approved location
                var filePath    = FileUtil.MapPath(FileName);
                var webSitePath = FileUtil.MapPath("/");
                var dataPath    = FileUtil.MapPath(Settings.DataFolder);

                if (!filePath.StartsWith(webSitePath, StringComparison.InvariantCultureIgnoreCase) &&
                    !filePath.StartsWith(dataPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    FileNameLabel.Text =
                        "Files from outside of the Sitecore Data and Website folders cannot be downloaded.\n\n" +
                        "Copy the file to the Sitecore Data folder and try again.";
                    SizeLabel.Visible     = false;
                    PathPrefix.Visible    = false;
                    SizePrefix.Visible    = false;
                    OK.Visible            = false;
                    DownloadImage.Visible = false;
                    ErrorImage.Visible    = true;
                    return;
                }

                FileNameLabel.Text = showFullPath ? FileName : Path.GetFileName(FileName);
                SheerResponse.Download(FileName);
                Hidden.Value = "downloaded";
                var file = new FileInfo(FileName);
                SizeLabel.Text = ToFileSize(file.Length);
            }

            var caption = handle["cp"];

            Context.ClientPage.Title = caption;
            Assert.ArgumentNotNull(e, "e");
            base.OnLoad(e);
            Text.Text    = handle["te"];
            Hidden.Value = "cancelled";
            Context.ClientPage.ClientResponse.SetDialogValue(Hidden.Value);
            UrlHandle.DisposeHandle(handle);
        }