예제 #1
0
        public void Should_resolve_policy_violation_handler_for_exception_from_container()
        {
            // Arrange
            var controllerName = NameHelper.Controller<BlogController>();
            const string actionName = "Index";

            var events = new List<ISecurityEvent>();
            SecurityDoctor.Register(events.Add);
            var expectedActionResult = new ViewResult { ViewName = "SomeViewName" };
            var violationHandler = new DenyAnonymousAccessPolicyViolationHandler(expectedActionResult);
            FakeIoC.GetAllInstancesProvider = () => new List<IPolicyViolationHandler>
            {
                violationHandler
            };

            SecurityConfigurator.Configure(policy =>
            {
                policy.ResolveServicesUsing(FakeIoC.GetAllInstances);
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act
            var result = securityHandler.HandleSecurityFor(controllerName, actionName, SecurityContext.Current);

            // Assert
            Assert.That(result, Is.EqualTo(expectedActionResult));
            Assert.That(events.Any(e => e.Message == "Handling security for {0} action {1}.".FormatWith(controllerName, actionName)));
            Assert.That(events.Any(e => e.Message == "Finding policy violation handler using convention {0}.".FormatWith(typeof(FindByPolicyNameConvention))));
            Assert.That(events.Any(e => e.Message == "Found policy violation handler {0}.".FormatWith(violationHandler.GetType().FullName)));
            Assert.That(events.Any(e => e.Message == "Handling violation with {0}.".FormatWith(violationHandler.GetType().FullName)));
            Assert.That(events.Any(e => e.Message == "Done enforcing policies. Violation occured!"));
        }
        public void Should_resolve_policy_violation_handler_for_exception_from_container()
        {
            // Arrange
            var expectedActionResult = new ViewResult { ViewName = "SomeViewName" };
            var violationHandler = new DenyAnonymousAccessPolicyViolationHandler(expectedActionResult);
            FakeIoC.GetAllInstancesProvider = () => new List<IPolicyViolationHandler>
            {
                violationHandler
            };

            SecurityConfigurator.Configure(policy =>
            {
                policy.ResolveServicesUsing(FakeIoC.GetAllInstances);
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act
            var result = securityHandler.HandleSecurityFor(NameHelper.Controller<BlogController>(), "Index", SecurityContext.Current);

            // Assert
            Assert.That(result, Is.EqualTo(expectedActionResult));
        }
        public void Should_throw_ArgumentException_when_actionname_is_null_or_empty()
        {
            // Arrange
            var securityHandler = new SecurityHandler();

            // Assert
            Assert.Throws<ArgumentException>(() => securityHandler.HandleSecurityFor("A", null, _context));
            Assert.Throws<ArgumentException>(() => securityHandler.HandleSecurityFor("A", "", _context));
        }
        public void Should_not_throw_when_when_controllername_is_Blog_and_actionname_is_Index()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor(NameHelper.Controller<BlogController>(), "Index", SecurityContext.Current));
        }
예제 #5
0
        //
        // Constructie
        //
        private DataAccess()
        {
            sysLog.Info("DataAccess startup");

            publicXmlRpcUrl = ConfigurationManager.AppSettings["PUBLIC_XML_RPC_SERVER"];
            privateXmlRpcUrl = ConfigurationManager.AppSettings["PRIVATE_XML_RPC_SERVER"];

            publicExchangeHandler = HandlerHelper.getPublicExchangeHandler(publicXmlRpcUrl);
            publicIndexHandler = HandlerHelper.getPublicIndexHandler(publicXmlRpcUrl);
            publicOrderHandler = HandlerHelper.getPublicOrderHandler(publicXmlRpcUrl);
            publicPortfolioHandler = HandlerHelper.getPublicPortfolioHandler(publicXmlRpcUrl);
            publicSecurityHandler = HandlerHelper.getPublicSecurityHandler(publicXmlRpcUrl);
            publicTransactionHandler = HandlerHelper.getPublicTransactionHandler(publicXmlRpcUrl);
            publicUserHandler = HandlerHelper.getPublicUserHandler(publicXmlRpcUrl);
            publicPointsTransactionHandler = HandlerHelper.getPublicPointsTransactionHandler(publicXmlRpcUrl);

            exchangeCache = new Dictionary<string, IExchange>();
        }
예제 #6
0
        public void Should_not_throw_ConfigurationErrorsException_when_IgnoreMissingConfigurations_is_true()
        {
            // Arrange
            var events = new List<ISecurityEvent>();
            SecurityDoctor.Register(events.Add);
            SecurityConfigurator.Configure(configuration =>
            {
                configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                configuration.Advanced.IgnoreMissingConfiguration();
                configuration.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor("NonConfiguredController", "Action", SecurityContext.Current));
            Assert.That(events.Any(e => e.Message == "Ignoring missing configuration."));
        }
예제 #7
0
        protected override void OnNodeMoved(object sender, NodeOperationEventArgs e)
        {
            // We do not have to deal with content outside of the IMS folder, because
            // moving local groups does not involve any membership change.
            if (!e.OriginalSourcePath.StartsWith(RepositoryStructure.ImsFolderPath + RepositoryPath.PathSeparator) && !e.SourceNode.Path.StartsWith(RepositoryStructure.ImsFolderPath + RepositoryPath.PathSeparator))
            {
                return;
            }

            base.OnNodeMoved(sender, e);

            var movedUsers  = new List <int>();
            var movedGroups = new List <int>();

            // if the moved content is an identity, put it into the appropriate list
            if (e.SourceNode is User)
            {
                movedUsers.Add(e.SourceNode.Id);
            }
            else if (e.SourceNode is Group || e.SourceNode is OrganizationalUnit)
            {
                movedGroups.Add(e.SourceNode.Id);
            }
            else
            {
                // If the moved content is an irrelevant container (e.g. a folder), collect relevant (first-level) child content (users, groups
                // and child orgunits even inside simple subfolders). These are already moved to the new location, but we only need their ids.
                using (new SystemAccount())
                {
                    CollectSecurityIdentityChildren(NodeHead.Get(e.SourceNode.Path), movedUsers, movedGroups);
                }
            }

            // empty collections: nothing to do
            if (movedUsers.Count == 0 && movedGroups.Count == 0)
            {
                return;
            }

            // find the original parent orgunit (if there was one)
            var parent           = Node.LoadNode(RepositoryPath.GetParentPath(e.OriginalSourcePath));
            var originalParentId = 0;
            var targetParentId   = 0;

            if (parent is OrganizationalUnit)
            {
                originalParentId = parent.Id;
            }
            else
            {
                using (new SystemAccount())
                {
                    parent = GetFirstOrgUnitParent(parent);
                    if (parent != null)
                    {
                        originalParentId = parent.Id;
                    }
                }
            }

            // find the target parent orgunit (if there is one)
            using (new SystemAccount())
            {
                parent = GetFirstOrgUnitParent(e.SourceNode);
                if (parent != null)
                {
                    targetParentId = parent.Id;
                }
            }

            // remove relevant child content from the original parent org unit (if it is different from the target)
            if (originalParentId > 0 && originalParentId != targetParentId)
            {
                SecurityHandler.RemoveMembers(originalParentId, movedUsers, movedGroups);
            }

            // add the previously collected identities to the target orgunit (if it is different from the original)
            if (targetParentId > 0 && originalParentId != targetParentId)
            {
                SecurityHandler.AddMembers(targetParentId, movedUsers, movedGroups);
            }
        }
예제 #8
0
 public void Apply()
 {
     ApplyChanges();
     SecurityHandler.Reset();
 }
예제 #9
0
 public void Dispose()
 {
     SecurityHandler.CreateAclEditor()
     .ClearPermission(_entityId, _identityId, _localOnly, _permissions)
     .Apply();
 }
예제 #10
0
        private static ContentView CreateFromActualPath(SNC.Content content, System.Web.UI.Page aspNetPage, ViewMode viewMode, string viewPath)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }
            if (aspNetPage == null)
            {
                throw new ArgumentNullException("aspNetPage");
            }
            if (viewPath == null)
            {
                throw new ArgumentNullException("viewPath");
            }
            if (viewPath.Length == 0)
            {
                throw new ArgumentOutOfRangeException("viewPath", "Parameter 'viewPath' cannot be empty");
            }
            if (viewMode == ViewMode.None)
            {
                throw new ArgumentOutOfRangeException("viewMode", "Parameter 'viewMode' cannot be ViewMode.None");
            }

            string path = String.Concat("~", viewPath);

            if (!SecurityHandler.HasPermission(User.Current, viewPath, 0, 0, PermissionType.RunApplication))
            {
                throw new SecurityException(path, PermissionType.RunApplication);
            }

            ContentView view = GetContentViewFromCache(path);

            // if not in request cache
            if (view == null)
            {
                var addToCache = false;
                try
                {
                    view       = aspNetPage.LoadControl(path) as ContentView;
                    addToCache = true;
                }
                catch (Exception e) //logged
                {
                    Logger.WriteException(e);
                    var errorContentViewPath         = RepositoryPath.Combine(Repository.ContentViewFolderName, "Error.ascx");
                    var resolvedErrorContentViewPath = SkinManager.Resolve(errorContentViewPath);
                    path = String.Concat("~", resolvedErrorContentViewPath);
                    view = aspNetPage.LoadControl(path) as ContentView;
                    view.ContentException = e;
                }
                if (view == null)
                {
                    throw new ApplicationException(string.Format("ContentView instantiation via LoadControl for path '{0}' failed.", path));
                }
                if (addToCache)
                {
                    AddContentViewToCache(path, view);
                }
            }

            view.Initialize(content, viewMode);
            return(view);
        }
        void OnAuthorizeRequest(object sender, EventArgs e)
        {
            PortalContext currentPortalContext = PortalContext.Current;
            var           d = NodeHead.Get("/Root");

            if (currentPortalContext != null && currentPortalContext.IsRequestedResourceExistInRepository)
            {
                var authMode = currentPortalContext.AuthenticationMode;
                //install time
                if (string.IsNullOrEmpty(authMode) && currentPortalContext.Site == null)
                {
                    authMode = "None";
                }

                if (string.IsNullOrEmpty(authMode))
                {
                    authMode = WebConfigurationManager.AppSettings["DefaultAuthenticationMode"];
                }

                bool appPerm = false;
                if (authMode == "Forms")
                {
                    appPerm = currentPortalContext.CurrentAction.CheckPermission();
                }
                else if (authMode == "Windows")
                {
                    currentPortalContext.CurrentAction.AssertPermissions();
                    appPerm = true;
                }
                else
                {
                    throw new NotSupportedException("None authentication is not supported");
                }

                var application     = sender as HttpApplication;
                var currentUser     = application.Context.User.Identity as User;
                var path            = currentPortalContext.RepositoryPath;
                var nodeHead        = NodeHead.Get(path);
                var isOwner         = nodeHead.CreatorId == currentUser.Id;
                var permissionValue = SecurityHandler.GetPermission(nodeHead, PermissionType.Open);

                if (permissionValue != PermissionValue.Allow || !appPerm)
                {
                    switch (authMode)
                    {
                    case "Forms":
                        if (User.Current.IsAuthenticated)
                        {
                            // user is authenticated, but has no permissions: return 403
                            application.Context.Response.StatusCode = 403;
                            application.Context.Response.Flush();
                            application.Context.Response.Close();
                        }
                        else
                        {
                            // user is not authenticated and visitor has no permissions: redirect to login page
                            // Get the login page Url (eg. http://localhost:1315/home/login)
                            string loginPageUrl = currentPortalContext.GetLoginPageUrl();
                            // Append trailing slash
                            if (loginPageUrl != null && !loginPageUrl.EndsWith("/"))
                            {
                                loginPageUrl = loginPageUrl + "/";
                            }

                            // Cut down the querystring (eg. drop ?Param1=value1@Param2=value2)
                            string currentRequestUrlWithoutQueryString = currentPortalContext.OriginalUri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.Unescaped);

                            // Append trailing slash
                            if (!currentRequestUrlWithoutQueryString.EndsWith("/"))
                            {
                                currentRequestUrlWithoutQueryString = currentRequestUrlWithoutQueryString + "/";
                            }

                            // Redirect to the login page, if neccessary.
                            if (currentRequestUrlWithoutQueryString != loginPageUrl)
                            {
                                application.Context.Response.Redirect(loginPageUrl + "?OriginalUrl=" + System.Web.HttpUtility.UrlEncode(currentPortalContext.OriginalUri.ToString()), true);
                            }
                        }
                        break;

                    //case "Windows":
                    //    application.Context.Response.Clear();
                    //    application.Context.Response.Buffer = true;
                    //    application.Context.Response.Status = "401 Unauthorized";
                    //    application.Context.Response.AddHeader("WWW-Authenticate", "NTLM");
                    //    application.Context.Response.End();
                    //    break;
                    default:
                        AuthenticationHelper.DenyAccess(application);
                        break;
                    }
                }
            }
        }
예제 #12
0
        /// <summary>
        /// Gets the text content from a given path and processes it. Override this method if you want to implement custom logic when each file is loaded.
        /// </summary>
        /// <param name="path">The path from which to the content should be retrieved.</param>
        /// <returns>The processed text content of the given path, or null if it was not found.</returns>
        protected virtual string GetTextFromPath(string path)
        {
            if (path[0] == '/')
            {
                // This is a repository URL

                var fsPath       = HostingEnvironment.MapPath(path);
                var fileNodeHead = NodeHead.Get(path);
                var fileNode     = fileNodeHead != null && SecurityHandler.HasPermission(fileNodeHead, PermissionType.Open)
                    ? Node.Load <File>(path)
                    : null;

                System.IO.Stream stream = null;

                if ((RepositoryPathProvider.DiskFSSupportMode == DiskFSSupportMode.Prefer || fileNode == null) && System.IO.File.Exists(fsPath))
                {
                    // If DiskFsSupportMode is Prefer and the file exists, or it's fallback but the node doesn't exist in the repo get it from the file system
                    stream = new System.IO.FileStream(fsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                }
                else if (path[0] == '/' && fileNode != null)
                {
                    // If the node exists, get it from the repo
                    stream = fileNode.Binary.GetStream();
                }
                else if (path.StartsWith("/" + ResourceHandler.UrlPart + "/"))
                {
                    // Special case, this is a resource URL, we will just render the resource script here
                    var parsed = ResourceHandler.ParseUrl(path);
                    if (parsed == null)
                    {
                        return(null);
                    }

                    var className = parsed.Item2;
                    var culture   = CultureInfo.GetCultureInfo(parsed.Item1);

                    try
                    {
                        return(ResourceScripter.RenderResourceScript(className, culture));
                    }
                    catch (Exception exc)
                    {
                        Logger.WriteException(exc);
                        return(null);
                    }
                }

                try
                {
                    return(stream != null?Tools.GetStreamString(stream) : null);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }

            if (path.StartsWith("http://") || path.StartsWith("https://"))
            {
                // This is a web URL

                try
                {
                    HttpWebRequest req;
                    if (PortalContext.IsKnownUrl(path))
                    {
                        string url;
                        var    ub       = new UriBuilder(path);
                        var    origHost = ub.Host;
                        ub.Host  = "127.0.0.1";
                        url      = ub.Uri.ToString();
                        req      = (HttpWebRequest)HttpWebRequest.Create(url);
                        req.Host = origHost;
                    }
                    else
                    {
                        req = (HttpWebRequest)HttpWebRequest.Create(path);
                    }

                    req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                    var res = req.GetResponse();

                    using (var st = res.GetResponseStream())
                        using (var stream = new System.IO.MemoryStream())
                        {
                            st.CopyTo(stream);

                            var arr    = stream.ToArray();
                            var result = Encoding.UTF8.GetString(arr);
                            return(result);
                        }
                }
                catch (Exception exc)
                {
                    Logger.WriteError(EventId.Bundling.ContentLoadError, "Error during bundle request: " + exc, properties: new Dictionary <string, object> {
                        { "Path", path }
                    });
                    return(null);
                }
            }

            return(null);
        }
예제 #13
0
        public void NodeEvent_PermissionChanging()
        {
            var content = Content.CreateNew("Car", _testRoot, Guid.NewGuid().ToString());

            content.Save();

            var expectedLog = String.Concat("TestObserver.OnPermissionChanging", Environment.NewLine, "TestObserver.OnPermissionChanged", Environment.NewLine);

            //---- 1
            LoggedTestObserver.ResetLog();
            content.Security.BreakInheritance();
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#1");

            //---- 2
            LoggedTestObserver.ResetLog();
            content.Security.SetPermission(Group.Everyone, true, PermissionType.RunApplication, PermissionValue.Allow);
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#2");

            //---- 3
            LoggedTestObserver.ResetLog();
            content.Security.SetPermissions(Group.Everyone.Id, true, new[] { PermissionValue.Allow, PermissionValue.Allow, PermissionValue.Allow, PermissionValue.Allow });
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#3");

            //---- 4
            LoggedTestObserver.ResetLog();
            content.Security.SetAcl(content.Security.GetAcl());
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#4a");
            LoggedTestObserver.ResetLog();
            SecurityHandler.SetAcl(content.Security.GetAcl(), content.Id);
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#4b");
            LoggedTestObserver.ResetLog();
            SecurityHandler.SetAcl(content.Security.GetAcl(), content.Path);
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#4c");

            //---- 5
            content = Content.Load(content.Id);
            LoggedTestObserver.ResetLog();
            content.Security.RemoveBreakInheritance();
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#5");

            //---- 6
            var sb       = new StringBuilder();
            var settings = new XmlWriterSettings {
                Indent = true, IndentChars = "  "
            };

            using (var xmlWriter = XmlWriter.Create(sb, settings))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("Permissions");
                content.Security.ExportPermissions(xmlWriter);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndDocument();
            }

            var xml = new XmlDocument();

            xml.LoadXml(sb.ToString());
            var permissionNode = xml.DocumentElement;

            LoggedTestObserver.ResetLog();
            content.Security.ImportPermissions(permissionNode, "####");

            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#6");

            //---- 7
            LoggedTestObserver.ResetLog();
            content.Security.RemoveExplicitEntries();
            Assert.IsTrue(LoggedTestObserver.GetLog() == expectedLog, "#7");
        }
예제 #14
0
        /// <summary>
        /// Sets the callback URL of the ActionMenu. It represents the service url with correct parameters for the actions.
        /// </summary>
        private void SetServiceUrl()
        {
            var scParams = GetReplacedScenarioParameters();
            var context  = UITools.FindContextInfo(this, ContextInfoID);
            var path     = !string.IsNullOrEmpty(ContextInfoID) ? context.Path : NodePath;

            var encodedReturnUrl = Uri.EscapeDataString(PortalContext.Current.RequestedUri.PathAndQuery);
            var encodedParams    = Uri.EscapeDataString(scParams ?? string.Empty);

            if (string.IsNullOrEmpty(path))
            {
                path = ContentView.GetContentPath(this);
            }

            if (string.IsNullOrEmpty(path))
            {
                this.Visible = false;
                return;
            }

            var head = NodeHead.Get(path);

            if (head == null || !SecurityHandler.HasPermission(head, PermissionType.See))
            {
                this.Visible = false;
                return;
            }

            this.Content = Content.Load(path);

            // Pre-check action count. If empty, hide the action menu.
            if (CheckActionCount)
            {
                var actionCount = 0;

                if (!string.IsNullOrEmpty(Scenario))
                {
                    actionCount = ActionFramework.GetActions(this.Content, Scenario, scParams, null).Count();
                }

                if (actionCount < 2 && string.Equals(Scenario, "new", StringComparison.CurrentCultureIgnoreCase))
                {
                    ClickDisabled = true;
                }
                else if (actionCount == 0)
                {
                    this.Visible = false;
                    return;
                }
            }

            // Pre-check required permissions
            var permissions = SenseNet.ContentRepository.Fields.PermissionChoiceField.ConvertToPermissionTypes(RequiredPermissions).ToArray();

            if (permissions.Length > 0 && !SecurityHandler.HasPermission(head, permissions))
            {
                this.Visible = false;
                return;
            }

            ServiceUrl = string.Format(ODataTools.GetODataOperationUrl(path, "SmartAppGetActions") + "?scenario={0}&back={1}&parameters={2}", Scenario, encodedReturnUrl, encodedParams);
        }
예제 #15
0
        protected void btLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (Session["check"] == null)
                {
                    this.tbCaptcha.Text = string.Empty;
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "message", "<script language=\"javascript\">alert(\"验证码失效!\")</script>");
                    return;
                }
                if (tbCaptcha.Text != Session["check"].ToString())
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "message", "<script language=\"javascript\">alert(\"验证码错误!\")</script>");
                    this.tbCaptcha.Text = string.Empty;
                    return;
                }
                string usercode = Server.HtmlEncode(tbUserName.Text);
                string passWord = tbPassWord.Text;
                //进行用户登录,security.LoginResult为null或者security.LoginResult.IsPassed && security.LoginResult.AuthorizationCode != ""
                //都是登录失败
                SecurityHandler security = SecurityHandler.Login(usercode, passWord);
                if (security.LoginResult.SystemCode == null) //判断存不存在
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "message", "<script language=\"javascript\">alert(\"用户名或密码错误!\")</script>");
                    this.tbUserName.Text = string.Empty;
                    this.tbPassWord.Text = string.Empty;
                    this.tbCaptcha.Text  = string.Empty;
                    return;
                }
                var      aa   = SecurityHandler.LoginOn(security.LoginResult.AuthorizationCode).GetCurrentUserInfo();
                Dictuser user = new Dictuser();
                user.Usercode = aa.USERNAME;
                user          = new DictuserService().GetDictuserInfoByUserCode(user);
                if (user != null)
                {
                    UserInfo userInfo = new UserInfo();
                    userInfo.AuthorizationCode = security.LoginResult.AuthorizationCode;
                    userInfo.userCode          = user.Usercode;
                    userInfo.userName          = user.Username;
                    userInfo.userId            = Convert.ToInt32(user.Dictuserid);
                    userInfo.loginTime         = DateTime.Now;
                    userInfo.joinLabidstr      = user.Joinlabid;
                    userInfo.dictlabid         = user.Dictlabid;
                    userInfo.joinDeptstr       = user.Joindeptid;
                    userInfo.dictlabdeptid     = user.Dictlabdeptid;
                    userInfo.sysSetting        = GetSysSetting();
                    Session["UserInfo"]        = userInfo;
                }

                if (security.LoginResult.IsPassed && security.LoginResult.AuthorizationCode != "")
                {
                    //这里的Cookie名字不能更改
                    HttpCookie cookie = new HttpCookie("authorizationcode");
                    cookie.Value = security.LoginResult.AuthorizationCode;
                    TimeSpan ts = new TimeSpan(1, 0, 0, 0);
                    cookie.Expires = DateTime.Now.Add(ts);//添加作用时间
                    Response.AppendCookie(cookie);

                    if (!RegexPassWordSecurity(passWord))
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "redirectToChangePassword",
                                                           "<script> alert('您的密码安全性较弱,请重新修改密码'); window.location.href='EditPassword.aspx';</script>");

                        return;
                    }

                    Response.Redirect("Main.aspx", false);
                    //////PageContext.RegisterStartupScript("top.location.href = 'Main.aspx';");
                    //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "message", "<script language=\"javascript\">top.location.href = 'Main.aspx';</script>");
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "message", "<script language=\"javascript\">alert(\"用户名或密码错误!\")</script>");
                    this.tbUserName.Text = string.Empty;
                    this.tbPassWord.Text = string.Empty;
                    this.tbCaptcha.Text  = string.Empty;
                    return;
                }
            }
            catch (Exception ex)
            {
                Alert.ShowInTop(ex.Message, "体检系统");
            }
        }
예제 #16
0
        public IActionResult GetRootContainer()
        {
            var    authorizationHeader = HttpContext.Request.Headers["Authorization"];
            var    ecosystemOperation  = HttpContext.Request.Headers[WopiHeaders.EcosystemOperation];
            string wopiSrc             = HttpContext.Request.Headers[WopiHeaders.WopiSrc].FirstOrDefault();

            if (ValidateAuthorizationHeader(authorizationHeader))
            {
                //TODO: supply user
                var user = "******";

                //TODO: implement bootstrap
                BootstrapRootContainerInfo bootstrapRoot = new BootstrapRootContainerInfo
                {
                    Bootstrap = new BootstrapInfo
                    {
                        EcosystemUrl     = GetWopiUrl("ecosystem", accessToken: "TODO"),
                        SignInName       = "",
                        UserFriendlyName = "",
                        UserId           = ""
                    }
                };
                if (ecosystemOperation == "GET_ROOT_CONTAINER")
                {
                    var resourceId = StorageProvider.RootContainerPointer.Identifier;
                    var token      = SecurityHandler.GenerateAccessToken(user, resourceId);

                    bootstrapRoot.RootContainerInfo = new RootContainerInfo
                    {
                        ContainerPointer = new ChildContainer
                        {
                            Name = StorageProvider.RootContainerPointer.Name,
                            Url  = GetWopiUrl("containers", resourceId, SecurityHandler.WriteToken(token))
                        }
                    };
                }
                else if (ecosystemOperation == "GET_NEW_ACCESS_TOKEN")
                {
                    var token = SecurityHandler.GenerateAccessToken(user, GetIdFromUrl(wopiSrc));

                    bootstrapRoot.AccessTokenInfo = new AccessTokenInfo
                    {
                        AccessToken       = SecurityHandler.WriteToken(token),
                        AccessTokenExpiry = token.ValidTo.ToUnixTimestamp()
                    };
                }
                else
                {
                    return(new NotImplementedResult());
                }
                return(new JsonResult(bootstrapRoot));
            }
            else
            {
                //TODO: implement WWW-authentication header https://wopirest.readthedocs.io/en/latest/bootstrapper/Bootstrap.html#www-authenticate-header
                string authorizationUri = "https://contoso.com/api/oauth2/authorize";
                string tokenIssuanceUri = "https://contoso.com/api/oauth2/token";
                string providerId       = "tp_contoso";
                string urlSchemes       = Uri.EscapeDataString("{\"iOS\" : [\"contoso\",\"contoso - EMM\"], \"Android\" : [\"contoso\",\"contoso - EMM\"], \"UWP\": [\"contoso\",\"contoso - EMM\"]}");
                Response.Headers.Add("WWW-Authenticate", $"Bearer authorization_uri=\"{authorizationUri}\",tokenIssuance_uri=\"{tokenIssuanceUri}\",providerId=\"{providerId}\", UrlSchemes=\"{urlSchemes}\"");
                return(new UnauthorizedResult());
            }
        }
예제 #17
0
        public RestoreResult restore(DirectoryInfo destination, List <string> only_these)
        {
            cancel_restore = false;
            TranslatingProgressHandler.setTranslatedMessage("CheckingDestination");
            // The files get extracted to the temp folder, so this sets up our ability to read them
            DirectoryInfo from_here = new DirectoryInfo(TempFolder);

            // If it's a destination that doesn't yet exist
            if (!destination.Exists)
            {
                try {
                    destination.Create();
                    // This sets the permissions on the folder to be for everyone
                    DirectorySecurity everyone       = destination.GetAccessControl();
                    string            everyones_name = @"Everyone";
                    everyone.AddAccessRule(new FileSystemAccessRule(everyones_name, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                    destination.SetAccessControl(everyone);
                } catch {
                    // This is if the folder creation fails
                    // It means we have to run as admin, but we check here if we already are
                    if (!SecurityHandler.amAdmin())
                    {
                        // If we aren't we elevate ourselves
                        RestoreResult res = restoreElevation(destination.FullName);
                        if (res != RestoreResult.Success)
                        {
                            return(res);
                        }
                    }
                    else
                    {
                        throw new TranslateableException("UnableToCreateOutputFolder", destination.FullName);
                    }
                }
            }
            if (cancel_restore)
            {
                return(RestoreResult.Cancel);
            }

            TranslatingProgressHandler.setTranslatedMessage("ExtractingArchive");
            ProgressHandler.state = ProgressState.Indeterminate;
            if (only_these == null)
            {
                ProgressHandler.max = file_count;
                extract(true);
            }
            else
            {
                ProgressHandler.max = only_these.Count;
                extract(only_these, true);
            }
            ProgressHandler.value = 0;
            ProgressHandler.state = ProgressState.Normal;

            // Clean up the masgau archive ID
            if (File.Exists(Path.Combine(TempFolder, "masgau.xml")))
            {
                File.Delete(Path.Combine(TempFolder, "masgau.xml"));
            }

            if (cancel_restore)
            {
                return(RestoreResult.Cancel);
            }

            TranslatingProgressHandler.setTranslatedMessage("CopyingFilesToDestination");
            if (!canWrite(destination))
            {
                Directory.Delete(TempFolder, true);

                RestoreResult res = restoreElevation(destination.FullName);
                if (res != RestoreResult.Success)
                {
                    return(res);
                }
                cancel_restore = true;
            }
            if (cancel_restore)
            {
                return(RestoreResult.Cancel);
            }

            copyFolders(from_here, destination, true);

            if (cancel_restore)
            {
                return(RestoreResult.Cancel);
            }

            purgeTemp();

            ProgressHandler.state = ProgressState.None;

            return(RestoreResult.Success);
        }
예제 #18
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ProviderContext.Create);
            app.CreatePerOwinContext <LtiUserManager>(LtiUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // The app also uses a RoleManager
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            app.UseLtiAuthentication(new LtiAuthenticationOptions
            {
                Provider = new LtiAuthenticationProvider
                {
                    // Look up the secret for the consumer
                    OnAuthenticate = async context =>
                    {
                        // Make sure the request is not being replayed
                        var timeout = TimeSpan.FromMinutes(5);
                        var oauthTimestampAbsolute = OAuthConstants.Epoch.AddSeconds(context.LtiRequest.Timestamp);
                        if (DateTime.UtcNow - oauthTimestampAbsolute > timeout)
                        {
                            throw new LtiException("Expired " + OAuthConstants.TimestampParameter);
                        }

                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key == context.LtiRequest.ConsumerKey);
                        if (consumer == null)
                        {
                            throw new LtiException("Invalid " + OAuthConstants.ConsumerKeyParameter);
                        }

                        var signature = context.LtiRequest.GenerateSignature(consumer.Secret);
                        if (!signature.Equals(context.LtiRequest.Signature))
                        {
                            throw new LtiException("Invalid " + OAuthConstants.SignatureParameter);
                        }

                        // If we made it this far the request is valid
                    },

                    // Sign in using application authentication. This handler will create a new application
                    // user if no matching application user is found.
                    OnAuthenticated = async context =>
                    {
                        var db       = context.OwinContext.Get <ProviderContext>();
                        var consumer = await db.Consumers.SingleOrDefaultAsync(c => c.Key.Equals(context.LtiRequest.ConsumerKey));
                        if (consumer == null)
                        {
                            return;
                        }

                        // Record the request for logging purposes and as reference for outcomes
                        var providerRequest = new ProviderRequest
                        {
                            Received   = DateTime.UtcNow,
                            LtiRequest = JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
                                                                     new JsonSerializerSettings {
                                NullValueHandling = NullValueHandling.Ignore
                            })
                        };
                        db.ProviderRequests.Add(providerRequest);
                        db.SaveChanges();

                        // Add the requst ID as a claim
                        var claims = new List <Claim>
                        {
                            new Claim("ProviderRequestId",
                                      providerRequest.ProviderRequestId.ToString(CultureInfo.InvariantCulture))
                        };

                        // Outcomes can live a long time to give the teacher enough
                        // time to grade the assignment. So they are stored in a separate table.
                        var lisOutcomeServiceUrl = ((IOutcomesManagementRequest)context.LtiRequest).LisOutcomeServiceUrl;
                        var lisResultSourcedid   = ((IOutcomesManagementRequest)context.LtiRequest).LisResultSourcedId;
                        if (!string.IsNullOrWhiteSpace(lisOutcomeServiceUrl) &&
                            !string.IsNullOrWhiteSpace(lisResultSourcedid))
                        {
                            var outcome = await db.Outcomes.SingleOrDefaultAsync(o =>
                                                                                 o.ConsumerId == consumer.ConsumerId &&
                                                                                 o.LisResultSourcedId == lisResultSourcedid);

                            if (outcome == null)
                            {
                                outcome = new Outcome
                                {
                                    ConsumerId         = consumer.ConsumerId,
                                    LisResultSourcedId = lisResultSourcedid
                                };
                                db.Outcomes.Add(outcome);
                                await db.SaveChangesAsync(); // Assign OutcomeId;
                            }
                            outcome.ContextTitle = context.LtiRequest.ContextTitle;
                            outcome.ServiceUrl   = lisOutcomeServiceUrl;
                            await db.SaveChangesAsync();

                            // Add the outcome ID as a claim
                            claims.Add(new Claim("OutcomeId",
                                                 outcome.OutcomeId.ToString(CultureInfo.InvariantCulture)));
                        }

                        // Sign in
                        await SecurityHandler.OnAuthenticated <LtiUserManager, LtiUser>(
                            context, claims);
                    },

                    // Generate a username using the LisPersonEmailPrimary from the LTI request
                    OnGenerateUserName = async context =>
                                         await SecurityHandler.OnGenerateUserName(context)
                },
                //ChallengeResultUrl = new PathString("/Manage/ToolConsumerLogins"),
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });
        }
예제 #19
0
        private static object GetPermissionInfo(Content content, string identity, bool singleContent)
        {
            // This method assembles an object containing identity information (basic fields and all groups),
            // inherited and subtree permissions that can be serialized and sent to the client.
            // If the singleContent parameter is true, permissions will be collected and returned
            // only for the provided content. Otherwise the result object will contain permission infos for
            // the children of the provided content and not the root.

            if (string.IsNullOrEmpty(identity))
            {
                throw new ArgumentException("Please provide an identity path");
            }

            var user = Node.Load <User>(identity);

            if (user == null)
            {
                throw new ArgumentException("Identity must be an existing user.");
            }

            // collect all groups for the user
            var groups       = Node.LoadNodes(SecurityHandler.GetGroupsWithOwnership(content.Id, user)).Select(n => Content.Create(n)).ToArray();
            var identityInfo = new IdentityInfo
            {
                Path        = user.Path,
                Name        = user.Name,
                DisplayName = user.DisplayName,
                Groups      = groups.Select(g => new GroupInfo {
                    DisplayName = g.DisplayName, Name = g.Name, Path = g.Path
                }).ToArray()
            };

            // identities include all groups and the user itself
            var identities = groups.Select(g => g.Id).Concat(new[] { user.Id }).ToArray();

            // If we have to collect permissions for the provided content, we will need its parent
            // to check inherited permissions. If children are in the focus than the parent is the
            // provided content itself.
            var parent = singleContent ? content.ContentHandler.Parent : content.ContentHandler;
            var effectiveParentEntries = parent == null || !parent.Security.HasPermission(PermissionType.SeePermissions)
                ? new AceInfo[0]
                : parent.Security.GetEffectiveEntries(EntryType.Normal).Where(e => identities.Contains(e.IdentityId) && !e.LocalOnly).ToArray();

            var permissionsTypes = PermissionType.BuiltInPermissionTypes.Select(p => new PermissionInfo {
                Index = p.Index, Name = p.Name
            }).ToArray();

            // Collect all entries on the parent that are not local-only therefore
            // have effect on children.
            foreach (var entry in permissionsTypes)
            {
                if (effectiveParentEntries.Any(e => e.GetPermissionValues()[entry.Index] == PermissionValue.Denied))
                {
                    entry.Type = "effectivedeny";
                }
                else if (effectiveParentEntries.Any(e => e.GetPermissionValues()[entry.Index] == PermissionValue.Allowed))
                {
                    entry.Type = "effectiveallow";
                }
                else
                {
                    entry.Type = "off";
                }
            }

            if (singleContent)
            {
                // collect permissions for the provided single content
                return(new
                {
                    d = new
                    {
                        identity = identityInfo,
                        permissionInfo = GetPermissionInfo(content, identities, permissionsTypes)
                    }
                });
            }

            // alternatively, collect permissions for child elements
            return(new
            {
                d = new
                {
                    identity = identityInfo,
                    results = content.Children.DisableAutofilters().AsEnumerable()
                              .Select(child => GetPermissionInfo(child, identities, permissionsTypes)).ToArray()
                }
            });
        }
        public void Should_not_throw_exception_when_the_user_is_authenticated_with_role_Owner()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.GetRolesFrom(StaticHelper.GetRolesIncludingOwner);
                policy.For<BlogController>(x => x.DeletePost(0)).RequireRole(UserRole.Owner);
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor(NameHelper.Controller<BlogController>(), "DeletePost", SecurityContext.Current));
        }
예제 #21
0
        public void Should_not_throw_exception_when_the_user_is_authenticated()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor(NameHelper<BlogController>.Controller(), "Index"));
        }
        public void Should_not_throw_ConfigurationErrorsException_when_IgnoreMissingConfigurations_is_true()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.IgnoreMissingConfiguration();
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor("NonConfiguredController", "Action", SecurityContext.Current));
        }
예제 #23
0
        public void Should_throw_when_the_user_is_anonymous()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act
            var exception = Assert.Throws<PolicyViolationException>(() => securityHandler.HandleSecurityFor(NameHelper<BlogController>.Controller(), "Index"));

            // Assert
            Assert.That(exception.PolicyType, Is.EqualTo(typeof(DenyAnonymousAccessPolicy)));
            Assert.That(exception.Message, Is.StringContaining("Anonymous access denied"));
        }
예제 #24
0
        public void ProcessRequest(HttpContext context, string httpMethod, Stream inputStream)
        {
            ODataRequest   odataReq      = null;
            ODataFormatter formatter     = null;
            var            portalContext = (PortalContext)context.Items[PortalContext.CONTEXT_ITEM_KEY];

            try
            {
                Content content;

                odataReq = portalContext.ODataRequest;
                if (odataReq == null)
                {
                    formatter = ODataFormatter.Create("json", portalContext);
                    throw new ODataException("The Request is not an OData request.", ODataExceptionCode.RequestError);
                }

                this.ODataRequest = portalContext.ODataRequest;
                Exception requestError = this.ODataRequest.RequestError;

                formatter = ODataFormatter.Create(portalContext, odataReq);
                if (formatter == null)
                {
                    formatter = ODataFormatter.Create("json", portalContext);
                    throw new ODataException(ODataExceptionCode.InvalidFormatParameter);
                }

                if (requestError != null)
                {
                    var innerOdataError = requestError as ODataException;
                    var message         = "An error occured during request parsing. " + requestError.Message +
                                          " See inner exception for details.";
                    var code = innerOdataError?.ODataExceptionCode ?? ODataExceptionCode.RequestError;
                    throw new ODataException(message, code, requestError);
                }

                odataReq.Format = formatter.FormatName;
                formatter.Initialize(odataReq);

                // Cross-Origin Resource Sharing (CORS)
                // Do this after the formatter was initialized to be able to provide a proper error message.
                if (!HttpHeaderTools.IsOriginHeaderAllowed())
                {
                    throw new ODataException(ODataExceptionCode.Forbidden);
                }

                var exists = Node.Exists(odataReq.RepositoryPath);
                if (!exists && !odataReq.IsServiceDocumentRequest && !odataReq.IsMetadataRequest && !AllowedMethodNamesWithoutContent.Contains(httpMethod))
                {
                    ContentNotFound(context, odataReq.RepositoryPath);
                    return;
                }

                JObject model = null;
                switch (httpMethod)
                {
                case "GET":
                    if (odataReq.IsServiceDocumentRequest)
                    {
                        formatter.WriteServiceDocument(portalContext, odataReq);
                    }
                    else if (odataReq.IsMetadataRequest)
                    {
                        formatter.WriteMetadata(context, odataReq);
                    }
                    else
                    {
                        if (!Node.Exists(odataReq.RepositoryPath))
                        {
                            ContentNotFound(context, odataReq.RepositoryPath);
                        }
                        else if (odataReq.IsCollection)
                        {
                            formatter.WriteChildrenCollection(odataReq.RepositoryPath, portalContext, odataReq);
                        }
                        else if (odataReq.IsMemberRequest)
                        {
                            formatter.WriteContentProperty(odataReq.RepositoryPath, odataReq.PropertyName,
                                                           odataReq.IsRawValueRequest, portalContext, odataReq);
                        }
                        else
                        {
                            formatter.WriteSingleContent(odataReq.RepositoryPath, portalContext);
                        }
                    }
                    break;

                case "PUT":     // update
                    if (odataReq.IsMemberRequest)
                    {
                        throw new ODataException("Cannot access a member with HTTP PUT.",
                                                 ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        model   = Read(inputStream);
                        content = LoadContentOrVirtualChild(odataReq);
                        if (content == null)
                        {
                            ContentNotFound(context, odataReq.RepositoryPath);
                            return;
                        }

                        ResetContent(content);
                        UpdateContent(content, model, odataReq);
                        formatter.WriteSingleContent(content, portalContext);
                    }
                    break;

                case "MERGE":
                case "PATCH":     // update
                    if (odataReq.IsMemberRequest)
                    {
                        throw new ODataException(
                                  String.Concat("Cannot access a member with HTTP ", httpMethod, "."),
                                  ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        model   = Read(inputStream);
                        content = LoadContentOrVirtualChild(odataReq);
                        if (content == null)
                        {
                            ContentNotFound(context, odataReq.RepositoryPath);
                            return;
                        }

                        UpdateContent(content, model, odataReq);
                        formatter.WriteSingleContent(content, portalContext);
                    }
                    break;

                case "POST":     // invoke an action, create content
                    if (odataReq.IsMemberRequest)
                    {
                        formatter.WriteOperationResult(inputStream, portalContext, odataReq);
                    }
                    else
                    {
                        // parent must exist
                        if (!Node.Exists(odataReq.RepositoryPath))
                        {
                            ContentNotFound(context, odataReq.RepositoryPath);
                            return;
                        }
                        model   = Read(inputStream);
                        content = CreateContent(model, odataReq);
                        formatter.WriteSingleContent(content, portalContext);
                    }
                    break;

                case "DELETE":
                    if (odataReq.IsMemberRequest)
                    {
                        throw new ODataException(
                                  String.Concat("Cannot access a member with HTTP ", httpMethod, "."),
                                  ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        content = LoadContentOrVirtualChild(odataReq);
                        if (content != null)
                        {
                            content.Delete();
                        }
                    }
                    break;

                case "OPTIONS":
                    // set allowed methods and headers
                    HttpHeaderTools.SetPreflightResponse();
                    break;
                }
            }
            catch (ContentNotFoundException e)
            {
                var oe = new ODataException(ODataExceptionCode.ResourceNotFound, e);

                formatter.WriteErrorResponse(context, oe);
            }
            catch (ODataException e)
            {
                if (e.HttpStatusCode == 500)
                {
                    SnLog.WriteException(e);
                }

                formatter.WriteErrorResponse(context, e);
            }
            catch (SenseNetSecurityException e)
            {
                // In case of a visitor we should not expose the information that this content actually exists. We return
                // a simple 404 instead to provide exactly the same response as the regular 404, where the content
                // really does not exist. But do this only if the visitor really does not have permission for the
                // requested content (because security exception could be thrown by an action or something else too).
                if (odataReq != null && User.Current.Id == User.Visitor.Id)
                {
                    var head = NodeHead.Get(odataReq.RepositoryPath);
                    if (head != null && !SecurityHandler.HasPermission(head, PermissionType.Open))
                    {
                        ContentNotFound(context, odataReq.RepositoryPath);
                        return;
                    }
                }

                var oe = new ODataException(ODataExceptionCode.NotSpecified, e);

                SnLog.WriteException(oe);

                formatter.WriteErrorResponse(context, oe);
            }
            catch (InvalidContentActionException ex)
            {
                var oe = new ODataException(ODataExceptionCode.NotSpecified, ex);
                if (ex.Reason != InvalidContentActionReason.NotSpecified)
                {
                    oe.ErrorCode = Enum.GetName(typeof(InvalidContentActionReason), ex.Reason);
                }

                // it is unnecessary to log this exception as this is not a real error
                formatter.WriteErrorResponse(context, oe);
            }
            catch (ContentRepository.Storage.Data.NodeAlreadyExistsException nae)
            {
                var oe = new ODataException(ODataExceptionCode.ContentAlreadyExists, nae);

                formatter.WriteErrorResponse(context, oe);
            }
            catch (System.Threading.ThreadAbortException tae)
            {
                if (!context.Response.IsRequestBeingRedirected)
                {
                    var oe = new ODataException(ODataExceptionCode.RequestError, tae);
                    formatter.WriteErrorResponse(context, oe);
                }
                // specific redirect response so do nothing
            }
            catch (Exception ex)
            {
                var oe = new ODataException(ODataExceptionCode.NotSpecified, ex);

                SnLog.WriteException(oe);

                formatter.WriteErrorResponse(context, oe);
            }
            finally
            {
                context.Response.End();
            }
        }
예제 #25
0
        public void Should_throw_when_the_user_does_not_have_the_role_Owner()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.GetRolesFrom(StaticHelper.GetRolesExcludingOwner);
                policy.For<BlogController>(x => x.DeletePost(0)).RequireRole(UserRole.Owner);
            });

            var securityHandler = new SecurityHandler();

            // Act
            var exception = Assert.Throws<PolicyViolationException>(() => securityHandler.HandleSecurityFor(NameHelper<BlogController>.Controller(), "DeletePost"));

            // Assert
            Assert.That(exception.PolicyType, Is.EqualTo(typeof(RequireRolePolicy)));
            Assert.That(exception.Message, Is.StringContaining("Access requires one of the following roles: Owner."));
        }
예제 #26
0
        void OnAuthorizeRequest(object sender, EventArgs e)
        {
            PortalContext currentPortalContext = PortalContext.Current;
            var           d = NodeHead.Get("/Root");

            // deny access for visitors in case of webdav or office protocol requests, if they have no See access to the content
            if (currentPortalContext != null)
            {
                var application = sender as HttpApplication;
                var currentUser = application != null ? application.Context.User.Identity as User : null;

                if (currentUser != null && currentUser.Id == RepositoryConfiguration.VisitorUserId && (currentPortalContext.IsOfficeProtocolRequest || currentPortalContext.IsWebdavRequest))
                {
                    if (!currentPortalContext.IsRequestedResourceExistInRepository ||
                        currentPortalContext.ContextNodeHead == null ||
                        !SecurityHandler.HasPermission(currentPortalContext.ContextNodeHead, PermissionType.See))
                    {
                        AuthenticationHelper.ForceBasicAuthentication(HttpContext.Current);
                    }
                }
            }

            if (currentPortalContext != null && currentPortalContext.IsRequestedResourceExistInRepository)
            {
                var authMode = currentPortalContext.AuthenticationMode;
                //install time
                if (string.IsNullOrEmpty(authMode) && currentPortalContext.Site == null)
                {
                    authMode = "None";
                }

                if (string.IsNullOrEmpty(authMode))
                {
                    authMode = WebConfigurationManager.AppSettings["DefaultAuthenticationMode"];
                }

                bool appPerm = false;
                if (authMode == "Forms")
                {
                    appPerm = currentPortalContext.CurrentAction.CheckPermission();
                }
                else if (authMode == "Windows")
                {
                    currentPortalContext.CurrentAction.AssertPermissions();
                    appPerm = true;
                }
                else
                {
                    throw new NotSupportedException("None authentication is not supported");
                }

                var application     = sender as HttpApplication;
                var currentUser     = application.Context.User.Identity as User;
                var path            = currentPortalContext.RepositoryPath;
                var nodeHead        = NodeHead.Get(path);
                var isOwner         = nodeHead.CreatorId == currentUser.Id;
                var permissionValue = SecurityHandler.GetPermission(nodeHead, PermissionType.Open);

                if (permissionValue == PermissionValue.Allow && DocumentPreviewProvider.Current.IsPreviewOrThumbnailImage(nodeHead))
                {
                    // In case of preview images we need to make sure that they belong to a content version that
                    // is accessible by the user (e.g. must not serve images for minor versions if the user has
                    // access only to major versions of the content).
                    if (!DocumentPreviewProvider.Current.IsPreviewAccessible(nodeHead))
                    {
                        permissionValue = PermissionValue.Deny;
                    }
                }
                else if (permissionValue != PermissionValue.Allow && appPerm && DocumentPreviewProvider.Current.HasPreviewPermission(nodeHead))
                {
                    // In case Open permission is missing: check for Preview permissions. If the current Document
                    // Preview Provider allows access to a preview, we should allow the user to access the content.
                    permissionValue = PermissionValue.Allow;
                }

                if (permissionValue != PermissionValue.Allow || !appPerm)
                {
                    switch (authMode)
                    {
                    case "Forms":
                        if (User.Current.IsAuthenticated)
                        {
                            // user is authenticated, but has no permissions: return 403
                            application.Context.Response.StatusCode = 403;
                            application.Context.Response.Flush();
                            application.Context.Response.Close();
                        }
                        else
                        {
                            // let webdav and office protocol handle authentication - in these cases redirecting to a login page makes no sense
                            if (PortalContext.Current.IsWebdavRequest || PortalContext.Current.IsOfficeProtocolRequest)
                            {
                                return;
                            }

                            // user is not authenticated and visitor has no permissions: redirect to login page
                            // Get the login page Url (eg. http://localhost:1315/home/login)
                            string loginPageUrl = currentPortalContext.GetLoginPageUrl();
                            // Append trailing slash
                            if (loginPageUrl != null && !loginPageUrl.EndsWith("/"))
                            {
                                loginPageUrl = loginPageUrl + "/";
                            }

                            // Cut down the querystring (eg. drop ?Param1=value1@Param2=value2)
                            string currentRequestUrlWithoutQueryString = currentPortalContext.OriginalUri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.Unescaped);

                            // Append trailing slash
                            if (!currentRequestUrlWithoutQueryString.EndsWith("/"))
                            {
                                currentRequestUrlWithoutQueryString = currentRequestUrlWithoutQueryString + "/";
                            }

                            // Redirect to the login page, if neccessary.
                            if (currentRequestUrlWithoutQueryString != loginPageUrl)
                            {
                                application.Context.Response.Redirect(loginPageUrl + "?OriginalUrl=" + System.Web.HttpUtility.UrlEncode(currentPortalContext.OriginalUri.ToString()), true);
                            }
                        }
                        break;

                    //case "Windows":
                    //    application.Context.Response.Clear();
                    //    application.Context.Response.Buffer = true;
                    //    application.Context.Response.Status = "401 Unauthorized";
                    //    application.Context.Response.AddHeader("WWW-Authenticate", "NTLM");
                    //    application.Context.Response.End();
                    //    break;
                    default:
                        AuthenticationHelper.DenyAccess(application);
                        break;
                    }
                }
            }
        }
예제 #27
0
        private static void CreateContentRecursive(Content sourceContent, Node targetContainer)
        {
            var sourceNode      = sourceContent.ContentHandler;
            var alreadyExisting = Node.LoadNode(targetContainer.Path + "/" + sourceNode.Name);

            if (alreadyExisting != null && alreadyExisting.NodeType.Name != sourceNode.NodeType.Name)
            {
                throw new Exception("The target node already exists with a different type.");
            }

            var target = alreadyExisting ?? NodeType.CreateInstance(sourceNode.NodeType.Name, targetContainer);

            target.Name          = sourceNode.Name;
            target.DisplayName   = sourceNode.DisplayName;
            target.Index         = sourceNode.Index;
            target.NodeOperation = NodeOperation.TemplateChildCopy;

            var targetContent = Content.Create(target);

            // We do not want to set the current user here but the user we 'inherited'
            // from the parent (the template). In case of user profiles (my site) the
            // creator and the owner will be the user itself.
            var realCreatorUser  = targetContainer.CreatedBy;
            var realModifierUser = targetContainer.ModifiedBy;

            var now = DateTime.UtcNow;

            target.CreatedBy               = realCreatorUser;
            target.VersionCreatedBy        = realCreatorUser;
            target.ModificationDate        = now;
            target.ModifiedBy              = realModifierUser;
            target.VersionModificationDate = now;
            target.VersionModifiedBy       = realModifierUser;
            target.Owner = realCreatorUser;

            foreach (var propertyType in sourceNode.PropertyTypes.Where(pt => !pt.IsContentListProperty))
            {
                switch (propertyType.DataType)
                {
                case DataType.Binary:
                    var sourceBinaryData = sourceNode.GetBinary(propertyType);
                    var targetBinaryData = new BinaryData();
                    targetBinaryData.CopyFrom(sourceBinaryData);
                    target.SetBinary(propertyType.Name, targetBinaryData);
                    break;

                default:
                    target[propertyType] = sourceNode[propertyType];
                    break;
                }
            }

            // Iterate through content list fields and set their value on the target node separately.
            // This is needed because the same content list fields may have a different property name
            // (e.g. #String_0 and #String_1) in the source and target content lists.
            foreach (var field in sourceContent.Fields.Values.Where(f => f.Name.StartsWith("#")))
            {
                // this should give us the name of the source property (e.g. #String_0)
                var sourcePropertyName = field.FieldSetting.Bindings.FirstOrDefault();
                if (string.IsNullOrEmpty(sourcePropertyName))
                {
                    continue;
                }

                // this should give us the name of the target property (e.g. #String_1)
                var targetPropertyName = targetContent.Fields[field.Name].FieldSetting.Bindings.FirstOrDefault();
                if (string.IsNullOrEmpty(targetPropertyName))
                {
                    continue;
                }

                if (field is BinaryField)
                {
                    var sourceBinaryData = sourceNode.GetBinary(sourcePropertyName);
                    var targetBinaryData = new BinaryData();
                    targetBinaryData.CopyFrom(sourceBinaryData);
                    target.SetBinary(targetPropertyName, targetBinaryData);
                }
                else
                {
                    target[targetPropertyName] = sourceNode[sourcePropertyName];
                }
            }

            // workaround for content lists: content list type needs to be refreshed
            var contentList = target as ContentList;

            if (contentList != null)
            {
                contentList.ContentListDefinition = contentList.ContentListDefinition;
            }

            target.Save();

            // inherit explicit permissions from template
            using (new SystemAccount())
            {
                var entries = SecurityHandler.GetExplicitEntriesAsSystemUser(sourceNode.Id, null, EntryType.Normal);
                if (entries.Count > 0)
                {
                    var aclEdit = SecurityHandler.CreateAclEditor();

                    foreach (var ace in entries)
                    {
                        aclEdit.SetEntry(target.Id, ace, true);
                    }

                    aclEdit.Apply();
                }
            }

            // This is to make sure that only those children are copied
            // that are really under this content. E.g. SmartFolder may
            // contain real children and queried children too.
            foreach (var childNode in sourceNode.PhysicalChildArray.Where(ch => ch.InFolder(sourceNode.Path)))
            {
                CreateContentRecursive(Content.Create(childNode), target);
            }
        }
예제 #28
0
        private static string ResolveContentViewPath(SNC.Content content, ViewMode mode, string path)
        {
            // ways to call this function:
            // - absolute actual: "/Root/Global/contentviews/Book/Edit.ascx"
            // - relative actual: "$skin/contentviews/Book/Edit.ascx"
            // - absolute root:   "/Root/Global/contentviews"
            // - relative root:   "$skin/contentviews"
            // - empty string:    ""

            if (string.IsNullOrEmpty(path))
            {
                path = Repository.ContentViewFolderName;
            }

            var isActual = path.EndsWith(".ascx");

            // - relative with custom name --> convert to relative actual
            if (isActual && !path.Contains(RepositoryPath.PathSeparator))
            {
                path = string.Format("{0}/{1}/{2}", Repository.ContentViewFolderName, content.ContentType.Name, path);
            }

            var isAbsolute = SkinManager.IsNotSkinRelativePath(path);

            // - absolute actual: "/Root/Global/contentviews/Book/Edit.ascx"
            if (isAbsolute && isActual)
            {
                return(path);
                // "/Root/Global/contentviews/Book/Edit.ascx"
            }

            // - relative actual: "$skin/contentviews/Book/Edit.ascx"
            if (!isAbsolute && isActual)
            {
                return(SkinManager.Resolve(path));
                // "/Root/{skin/global}/contentviews/Book/Edit.ascx"
            }

            // - absolute root:   "/Root/Global/contentviews"
            if (isAbsolute && !isActual)
            {
                var probePath = GetTypeDependentPath(content, mode, path);
                var node      = Node.LoadNode(probePath);
                if (node != null)
                {
                    return(probePath);
                }
                // "/Root/Global/contentviews/Book/Edit.ascx"

                probePath = GetGenericPath(content, mode, path);
                node      = Node.LoadNode(probePath);
                if (node != null)
                {
                    return(probePath);
                }
                // "/Root/Global/contentviews/Edit.ascx"

                return(string.Empty);
            }

            // - relative root:   "$skin/contentviews"
            if (!isAbsolute && !isActual)
            {
                var typedPath    = GetTypeDependentPath(content, mode, path);
                var resolvedPath = string.Empty;
                if (SkinManager.TryResolve(typedPath, out resolvedPath))
                {
                    return(resolvedPath);
                }
                // "/Root/{skin}/contentviews/Book/Edit.ascx"

                var genericPath = GetGenericPath(content, mode, path);
                if (SkinManager.TryResolve(genericPath, out resolvedPath))
                {
                    return(resolvedPath);
                }
                // "/Root/{skin}/contentviews/Edit.ascx"

                var probePath = SkinManager.Resolve(typedPath);
                var viewHead  = !string.IsNullOrEmpty(probePath) ? NodeHead.Get(probePath) : null;
                if (viewHead != null && SecurityHandler.HasPermission(viewHead, PermissionType.RunApplication))
                {
                    return(probePath);
                }
                // "/Root/Global/contentviews/Book/Edit.ascx"

                probePath = SkinManager.Resolve(genericPath);
                viewHead  = !string.IsNullOrEmpty(probePath) ? NodeHead.Get(probePath) : null;
                if (viewHead != null && SecurityHandler.HasPermission(viewHead, PermissionType.RunApplication))
                {
                    return(probePath);
                }
                // "/Root/Global/contentviews/Edit.ascx"

                return(string.Empty);
            }
            return(string.Empty);
        }
예제 #29
0
        private static void SetPermissions(Node templateRoot, Node targetRoot)
        {
            if (templateRoot == null)
            {
                throw new ArgumentNullException("templateRoot");
            }
            if (targetRoot == null)
            {
                throw new ArgumentNullException("targetRoot");
            }

            using (new SystemAccount())
            {
                IEnumerable <Node> sourceNodes;

                if (SearchManager.ContentQueryIsAllowed)
                {
                    sourceNodes = ContentQuery.Query(SafeQueries.InTreeOrderByPath,
                                                     new QuerySettings {
                        EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled
                    },
                                                     templateRoot.Path).Nodes;
                }
                else
                {
                    var sourceNodeList = NodeQuery.QueryNodesByPath(templateRoot.Path, true).Nodes.ToList();
                    var first          = sourceNodeList.FirstOrDefault();

                    // we have to add the tenplate node manually because the query above does not return the root itself
                    if (first == null || first.Id != templateRoot.Id)
                    {
                        sourceNodeList.Insert(0, templateRoot);
                    }

                    sourceNodes = sourceNodeList;
                }

                var ctx       = SecurityHandler.SecurityContext;
                var aclEditor = SecurityHandler.CreateAclEditor(ctx);
                foreach (var sourceNode in sourceNodes)
                {
                    var expEntries = ctx.GetExplicitEntries(sourceNode.Id);

                    // no need to do anyithing: no explicit entries and no inheritance break here
                    if (expEntries.Count == 0 && sourceNode.IsInherited)
                    {
                        continue;
                    }

                    var targetNodePath = sourceNode.Path.Replace(templateRoot.Path, targetRoot.Path);
                    var targetNode     = Node.LoadNode(targetNodePath);
                    if (!sourceNode.IsInherited)
                    {
                        targetNode.Security.BreakInheritance();
                        targetNode.Security.RemoveExplicitEntries();
                    }


                    foreach (var ace in expEntries)
                    {
                        var sourcePrincHead = NodeHead.Get(ace.IdentityId);

                        if (sourcePrincHead.Path.StartsWith(templateRoot.Path))
                        {
                            // local groups: we need to change the permission
                            // setting to map to the newly created local group
                            var targetGroupPath = sourcePrincHead.Path.Replace(templateRoot.Path, targetRoot.Path);
                            var targetGroup     = NodeHead.Get(targetGroupPath);
                            if (targetGroup == null)
                            {
                                throw new InvalidOperationException("Target local group was not found: " + targetGroupPath);
                            }

                            // set permissions for target local group
                            aclEditor.Set(targetNode.Id, targetGroup.Id, ace.LocalOnly, ace.AllowBits, ace.DenyBits);

                            // clear original permissions
                            aclEditor.Reset(targetNode.Id, ace.IdentityId, ace.LocalOnly, PermissionBitMask.All);
                        }
                        else
                        {
                            // normal groups or users
                            // targetNode.Security.SetPermissions(se.PrincipalId, se.Propagates, se.PermissionValues);
                            aclEditor.SetEntry(targetNode.Id, ace, true);
                        }
                    }
                }
                aclEditor.Apply();
            }
        }
예제 #30
0
        /* ============================================================================ DATABASE AND INDEX BUILDER */

        public static void GenerateInMemoryDatabaseFromImport(Arguments arguments)
        {
            //Providers.PropertyCollectorClassName = typeof(EventPropertyCollector).FullName;
            var builder = CreateRepositoryBuilder();

            //Indexing.IsOuterSearchEngineEnabled = false;
            builder.StartIndexingEngine = false;

            using (Repository.Start(builder))
            {
                // IMPORT
                new Installer(CreateRepositoryBuilder()).Import(arguments.ImportPath);

                // Copy importlog
                using (var reader = new StreamReader(Logger.GetLogFileName()))
                    using (var writer = new StreamWriter(Path.Combine(arguments.OutputPath, "_importlog.log"), false, Encoding.UTF8))
                        writer.WriteLine(reader.ReadToEnd());

                // Re-set initial object
                User.Current = User.Administrator;

                // Add Admin* permissions on the /Root
                Console.WriteLine("Set Root permissions.");
                using (new SystemAccount())
                    SecurityHandler.CreateAclEditor()
                    .Allow(Identifiers.PortalRootId, Identifiers.AdministratorUserId,
                           false, PermissionType.BuiltInPermissionTypes)
                    .Allow(Identifiers.PortalRootId, Identifiers.AdministratorsGroupId,
                           false, PermissionType.BuiltInPermissionTypes)
                    .Apply();

                // Use the path-blacklist
                Console.WriteLine("Remove unnecessary subtrees ({0}):", arguments.SkippedPathArray.Length);
                RemoveSkippedPaths(arguments);

                // Save database to separated files.
                Console.Write("Saving data...");
                SaveData(arguments.OutputPath);
                SavePermissions(Providers.Instance.SecurityDataProvider, arguments.OutputPath);
                Console.WriteLine("ok.");

                // Build index
                Console.WriteLine("Building index.");

                Indexing.IsOuterSearchEngineEnabled = true;

                var nodeCount = DataStore.GetNodeCountAsync(CancellationToken.None)
                                .ConfigureAwait(false).GetAwaiter().GetResult();
                var count = 0;
                Console.Write($"{count} / {nodeCount}   \r");
                using (new SystemAccount())
                {
                    var populator = SearchManager.GetIndexPopulator();
                    populator.IndexDocumentRefreshed += (sender, e) =>
                    {
                        Console.Write($"{++count} / {nodeCount}   \r");
                    };
                    populator.RebuildIndexDirectlyAsync("/Root",
                                                        CancellationToken.None, IndexRebuildLevel.DatabaseAndIndex)
                    .ConfigureAwait(false).GetAwaiter().GetResult();
                    Console.WriteLine();
                }

                // Save index
                Console.Write("Saving index...");
                var indexFileName = Path.Combine(arguments.OutputPath, "index.txt");
                if (SearchManager.SearchEngine is InMemorySearchEngine searchEngine)
                {
                    searchEngine.Index.Save(indexFileName);
                }
                Console.WriteLine("ok.");
            }
        }
예제 #31
0
        // =================================================================================== IUser Members

        public bool IsInGroup(IGroup group)
        {
            return(SecurityHandler.IsInGroup(this.Id, group.Id));
        }
예제 #32
0
파일: TrashBag.cs 프로젝트: y1027/sensenet
        /// <summary>
        /// Returns a new <see cref="TrashBag"/> instance that packages the
        /// given <see cref="GenericContent"/> instance.
        /// </summary>
        /// <param name="node">The <see cref="GenericContent"/> instance that will be wrapped.</param>
        public static TrashBag BagThis(GenericContent node)
        {
            var bin = TrashBin.Instance;

            if (bin == null)
            {
                return(null);
            }

            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            // creating a bag has nothing to do with user permissions: Move will handle that
            TrashBag bag            = null;
            var      wsId           = 0;
            var      wsRelativePath = string.Empty;
            var      ws             = SystemAccount.Execute(() => node.Workspace);

            if (ws != null)
            {
                wsId           = ws.Id;
                wsRelativePath = node.Path.Substring(ws.Path.Length);
            }

            using (new SystemAccount())
            {
                bag = new TrashBag(bin)
                {
                    KeepUntil             = DateTime.UtcNow.AddDays(bin.MinRetentionTime),
                    OriginalPath          = RepositoryPath.GetParentPath(node.Path),
                    WorkspaceRelativePath = wsRelativePath,
                    WorkspaceId           = wsId,
                    DisplayName           = node.DisplayName,
                    Link  = node,
                    Owner = node.Owner
                };
                bag.Save();

                CopyPermissions(node, bag);

                // add delete permission for the owner
                SecurityHandler.CreateAclEditor()
                .Allow(bag.Id, node.OwnerId, false, PermissionType.Delete)
                .Apply();
            }

            try
            {
                Node.Move(node.Path, bag.Path);
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);

                bag.Destroy();

                throw new InvalidOperationException("Error moving item to the trash", ex);
            }

            return(bag);
        }
예제 #33
0
 public bool IsInOrganizationalUnit(IOrganizationalUnit orgUnit)
 {
     return(SecurityHandler.IsInGroup(this.Id, orgUnit.Id));
 }
예제 #34
0
        public void Should_not_throw_exception_when_the_user_is_authenticated()
        {
            // Arrange
            var controllerName = NameHelper.Controller<BlogController>();
            const string actionName = "Index";

            var events = new List<ISecurityEvent>();
            SecurityDoctor.Register(events.Add);
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor(controllerName, actionName, SecurityContext.Current));
            Assert.That(events.Any(e => e.Message == "Handling security for {0} action {1}.".FormatWith(controllerName, actionName)));
            Assert.That(events.Any(e => e.Message == "Done enforcing policies. Success!"));
        }
예제 #35
0
        static void Main(string[] args)
        {
            PDFNet.Initialize();

            // Relative path to the folder containing test files.
            string input_path  = "../../TestFiles/";
            string output_path = "../../TestFiles/Output/";

            // Example 1: Securing a document with password protection and adjusting permissions
            // on the document.
            try
            {
                // Open the test file
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("Securing an existing document...");
                using (PDFDoc doc = new PDFDoc(input_path + "fish.pdf"))
                {
                    if (!doc.InitSecurityHandler())
                    {
                        Console.WriteLine("Document authentication error...");
                        return;
                    }

                    // Perform some operation on the document. In this case we use low level SDF API
                    // to replace the content stream of the first page with contents of file 'my_stream.txt'
                    if (true)                      // Optional
                    {
                        Console.WriteLine("Replacing the content stream, use flate compression...");

                        // Get the first page dictionary using the following path: trailer/Root/Pages/Kids/0
                        Obj page_dict = doc.GetTrailer().Get("Root").Value().
                                        Get("Pages").Value().Get("Kids").Value().GetAt(0);

                        // Embed a custom stream (file mystream.txt) using Flate compression.
                        MappedFile   embed_file = new MappedFile(input_path + "my_stream.txt");
                        FilterReader mystm      = new FilterReader(embed_file);
                        page_dict.Put("Contents", doc.CreateIndirectStream(mystm));
                        embed_file.Close();
                    }

                    // Apply a new security handler with given security settings.
                    // In order to open saved PDF you will need a user password 'test'.
                    SecurityHandler new_handler = new SecurityHandler();
                    // Set a new password required to open a document
                    string my_password = "******";
                    new_handler.ChangeUserPassword(my_password);

                    // Set Permissions
                    new_handler.SetPermission(SecurityHandler.Permission.e_print, true);
                    new_handler.SetPermission(SecurityHandler.Permission.e_extract_content, false);

                    // Note: document takes the ownership of new_handler.
                    doc.SetSecurityHandler(new_handler);

                    // Save the changes.
                    Console.WriteLine("Saving modified file...");
                    doc.Save(output_path + "secured.pdf", 0);
                }

                Console.WriteLine("Done. Result saved in secured.pdf");
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            // Example 2: Reading password protected document without user feedback.
            try
            {
                // In this sample case we will open an encrypted document that
                // requires a user password in order to access the content.
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("Open the password protected document from the first example...");
                using (PDFDoc doc = new PDFDoc(output_path + "secured.pdf"))                    // Open the encrypted document that we saved in the first example.
                {
                    Console.WriteLine("Initializing security handler without any user interaction...");

                    // At this point MySecurityHandler callbacks will be invoked.
                    // MySecurityHandler.GetAuthorizationData() should collect the password and
                    // AuthorizeFailed() is called if user repeatedly enters a wrong password.
                    if (!doc.InitStdSecurityHandler("test"))
                    {
                        Console.WriteLine("Document authentication error...");
                        Console.WriteLine("The password is not valid.");
                        return;
                    }
                    else
                    {
                        Console.WriteLine("The password is correct! Document can now be used for reading and editing");

                        // Remove the password security and save the changes to a new file.
                        doc.RemoveSecurity();
                        doc.Save(output_path + "secured_nomore1.pdf", 0);
                        Console.WriteLine("Done. Result saved in secured_nomore1.pdf");
                    }
                }
            }
            catch (PDFNetException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Tests completed.");
        }
예제 #36
0
        internal async Task ProcessRequestAsync(HttpContext httpContext, ODataRequest odataRequest)
        {
            httpContext.SetODataRequest(odataRequest);

            var         request     = httpContext.Request;
            var         httpMethod  = request.Method;
            var         inputStream = request.Body;
            ODataWriter odataWriter = null;

            try
            {
                Content content;
                if (odataRequest == null)
                {
                    odataWriter = new ODataJsonWriter();
                    throw new ODataException("The Request is not an OData request.", ODataExceptionCode.RequestError);
                }

                odataWriter = ODataWriter.Create(httpContext, odataRequest);
                if (odataWriter == null)
                {
                    odataWriter = new ODataJsonWriter();
                    odataWriter.Initialize(odataRequest);
                    throw new ODataException(ODataExceptionCode.InvalidFormatParameter);
                }

                odataWriter.Initialize(odataRequest);

                var requestError = odataRequest.RequestError;
                if (requestError != null)
                {
                    var innerOdataError = requestError as ODataException;
                    var message         = "An error occured during request parsing. " + requestError.Message +
                                          " See inner exception for details.";
                    var code = innerOdataError?.ODataExceptionCode ?? ODataExceptionCode.RequestError;
                    throw new ODataException(message, code, requestError);
                }

                odataRequest.Format = odataWriter.FormatName;

                var requestedContent = LoadContentByVersionRequest(odataRequest.RepositoryPath, httpContext);

                var exists = requestedContent != null;
                if (!exists && !odataRequest.IsServiceDocumentRequest && !odataRequest.IsMetadataRequest &&
                    !AllowedMethodNamesWithoutContent.Contains(httpMethod))
                {
                    ContentNotFound(httpContext);
                    return;
                }

                JObject model;
                switch (httpMethod)
                {
                case "GET":
                    if (odataRequest.IsServiceDocumentRequest)
                    {
                        await odataWriter.WriteServiceDocumentAsync(httpContext, odataRequest)
                        .ConfigureAwait(false);
                    }
                    else if (odataRequest.IsMetadataRequest)
                    {
                        await odataWriter.WriteMetadataAsync(httpContext, odataRequest)
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        if (!Node.Exists(odataRequest.RepositoryPath))
                        {
                            ContentNotFound(httpContext);
                        }
                        else if (odataRequest.IsCollection)
                        {
                            await odataWriter.WriteChildrenCollectionAsync(odataRequest.RepositoryPath, httpContext,
                                                                           odataRequest)
                            .ConfigureAwait(false);
                        }
                        else if (odataRequest.IsMemberRequest)
                        {
                            await odataWriter.WriteContentPropertyAsync(
                                odataRequest.RepositoryPath, odataRequest.PropertyName,
                                odataRequest.IsRawValueRequest, httpContext, odataRequest)
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            await odataWriter.WriteSingleContentAsync(requestedContent, httpContext)
                            .ConfigureAwait(false);
                        }
                    }

                    break;

                case "PUT":     // update
                    if (odataRequest.IsMemberRequest)
                    {
                        throw new ODataException("Cannot access a member with HTTP PUT.",
                                                 ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        model = await ReadToJsonAsync(httpContext).ConfigureAwait(false);

                        content = LoadContentOrVirtualChild(odataRequest);
                        if (content == null)
                        {
                            ContentNotFound(httpContext);
                            return;
                        }

                        ResetContent(content);
                        UpdateContent(content, model, odataRequest);
                        await odataWriter.WriteSingleContentAsync(content, httpContext)
                        .ConfigureAwait(false);
                    }

                    break;

                case "MERGE":
                case "PATCH":     // update
                    if (odataRequest.IsMemberRequest)
                    {
                        throw new ODataException(
                                  String.Concat("Cannot access a member with HTTP ", httpMethod, "."),
                                  ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        model = await ReadToJsonAsync(httpContext).ConfigureAwait(false);

                        content = LoadContentOrVirtualChild(odataRequest);
                        if (content == null)
                        {
                            ContentNotFound(httpContext);
                            return;
                        }

                        UpdateContent(content, model, odataRequest);
                        await odataWriter.WriteSingleContentAsync(content, httpContext)
                        .ConfigureAwait(false);
                    }

                    break;

                case "POST":     // invoke an action, create content
                    if (odataRequest.IsMemberRequest)
                    {
                        // MEMBER REQUEST
                        await odataWriter.WritePostOperationResultAsync(httpContext, odataRequest)
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        // CREATION
                        if (!Node.Exists(odataRequest.RepositoryPath))
                        {
                            // parent does not exist
                            ContentNotFound(httpContext);
                            return;
                        }

                        model = await ReadToJsonAsync(httpContext).ConfigureAwait(false);

                        var newContent = CreateNewContent(model, odataRequest);
                        await odataWriter.WriteSingleContentAsync(newContent, httpContext)
                        .ConfigureAwait(false);
                    }

                    break;

                case "DELETE":
                    if (odataRequest.IsMemberRequest)
                    {
                        throw new ODataException(
                                  String.Concat("Cannot access a member with HTTP ", httpMethod, "."),
                                  ODataExceptionCode.IllegalInvoke);
                    }
                    else
                    {
                        content = LoadContentOrVirtualChild(odataRequest);
                        if (content != null)
                        {
                            var x = httpContext.Request.Query["permanent"].ToString();
                            if (x.Equals("true", StringComparison.OrdinalIgnoreCase))
                            {
                                content.DeletePhysical();
                            }
                            else
                            {
                                content.Delete();
                            }
                        }
                    }

                    break;
                }
            }
            catch (ContentNotFoundException e)
            {
                var oe = new ODataException(ODataExceptionCode.ResourceNotFound, e);
                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (ODataException e)
            {
                if (e.HttpStatusCode == 500)
                {
                    SnLog.WriteException(e);
                }
                await odataWriter.WriteErrorResponseAsync(httpContext, e)
                .ConfigureAwait(false);
            }
            catch (AccessDeniedException e)
            {
                var oe = new ODataException(ODataExceptionCode.Forbidden, e);
                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (UnauthorizedAccessException e)
            {
                var oe = new ODataException(ODataExceptionCode.Unauthorized, e);
                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (SenseNetSecurityException e)
            {
                // In case of a visitor we should not expose the information that this content actually exists. We return
                // a simple 404 instead to provide exactly the same response as the regular 404, where the content
                // really does not exist. But do this only if the visitor really does not have permission for the
                // requested content (because security exception could be thrown by an action or something else too).
                if (odataRequest != null && User.Current.Id == Identifiers.VisitorUserId)
                {
                    var head = NodeHead.Get(odataRequest.RepositoryPath);
                    if (head != null && !SecurityHandler.HasPermission(head, PermissionType.Open))
                    {
                        ContentNotFound(httpContext);
                        return;
                    }
                }

                var oe = new ODataException(ODataExceptionCode.NotSpecified, e);

                SnLog.WriteException(oe);

                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (InvalidContentActionException ex)
            {
                var oe = new ODataException(ODataExceptionCode.NotSpecified, ex);
                if (ex.Reason != InvalidContentActionReason.NotSpecified)
                {
                    oe.ErrorCode = Enum.GetName(typeof(InvalidContentActionReason), ex.Reason);
                }

                // it is unnecessary to log this exception as this is not a real error
                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (ContentRepository.Storage.Data.NodeAlreadyExistsException nae)
            {
                var oe = new ODataException(ODataExceptionCode.ContentAlreadyExists, nae);

                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                var oe = new ODataException(ODataExceptionCode.NotSpecified, ex);

                SnLog.WriteException(oe);

                await odataWriter.WriteErrorResponseAsync(httpContext, oe)
                .ConfigureAwait(false);
            }
        }
예제 #37
0
        public void ContentProtector_DeleteUser()
        {
            Test(() =>
            {
                CreateUserAndGroupStructure();

                // add permissions for the users to let them perform the Delete operation
                var user1   = Node.Load <User>("/Root/IMS/Public/TestOrg/user1");
                var user2   = Node.Load <User>("/Root/IMS/Public/TestOrg/user2");
                var testOrg = Node.Load <OrganizationalUnit>("/Root/IMS/Public/TestOrg");

                SecurityHandler.CreateAclEditor()
                .Allow(testOrg.Id, user1.Id, false, PermissionType.Save, PermissionType.Delete)
                .Allow(testOrg.Id, user2.Id, false, PermissionType.Save, PermissionType.Delete)
                .Apply();

                var originalUser = AccessProvider.Current.GetOriginalUser();
                try
                {
                    AccessProvider.Current.SetCurrentUser(user1);

                    // delete user2 without a problem
                    user2.ForceDelete();
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                var thrown = false;
                try
                {
                    AccessProvider.Current.SetCurrentUser(user1);

                    // try to delete themselves
                    user1.ForceDelete();
                }
                catch (ApplicationException ex)
                {
                    if (ex.Message.Contains("Users cannot delete"))
                    {
                        thrown = true;
                    }
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                Assert.IsTrue(thrown, "Exception was not thrown.");

                thrown = false;
                try
                {
                    AccessProvider.Current.SetCurrentUser(user1);

                    // try to delete parent
                    testOrg.ForceDelete();
                }
                catch (ApplicationException ex)
                {
                    if (ex.Message.Contains("Users cannot delete"))
                    {
                        thrown = true;
                    }
                }
                finally
                {
                    AccessProvider.Current.SetCurrentUser(originalUser);
                }

                Assert.IsTrue(thrown, "Exception was not thrown.");
            });
        }
        public void Should_throw_when_the_user_is_anonymous()
        {
            // Arrange
            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.GetRolesFrom(StaticHelper.GetRolesExcludingOwner);
                policy.For<BlogController>(x => x.DeletePost(0)).RequireRole(UserRole.Owner);
            });

            var securityHandler = new SecurityHandler();

            // Act
            var exception = Assert.Throws<PolicyViolationException>(() => securityHandler.HandleSecurityFor(NameHelper.Controller<BlogController>(), "DeletePost", SecurityContext.Current));

            // Assert
            Assert.That(exception.PolicyType, Is.EqualTo(typeof(RequireRolePolicy)));
            Assert.That(exception.Message, Is.StringContaining("Anonymous access denied"));
        }
예제 #39
0
 public List <int> GetGroups()
 {
     return(SecurityHandler.GetGroups(this));
 }
        public void Should_throw_ConfigurationErrorsException_when_IgnoreMissingConfigurations_is_false()
        {
            // Arrange
            ExceptionFactory.RequestDescriptionProvider = () => TestDataFactory.CreateRequestDescription();

            SecurityConfigurator.Configure(policy =>
            {
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act & Assert
            Assert.Throws<ConfigurationErrorsException>(() => securityHandler.HandleSecurityFor("NonConfiguredController", "Action", SecurityContext.Current));
        }
예제 #41
0
        protected override void CreateChildControls()
        {
            if (this.ContextNode == null)
            {
                return;
            }

            if (ShowExecutionTime)
            {
                Timer.Start();
            }

            System.Web.UI.Control control = null;
            try
            {
                var viewHead = NodeHead.Get(ControlPath);
                if (viewHead != null && SecurityHandler.HasPermission(viewHead, PermissionType.RunApplication))
                {
                    control = Page.LoadControl(ControlPath);
                    this.Controls.Add(control);
                }
            }
            catch (Exception ex)
            {
                SnLog.WriteException(ex);
                this.Controls.Add(new System.Web.UI.LiteralControl(ex.Message));
                return;
            }

            if (control == null)
            {
                return;
            }

            _workspaceIsWallContainer = control.FindControlRecursive("WorkspaceIsWallContainer") as PlaceHolder;
            var portletContextNodeLink = control.FindControlRecursive("PortletContextNodeLink") as System.Web.UI.WebControls.HyperLink;
            var configureWorkspaceWall = control.FindControlRecursive("ConfigureWorkspaceWall") as Button;

            if (_workspaceIsWallContainer != null && configureWorkspaceWall != null)
            {
                _workspaceIsWallContainer.Visible = false;

                var ws = this.ContextNode as Workspace;
                if (ws != null && !ws.IsWallContainer && ws.Security.HasPermission(PermissionType.Save))
                {
                    _workspaceIsWallContainer.Visible = true;
                    if (portletContextNodeLink != null)
                    {
                        portletContextNodeLink.Text        = System.Web.HttpUtility.HtmlEncode(Content.Create(ws).DisplayName);
                        portletContextNodeLink.NavigateUrl = ws.Path;
                    }

                    configureWorkspaceWall.Click += ConfigureWorkspaceWall_Click;
                }
            }

            var postsPlaceholder = control.FindControlRecursive("Posts");

            List <PostInfo> posts;

            var postInfos = GatherPosts();

            posts = postInfos == null ? new List <PostInfo>() : postInfos.Take(PageSize).ToList();

            postsPlaceholder.Controls.Add(new Literal {
                Text = WallHelper.GetWallPostsMarkup(this.ContextNode.Path, posts)
            });

            if (ShowExecutionTime)
            {
                Timer.Stop();
            }

            base.CreateChildControls();
            this.ChildControlsCreated = true;
        }
예제 #42
0
 public bool IsInContainer(ISecurityContainer container)
 {
     return(SecurityHandler.IsInGroup(this.Id, container.Id));
 }
예제 #43
0
        // Voting View
        private void AddVotingView()
        {
            var votingNode = ContextNode as Voting;

            if (votingNode == null)
            {
                Controls.Add(new Literal {
                    Text = SenseNetResourceManager.Current.GetString("Voting", "ContextNodeError")
                });
                return;
            }

            if (votingNode.IsVotingAvailable)
            {
                if (votingNode.VotingPageContentView != null)
                {
                    var contentView = ContentView.Create(_currentContent, Page, ViewMode.Browse, votingNode.VotingPageContentView.Path);
                    if (contentView == null)
                    {
                        Controls.Add(new Literal {
                            Text = SenseNetResourceManager.Current.GetString("Voting", "ContentViewCreateError")
                        });
                        return;
                    }

                    //add ContentView to the Controls collection
                    Controls.Add(contentView);

                    var qph = contentView.FindControlRecursive("QuestionPlaceHolder") as PlaceHolder;
                    if (qph == null)
                    {
                        Controls.Clear();
                        Controls.Add(new Literal {
                            Text = SenseNetResourceManager.Current.GetString("Voting", "PlaceHolderError")
                        });
                        return;
                    }

                    var args = new object[0];

                    // Checks if Foldering is enabled and sets the parent depending on it
                    var parent     = FolderingEnabled ? GetFolder(ContextNode) : ContextNode;
                    var votingItem = Content.CreateNew("VotingItem", parent, null, args);

                    // If there is no question in the Voting (question is avalaible on the Voting Items under the Voting)
                    var isQuestionExist = votingItem.Fields.Any(a => a.Value.Name.StartsWith("#"));
                    if (!isQuestionExist)
                    {
                        Controls.Add(new Literal {
                            Text = SenseNetResourceManager.Current.GetString("Voting", "NoQuestion")
                        });
                        return;
                    }

                    var votingItemNewContentView = ContentView.Create(votingItem, Page, ViewMode.InlineNew);
                    if (votingItemNewContentView == null)
                    {
                        Controls.Add(new Literal {
                            Text = SenseNetResourceManager.Current.GetString("Voting", "ContentViewCreateError")
                        });
                        return;
                    }
                    votingItemNewContentView.ID          = "VotingItenContentView";
                    votingItemNewContentView.UserAction += VotingItemNewContentViewUserAction;

                    qph.Controls.Add(votingItemNewContentView);

                    if (!SecurityHandler.HasPermission(votingItemNewContentView.ContentHandler, PermissionType.AddNew))
                    {
                        var btn = votingItemNewContentView.FindControlRecursive("ActButton1") as Button;
                        if (btn != null)
                        {
                            btn.Visible = false;
                        }
                    }

                    if (MoreFilingIsEnabled && IsResultAvalaibleBefore && VotingPortletMode == PortletMode.VoteAndGotoResult)
                    {
                        var lb = contentView.FindControl("VotingAndResult") as LinkButton;
                        if (lb == null)
                        {
                            Controls.Add(new Literal {
                                Text = SenseNetResourceManager.Current.GetString("Voting", "CannotFindLink")
                            });
                            return;
                        }

                        lb.Text    = SenseNetResourceManager.Current.GetString("Voting", "GoToResultLink");
                        lb.Click  += LbClick;
                        lb.Visible = true;
                    }
                    return;
                }
                // No content view is set
                Controls.Add(new Literal {
                    Text = SenseNetResourceManager.Current.GetString("Voting", "NoContentView")
                });
            }
            else
            {
                // When the user can only Vote once
                Controls.Add(new Literal {
                    Text = SenseNetResourceManager.Current.GetString("Voting", "OnlyOneVoteError")
                });
            }
        }
        public void Should_throw_ArgumentNulllException_when_security_context_is_null()
        {
            // Arrange
            var securityHandler = new SecurityHandler();
            const ISecurityContext securityContext = null;

            // Assert
            Assert.Throws<ArgumentNullException>(() => securityHandler.HandleSecurityFor("A", "A", securityContext));
        }
예제 #45
0
 public bool IsInGroup(int securityGroupId)
 {
     return(SecurityHandler.IsInGroup(this.Id, securityGroupId));
 }