Example #1
0
        /// <summary>
        /// Initializes a new instance of the AuthorizationRule class.
        /// </summary>
        /// <param name="rights">The rights associated with the rule.</param>
        /// <param name="id">Resource Id</param>
        /// <param name="name">Resource name</param>
        /// <param name="type">Resource type</param>

        public AuthorizationRuleAttributes(AuthorizationRule authorizationrule)
        {
            Id     = authorizationrule.Id;
            Name   = authorizationrule.Name;
            Type   = authorizationrule.Type;
            Rights = authorizationrule.Rights;
        }
 public CountryRequirement(AuthorizationRule options)
 {
     if (options != null && !string.IsNullOrEmpty(options.Country))
     {
         ClaimValue = options.Country;
     }
 }
Example #3
0
        private void OnAuthorizeRequest(object source, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication) source;
            HttpContext context = application.Context;

            // If an <authorization> section exists in the current web.config, and it hasn't yet
            // been registered with the AuthorizationService, add it now.
            IAuthorizationService authorizationService = WebSecurityEngine.Get<IAuthorizationService>();
            AuthorizationSection authorizationSection = System.Web.Configuration.WebConfigurationManager.GetSection("zeus.web/authorization") as AuthorizationSection;
            string locationPath = context.Request.Path.ToLower();
            if (authorizationSection != null && !authorizationService.LocationExists(locationPath))
            {
                List<AuthorizationRule> rules = new List<AuthorizationRule>();
                foreach (AuthorizationRule authorizationRule in authorizationSection.Rules)
                {
                    AuthorizationRule rule = new AuthorizationRule();
                    rule.Action = (authorizationRule.Action == AuthorizationRuleAction.Allow) ? AuthorizationRuleAction.Allow : AuthorizationRuleAction.Deny;
                    rule.Roles.AddRange(authorizationRule.Roles);
                    rule.Users.AddRange(authorizationRule.Users);
                    rules.Add(rule);
                }
                authorizationService.AddRules(locationPath, rules);
            }

            if (!context.SkipAuthorization)
            {
                if (!authorizationService.CheckUrlAccessForPrincipal(context.Request.Url.AbsolutePath, context.User, context.Request.RequestType))
                {
                    context.Response.StatusCode = 0x191;
                    application.CompleteRequest();
                }
            }
        }
Example #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions <AuthorizationRule>();

            var authorizationRule = new AuthorizationRule();

            Configuration.Bind("Authorization", authorizationRule);

            services.Configure <AuthorizationRule>(Configuration.GetSection("Authorization"));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.Authority = Configuration["AzureAD:Authority"];
                options.Audience  = Configuration["AzureAD:Audience"];
                options.SaveToken = true;
            });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ClaimAuthorization", policy =>
                {
                    policy.Requirements.Add(new CountryRequirement(authorizationRule));
                    policy.Requirements.Add(new GroupRequirement(authorizationRule));
                });
            });
            services.AddTransient <IAuthorizationHandler, CountryAuthorizationHandler>();
            services.AddTransient <IAuthorizationHandler, GroupAuthorizationHandler>();

            services.AddControllers();
        }
Example #5
0
        public async void TestEdit()
        {
            await this.SetUp();

            var item     = new AuthorizationRule(null);
            var original = "testers";

            item.Roles = original;
            _feature.AddItem(item);

            Assert.Equal(original, _feature.SelectedItem.Roles);
            Assert.Equal(2, _feature.Items.Count);
            var expected = "defenders";

            item.Roles = expected;
            _feature.EditItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal(expected, _feature.SelectedItem.Roles);
            Assert.Equal(2, _feature.Items.Count);

            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(Path.Combine("Authorization", "expected_edit1.site.config"), Path.Combine("Website1", "web.config"));
        }
 private void AssertRuleCorrect(AuthorizationRule expected, WikiAuthorizationRule actual, string message)
 {
     Assert.AreEqual(expected.Action, actual.Action, "Checking that action was correct for " + message);
     Assert.AreEqual(expected.Polarity, actual.Polarity, "Checking that polarity was correct for " + message);
     Assert.AreEqual(expected.Who.Who, actual.Who, "Checking that who was correct for " + message);
     Assert.AreEqual(expected.Who.WhoType, actual.WhoType, "Checking that who type was correct for " + message);
 }
        public async Task<IActionResult> Edit(int id, [Bind("HandlerMethodSignature,TypeFullName,IdentificationKey,AuthorizationRuleConfigJson,Id,Remark,OrderNumber,RowVersion,IsEnable,IsDeleted,CreationTime,LastModificationTime,CreatorId,LastModificationUserId")] AuthorizationRule requestAuthorizationRule)
        {
            if (id != requestAuthorizationRule.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(requestAuthorizationRule);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RequestAuthorizationRuleExists(requestAuthorizationRule.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(requestAuthorizationRule);
        }
Example #8
0
        public override void ExecuteCmdlet()
        {
            Client = Client ?? new ServiceBusClientExtensions(CurrentSubscription, WriteDebug);
            AuthorizationRule rule   = null;
            PSObject          output = null;

            switch (ParameterSetName)
            {
            case NamespaceSASParameterSet:
                rule   = Client.UpdateSharedAccessAuthorization(Namespace, Name, PrimaryKey, SecondaryKey, Permission);
                output = ServiceBusPowerShellUtility.GetNamespacePSObject(rule);
                break;

            case EntitySASParameterSet:
                rule = Client.UpdateSharedAccessAuthorization(
                    Namespace,
                    EntityName,
                    EntityType,
                    Name,
                    PrimaryKey,
                    SecondaryKey,
                    Permission);
                output = ServiceBusPowerShellUtility.GetEntityPSObject(rule);
                break;

            default:
                throw new ArgumentException(string.Format(Resources.InvalidParameterSetName, ParameterSetName));
            }

            WriteObject(output);
        }
        public void TestAdd()
        {
            SetUp();

            var site          = Path.Combine("Website1", "web.config");
            var expected      = "expected_add.site.config";
            var document      = XDocument.Load(site);
            var node          = document.Root.XPathSelectElement("/configuration/system.webServer");
            var security      = new XElement("security");
            var authorization = new XElement("authorization");
            var add           = new XElement("add");

            add.SetAttributeValue("roles", "test");
            add.SetAttributeValue("accessType", "Allow");
            node?.Add(security);
            security.Add(authorization);
            authorization.Add(add);
            document.Save(expected);

            var item = new AuthorizationRule(null);

            item.Roles = "test";
            _feature.AddItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.Equal("test", _feature.SelectedItem.Roles);

            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }
Example #10
0
    public void CreateRule(object sender, EventArgs e)
    {
        AuthorizationRule newRule;

        if (ActionAllow.Checked)
        {
            newRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
        }
        else
        {
            newRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
        }

        if (ApplyRole.Checked && UserRoles.SelectedIndex > 0)
        {
            newRule.Roles.Add(UserRoles.Text);
            AddRule(newRule);
        }
        else if (ApplyUser.Checked && UserList.SelectedIndex > 0)
        {
            newRule.Users.Add(UserList.Text);
            AddRule(newRule);
        }
        else if (ApplyAllUsers.Checked)
        {
            newRule.Users.Add("*");
            AddRule(newRule);
        }
        else if (ApplyAnonUser.Checked)
        {
            newRule.Users.Add("?");
            AddRule(newRule);
        }
    }
        public void TestRemove()
        {
            SetUp();

            var site     = Path.Combine("Website1", "web.config");
            var expected = "expected_remove1.site.config";
            var document = XDocument.Load(site);

            document.Save(expected);

            var item = new AuthorizationRule(null);

            item.Roles = "test";
            _feature.AddItem(item);

            Assert.Equal("test", _feature.SelectedItem.Roles);
            Assert.Equal(2, _feature.Items.Count);
            _feature.Remove();
            Assert.Null(_feature.SelectedItem);
            Assert.Single(_feature.Items);

            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }
Example #12
0
        public FileShareWitnessCheckResult Check()
        {
            this.RecalculateAccessRules();
            if (!this.Exists())
            {
                return(FileShareWitnessCheckResult.FswDoesNotExist);
            }
            if (this.m_existingWitnessDirectory != this.WitnessDirectory)
            {
                return(FileShareWitnessCheckResult.FswWrongDirectory);
            }
            AuthorizationRuleCollection accessRules = this.m_existingSecurity.GetAccessRules(true, true, typeof(NTAccount));

            if (accessRules == null)
            {
                return(FileShareWitnessCheckResult.FswWrongPermissions);
            }
            List <FileSystemAccessRule> list = new List <FileSystemAccessRule>(this.AccessRules);

            foreach (object obj in accessRules)
            {
                AuthorizationRule    authorizationRule    = (AuthorizationRule)obj;
                FileSystemAccessRule fsRule               = (FileSystemAccessRule)authorizationRule;
                FileSystemAccessRule fileSystemAccessRule = list.Find((FileSystemAccessRule ar) => fsRule.IdentityReference == ar.IdentityReference && fsRule.FileSystemRights == ar.FileSystemRights);
                if (fileSystemAccessRule != null)
                {
                    list.Remove(fileSystemAccessRule);
                }
            }
            if (list.Count == 0)
            {
                return(FileShareWitnessCheckResult.FswOK);
            }
            return(FileShareWitnessCheckResult.FswWrongPermissions);
        }
        private void RemoveUnwantedDkmContainerAccessRules(string dkmContainerName, IEnumerable <SecurityIdentifier> principalsToHaveKeyReadWritePermissionsAdded, IEnumerable <SecurityIdentifier> principalsToHaveFullControlPermissionsAdded, string rootDomainDN)
        {
            DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("LDAP://CN={0},{1},{2},{3}", new object[]
            {
                dkmContainerName,
                "CN=Distributed KeyMan",
                "CN=Microsoft,CN=Program Data",
                rootDomainDN
            }));

            if (!directoryEntry.ObjectSecurity.AreAccessRulesCanonical)
            {
                InitializeDkmDatacenter.CanonicalizeAcl(directoryEntry.ObjectSecurity);
            }
            AuthorizationRuleCollection accessRules = directoryEntry.ObjectSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));

            foreach (object obj in accessRules)
            {
                AuthorizationRule authorizationRule = (AuthorizationRule)obj;
                if (!(authorizationRule.IdentityReference == InitializeDkmDatacenter.DomainAdminsSid) && !InitializeDkmDatacenter.IsIdentityInCollection(authorizationRule.IdentityReference, principalsToHaveKeyReadWritePermissionsAdded) && !InitializeDkmDatacenter.IsIdentityInCollection(authorizationRule.IdentityReference, principalsToHaveFullControlPermissionsAdded))
                {
                    this.WriteWarning(Strings.RemovingAceFromDkmContainerAcl(dkmContainerName, InitializeDkmDatacenter.AccountNameFromSid(authorizationRule.IdentityReference.ToString())));
                    directoryEntry.ObjectSecurity.PurgeAccessRules(authorizationRule.IdentityReference);
                }
            }
            directoryEntry.ObjectSecurity.SetSecurityDescriptorBinaryForm(directoryEntry.ObjectSecurity.GetSecurityDescriptorBinaryForm());
            directoryEntry.CommitChanges();
            directoryEntry.Close();
        }
Example #14
0
        public async Task <IActionResult> Edit(Guid id, [Bind("AuthorizationRuleConfigJson,Id,Remark,OrderNumber,RowVersion,IsEnable,IsDeleted,CreationTime,LastModificationTime,CreationUserId,LastModificationUserId")] AuthorizationRule authorizationRule)
        {
            if (id != authorizationRule.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(authorizationRule);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!AuthorizationRuleExists(authorizationRule.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CreationUserId"]         = new SelectList(_context.Users, "Id", "Id", authorizationRule.CreationUserId);
            ViewData["LastModificationUserId"] = new SelectList(_context.Users, "Id", "Id", authorizationRule.LastModificationUserId);
            return(View(authorizationRule));
        }
        public void Defaults()
        {
            AuthorizationRule a = new AuthorizationRule(AuthorizationRuleAction.Deny);

            Assert.AreEqual(AuthorizationRuleAction.Deny, a.Action, "A1");
            Assert.IsNotNull(a.Roles, "A2");
            Assert.IsNotNull(a.Users, "A3");
            Assert.IsNotNull(a.Verbs, "A4");
        }
        private static bool IsSpecifiedToIdentity(AuthorizationRule rule, WindowsIdentity identity)
        {
            if (identity.User != null && identity.User == rule.IdentityReference)
            {
                return(true);
            }

            return(identity.Groups != null && identity.Groups.Any(g => g == rule.IdentityReference));
        }
Example #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="authRuleResource"></param>
 public SharedAccessAuthorizationRuleAttributes(AuthorizationRule authRuleResource)
 {
     if (authRuleResource != null)
     {
         Id     = authRuleResource.Id;
         Name   = authRuleResource.Name;
         Type   = authRuleResource.Type;
         Rights = authRuleResource.Rights;
     }
 }
        public PSSharedAccessAuthorizationRuleAttributes CreateOrUpdateNamespaceAuthorizationRules(string resourceGroupName, string namespaceName, string authorizationRuleName, PSSharedAccessAuthorizationRuleAttributes parameter)
        {
            var parameter1 = new AuthorizationRule()
            {
                Rights = parameter.Rights.ToList()
            };
            var response = Client.Namespaces.CreateOrUpdateAuthorizationRule(resourceGroupName, namespaceName, authorizationRuleName, parameter1);

            return(new PSSharedAccessAuthorizationRuleAttributes(response));
        }
 public async Task<IActionResult> Create([Bind("HandlerMethodSignature,TypeFullName,IdentificationKey,AuthorizationRuleConfigJson,Id,Remark,OrderNumber,RowVersion,IsEnable,IsDeleted,CreationTime,LastModificationTime,CreatorId,LastModificationUserId")] AuthorizationRule requestAuthorizationRule)
 {
     if (ModelState.IsValid)
     {
         _context.Add(requestAuthorizationRule);
         await _context.SaveChangesAsync();
         return RedirectToAction(nameof(Index));
     }
     return View(requestAuthorizationRule);
 }
Example #20
0
        public void delete(AuthorizationRule dbitem)
        {
            context.AuthorizationRule.Remove(dbitem);
            var auditrail = new Auditrail {
                Actionnya = "Delete", EventDate = DateTime.Now, Modulenya = "General Setting", QueryDetail = "Delete " + dbitem.Id, RemoteAddress = AppHelper.GetIPAddress(), IdUser = 1
            };

            context.Auditrail.Add(auditrail);
            context.SaveChanges();
        }
Example #21
0
 public static PSObject GetNamespacePSObject(AuthorizationRule rule)
 {
     return(null == rule? null : PowerShellUtility.ConstructPSObject(
                typeof(AuthorizationRule).FullName,
                "Namespace", rule.Namespace,
                "Name", rule.Name,
                "ConnectionString", rule.ConnectionString,
                "Permission", rule.Permission,
                "Rule", rule.Rule));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="authRuleResource"></param>
 public AuthorizationRuleAttributes(AuthorizationRule authRuleResource)
 {
     if (authRuleResource != null)
     {
         Id     = authRuleResource.Id;
         Name   = authRuleResource.Name;
         Type   = authRuleResource.Type;
         Rights = authRuleResource.Rights.ToList();
     }
 }
Example #23
0
        public SharedAccessAuthorizationRuleAttributes CreateOrUpdateEventHubAuthorizationRules(string resourceGroupName, string namespaceName, string eventHubName, string authorizationRuleName, SharedAccessAuthorizationRuleAttributes parameters)
        {
            var parameter1 = new AuthorizationRule()
            {
                Rights = parameters.Rights.ToList()
            };

            var response = Client.EventHubs.CreateOrUpdateAuthorizationRule(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, parameter1);

            return(new SharedAccessAuthorizationRuleAttributes(response));
        }
Example #24
0
        public AuthorizationRuleAttributes CreateOrUpdateWcfRelayAuthorizationRules(string resourceGroupName, string namespaceName, string wcfRelayName, string authorizationRuleName, AuthorizationRuleAttributes parameters)
        {
            var parameter1 = new AuthorizationRule()
            {
                Rights = parameters.Rights.ToList()
            };

            var response = Client.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroupName, namespaceName, wcfRelayName, authorizationRuleName, parameter1);

            return(new AuthorizationRuleAttributes(response));
        }
        public WikiAuthorizationRule(AuthorizationRule rule)
        {
            if (rule.Scope != AuthorizationRuleScope.Wiki)
            {
                throw new ArgumentException("Rule must be a wiki-level rule.");
            }

            _action = rule.Action;
            _polarity = rule.Polarity;
            _who = rule.Who;
        }
Example #26
0
        public AuthorizationRuleAttributes CreateOrUpdateHybridConnectionsAuthorizationRules(string resourceGroupName, string namespaceName, string hybridConnectionsName, string authorizationRuleName, AuthorizationRuleAttributes parameters)
        {
            var parameter1 = new AuthorizationRule()
            {
                Rights = parameters.Rights.ToList()
            };

            var response = Client.HybridConnections.CreateOrUpdateAuthorizationRule(resourceGroupName, namespaceName, hybridConnectionsName, authorizationRuleName, parameter1);

            return(new AuthorizationRuleAttributes(response));
        }
Example #27
0
            public RulesBundle(ContextModel context, IRule rule)
            {
                OrderResourceRule = new ResourceRule <Olma.Order>(context.Id, rule).Include(o => o.Group)
                                    .Include(o => o.CreatedBy).Include(u => u.CreatedBy.Person)
                                    .Include(i => i.DplNotes);

                var getOperatorRule = new GetOperatorRule <ContextModel, Olma.Order>(context, (c) => c.Rules.OrderResourceRule.Context.Resource);

                AuthorizationRule = new AuthorizationRule <Olma.Order, ContextModel, DivisionPermissionResource, CanCancelOrderRequirement>(getOperatorRule, rule);
                OrderCancelStatusValidationRule = new OrderCancelStatusValidationRule <Olma.Order, ContextModel>(getOperatorRule, rule);
            }
        public void SerializeAuthorization()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            AuthorizationRule rule = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.GenericAnonymous),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.Edit, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(rule));

            XmlSerializer serializer = new XmlSerializer(typeof(FederationConfiguration));
            serializer.Serialize(Console.Out, configuration);

            Assert.Fail("Need to add real verification to this.");
        }
        public async Task <IActionResult> Create([Bind("AuthorizationRuleConfigJson,Id,Remark,OrderNumber,RowVersion,IsEnable,IsDeleted,CreationTime,LastModificationTime,CreatorId,LastModificationUserId")] AuthorizationRule authorizationRule)
        {
            if (ModelState.IsValid)
            {
                _permissionDbContext.Add(authorizationRule);
                await _permissionDbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["CreatorId"] = new SelectList(_identitycontext.Users, "Id", "Id", authorizationRule.CreatorId);
            return(View(authorizationRule));
        }
        /// <summary>
        /// Initializes a new instance of the AuthorizationRule class.
        /// </summary>
        /// <param name="rights">The rights associated with the rule.</param>
        /// <param name="id">Resource Id</param>
        /// <param name="name">Resource name</param>
        /// <param name="type">Resource type</param>

        public AuthorizationRuleAttributes(AuthorizationRule authorizationrule)
        {
            Id   = authorizationrule.Id;
            Name = authorizationrule.Name;
            Type = authorizationrule.Type;

            Rights = new List <string>();

            foreach (AccessRights rights in authorizationrule.Rights)
            {
                Rights.Add(rights.ToString());
            }
        }
Example #31
0
            public RulesBundle(ContextModel context, IRule rule)
            {
                VoucherResourceRule = new ResourceRule <Olma.Voucher>(x => x.Document.Number == context.Number, rule);

                var getOperator = new GetOperatorRule <ContextModel, Olma.Voucher>(context,
                                                                                   model => model.Rules.VoucherResourceRule.Context.Resource);

                VoucherAuthorizationRule = new AuthorizationRule <
                    Olma.Voucher,
                    ContextModel,
                    DivisionPermissionResource,
                    CanReadVoucherRequirement>(getOperator, rule);
            }
Example #32
0
 public void RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         AuthorizationRule rule = (AuthorizationRule)e.Row.DataItem;
         if (!rule.ElementInformation.IsPresent)
         {
             e.Row.Cells[3].Text = "Inherited from higher level";
             e.Row.Cells[4].Text = "Inherited from higher level";
             e.Row.CssClass      = "odd";
         }
     }
 }
Example #33
0
        public PSAuthorizationRuleAttributes CreateOrUpdateWcfRelayAuthorizationRules(string resourceGroupName, string namespaceName, string wcfRelayName, string authorizationRuleName, PSAuthorizationRuleAttributes parameters)
        {
            var parameter1 = new AuthorizationRule()
            {
                Rights = parameters.Rights.Select(x => Enum.Parse(typeof(AccessRights), x))
                         .Cast <AccessRights?>()
                         .ToList()
            };

            var response = Client.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroupName, namespaceName, wcfRelayName, authorizationRuleName, parameter1);

            return(new PSAuthorizationRuleAttributes(response));
        }
Example #34
0
        /// <summary>
        /// Fills iis configuration  from ftp account.
        /// </summary>
        /// <param name="ftpAccount">Ftp account to fill from.</param>
        private void FillIisFromFtpAccount(FtpAccount ftpAccount)
        {
            // Remove permissions if required.
            string currentPhysicalPath = this.ftpSitesService.GetSitePhysicalPath(this.SiteId, String.Format("/{0}", ftpAccount.Name));

            if (String.Compare(currentPhysicalPath, ftpAccount.Folder, true) != 0)
            {
                RemoveFtpFolderPermissions(currentPhysicalPath, ftpAccount.Name);
            }

            // Set new permissions
            EnsureUserHomeFolderExists(ftpAccount.Folder, ftpAccount.Name, ftpAccount.CanRead, ftpAccount.CanWrite);
            // Update physical path.
            this.ftpSitesService.SetSitePhysicalPath(this.SiteId, ftpAccount.VirtualPath, ftpAccount.Folder);

            // Configure connect as feature.
            this.ftpSitesService.ConfigureConnectAs(ftpAccount.Folder, this.SiteId, ftpAccount.VirtualPath,
                                                    this.GetQualifiedAccountName(ftpAccount.Name), ftpAccount.Password, false);

            // Update authorization rules.
            AuthorizationRuleCollection authRulesCollection = this.ftpSitesService.GetAuthorizationRuleCollection(String.Format("{0}/{1}", this.SiteId, ftpAccount.Name));
            AuthorizationRule           realtedRule         = null;

            foreach (AuthorizationRule rule in authRulesCollection)
            {
                IList <string> users = rule.Users.Split(',');
                if (users.Contains(ftpAccount.Name))
                {
                    realtedRule = rule;
                }
            }
            if (realtedRule != null)
            {
                PermissionsFlags permissions = 0;
                if (ftpAccount.CanRead)
                {
                    permissions |= PermissionsFlags.Read;
                }
                if (ftpAccount.CanWrite)
                {
                    permissions |= PermissionsFlags.Write;
                }
                if (ftpAccount.CanRead || ftpAccount.CanWrite)
                {
                    realtedRule.Permissions = permissions;
                }
            }

            this.ftpSitesService.CommitChanges();
        }
    public static void CreateApplication()
    {
        // Create an offline connection, we use an empty Guid as personId
        // There is a bug to create a constructor without requiring a guid
        //// Use this only if you master application wants to do this in Offline mode
        OfflineWebApplicationConnection offlineConnection =
            new OfflineWebApplicationConnection(Guid.Empty);
        offlineConnection.Authenticate();

        // Setting up the application we want to create
        ApplicationInfo appInfo =
            new ApplicationInfo();
        appInfo.Name = "Android application";
        appInfo.AuthorizationReason =
            "Android aplication";
        appInfo.Description =
            "Just an android application";
        // get a base64 encoded logo
        appInfo.LargeLogo = new ApplicationBinaryConfiguration(
            "C:\\blah.png", "image/gif");
        // base64 encoded public key for this application
        appInfo.PublicKeys.Add(
            GetPublicKeyFromPfxOrP12("C:\\JourneyCompass.cer"));

        // You need to have PrivacyStatement + TermsOfUse or ActionUrl
        appInfo.PrivacyStatement = new ApplicationBinaryConfiguration(
        "C:\\privacy.txt", "text/plain");
        appInfo.TermsOfUse = new ApplicationBinaryConfiguration
            ("C:\\terms.txt", "text/plain");
        //actionUrl
        //appInfo.ActionUrl = new Uri("http://localhost/redirect.aspx");

        // Create and add the rules individually
        List<AuthorizationSetDefinition> rules = new List<AuthorizationSetDefinition>();
        rules.Add((AuthorizationSetDefinition)(new TypeIdSetDefinition(Height.TypeId)));
        rules.Add((AuthorizationSetDefinition)(new TypeIdSetDefinition(new Guid("a5033c9d-08cf-4204-9bd3-cb412ce39fc0"))));
        AuthorizationRule rule1 = new AuthorizationRule(
            HealthRecordItemPermissions.All,
            rules,
            null);
        // Here we are setting up the child as an offline application
        appInfo.OfflineBaseAuthorizations.Add(rule1);

        // Add more rules, if needed

        // Lets make the child app!
        Provisioner.AddApplication(offlineConnection, appInfo);
    }
 public NotificationHubAuthorizationRuleWrapper(AuthorizationRule rule)
 {
     KeyName = rule.KeyName;
     if (rule is SharedAccessAuthorizationRule)
     {
         var sharedAccessAuthorizationRule = rule as SharedAccessAuthorizationRule;
         PrimaryKey = sharedAccessAuthorizationRule.PrimaryKey;
         SecondaryKey = sharedAccessAuthorizationRule.SecondaryKey;
     }
     Manage = rule.Rights.Contains(AccessRights.Manage);
     Send = rule.Rights.Contains(AccessRights.Send);
     Listen = rule.Rights.Contains(AccessRights.Listen);
     ClaimType = rule.ClaimType;
     ClaimValue = rule.ClaimValue;
     IssuerName = rule.IssuerName;
     Revision = rule.Revision;
     CreatedTime = rule.CreatedTime;
     ModifiedTime = rule.ModifiedTime;
     AuthorizationRule = rule;
 }
        private ExtendedAuthorizationRule CreateExtendedAuthorizationRule(
            AuthorizationRule rule,
            string namespaceName)
        {
            string connectionString = string.Empty;

            if (IsActiveNamespace(namespaceName))
            {
                connectionString = GetConnectionString(namespaceName, rule.KeyName);
            }

            return new ExtendedAuthorizationRule()
            {
                Rule = rule,
                Name = rule.KeyName,
                Namespace = namespaceName,
                Permission = rule.Rights.ToList(),
                ConnectionString = connectionString
            };
        }
        public void UnlockTopicDenied()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Use the default configuration, where everything is denied
            federation.Configuration.AuthorizationRules.Clear();

            // Grant the Edit permission, which should not be enough.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Edit, 0);
            manager.WriteTopicAndNewVersion(manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                UnqualifiedTopicName topic = new UnqualifiedTopicName("TopicOne");
                provider.UnlockTopic(topic);

                Assert.Fail("A security exception should have been thrown.");
            }
        }
        public void AllTopicsAllowed()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // We should be able to get the list of topics even if we can't read some of them.
            AuthorizationRule rule = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.GenericAll),
                AuthorizationRulePolarity.Deny, AuthorizationRuleScope.Topic, SecurableAction.Read, 0);
            manager.WriteTopicAndNewVersion("DeniedTopic", rule.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                QualifiedTopicNameCollection topics = provider.AllTopics();

                Assert.AreEqual(4, topics.Count, "Checking that the right number of topics were returned.");
            }
        }
 private ExtendedAuthorizationRule CreateExtendedAuthorizationRule(
     AuthorizationRule rule,
     string namespaceName,
     string entityName,
     ServiceBusEntityType entityType)
 {
     return new ExtendedAuthorizationRule()
     {
         Rule = rule,
         Name = rule.KeyName,
         Permission = rule.Rights.ToList(),
         ConnectionString = GetConnectionString(namespaceName, entityName, entityType, rule.KeyName),
         Namespace = namespaceName,
         EntityName = entityName,
         EntityType = entityType
     };
 }
        public void HasPermissionNonexistentTopicDenied()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleEmptyNamespace, configuration);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Set it up so we only have Read
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Read, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                Assert.IsTrue(provider.HasPermission(new UnqualifiedTopicName("NoSuchTopic"),
                    TopicPermission.Read),
                    "Checking that allowing read at the namespace level grants read on nonexistent topics.");
                Assert.IsFalse(provider.HasPermission(new UnqualifiedTopicName("NoSuchTopic"),
                    TopicPermission.Edit),
                    "Checking that allowing read at the namespace level denies edit on nonexistent topics.");
            }
        }
        public void IsReadOnlyContentStoreReadWriteSecurityReadWrite()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Use the default configuration, where everything is denied
            federation.Configuration.AuthorizationRules.Clear();

            // Grant the Read permission, which should be what is needed.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Edit, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                Assert.IsFalse(provider.IsReadOnly,
                    "Checking that the store is read-write when store and security policy are read-write.");
            }
        }
        public void TopicExistsNonexistentTopic()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Use the default configuration, where everything is denied
            federation.Configuration.AuthorizationRules.Clear();

            // Deny the Read permission. Topic existence shouldn't be affected by security policy.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Deny, AuthorizationRuleScope.Topic, SecurableAction.Read, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager, "TopicOne", allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                Assert.IsFalse(provider.TopicExists(new UnqualifiedTopicName("NoSuchTopic")),
                    "Checking that TopicExists returns false even when read permission is denied.");
            }
        }
Example #44
0
 protected string GetRole(AuthorizationRule rule)
 {
     return rule.Roles.ToString();
 }
Example #45
0
 protected string GetUser(AuthorizationRule rule)
 {
     return rule.Users.ToString();
 }
        public void SetUp()
        {
            string author = "tester-joebob";
            _lm = new LinkMaker("http://bogusville");
            FederationConfiguration configuration = new FederationConfiguration();
            AuthorizationRule rule = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.GenericAll, null),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.ManageNamespace, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(rule));
            MockWikiApplication application = new MockWikiApplication(
                configuration,
                _lm,
                OutputFormat.HTML,
                new MockTimeProvider(TimeSpan.FromSeconds(1)));
            Federation = new Federation(application);

            _versions = new ArrayList();
            _storeManager = WikiTestUtilities.CreateMockStore(Federation, "FlexWiki.Base");

            WikiTestUtilities.WriteTestTopicAndNewVersion(_storeManager, "TopicOne", @"1
            2
            3
            4
            5
            6
            7
            8
            9", author);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_storeManager, "TopicOne", @"1
            2
            a
            b
            c
            3
            4
            5
            6
            7
            8
            9", author);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_storeManager, "TopicOne", @"1
            2
            a
            b
            6
            7
            8
            9", author);

            foreach (TopicChange change in _storeManager.AllChangesForTopic("TopicOne"))
            {
                _versions.Add(change.Version);
            }
        }
 private static bool IsAuthorized(AuthorizationRule rule)
 {
     SecurityProvider provider = SecurityProvider.GetInstance();
     if (rule.DenyEveryone)
         return false;
     if (rule.AllowEveryone || rule.AllowAnonymous)
         return true;
     if (provider.IsAuthenticated && rule.DenyAnonymous)
         return true;
     if (provider.IsAuthenticated && provider.IsInRoles(rule.Roles))
         return rule.Type == AuthorizationRuleType.Allow;
     return false;
 }
Example #48
0
 // add rule
 protected void AddRule(AuthorizationRule newRule)
 {
     string virtualFolderPath = FolderTree.SelectedValue;
     Configuration config = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath);
     SystemWebSectionGroup systemWeb = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
     AuthorizationSection section = (AuthorizationSection)systemWeb.Sections["authorization"];
     section.Rules.Add(newRule);
     try
     {
         config.Save();
         RuleCreationError.Visible = false;
     }
     catch (Exception ex)
     {
         RuleCreationError.Visible = true;
         RuleCreationError.Text = "<div class=\"alert\"><br />An error occurred and the rule was not added.<br /><br />Error message:<br /><br /><i>" + ex.Message + "</i></div>";
     }
 }
        public void UnlockTopicAllowed()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Use the default configuration, where everything is denied
            federation.Configuration.AuthorizationRules.Clear();

            // Grant the ManageNamespace permission, which should be what is needed.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.ManageNamespace, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                UnqualifiedTopicName topic = new UnqualifiedTopicName("TopicOne");
                provider.LockTopic(topic);
                Assert.IsFalse(provider.HasPermission(topic, TopicPermission.Edit),
                    "Checking that topic is not editable before UnlockTopic.");
                Assert.IsTrue(provider.HasPermission(topic, TopicPermission.Read),
                    "Checking that topic is readable before UnlockTopic.");
                provider.UnlockTopic(topic);
                Assert.IsTrue(provider.HasPermission(topic, TopicPermission.Edit),
                    "Checking that topic is editable after UnlockTopic.");
                Assert.IsTrue(provider.HasPermission(topic, TopicPermission.Read),
                    "Checking that topic is still readable after UnlockTopic.");
            }
        }
Example #50
0
 // authorization rules
 protected string GetAction(AuthorizationRule rule)
 {
     return rule.Action.ToString();
 }
        public void TextReaderForTopicAllowed()
        {
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Use the default configuration, where everything is denied
            federation.Configuration.AuthorizationRules.Clear();

            // Grant the Read permission, which should be enough.
            AuthorizationRule deny = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Read, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, deny.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                string contents = provider.TextReaderForTopic(new UnqualifiedTopicRevision("TopicOne")).ReadToEnd();
                Assert.AreEqual(7, contents.Length, "Checking that the right contents were returned.");
            }
        }
Example #52
0
    // create rule
    protected void CreateRule(object sender, EventArgs e)
    {
        AuthorizationRule newRule;
        if (ActionAllow.Checked)
        {
            newRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
        }
        else
        {
            newRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
        }

        if (ApplyRole.Checked && UserRoles.SelectedIndex > 0)
        {
            newRule.Roles.Add(UserRoles.Text);
            AddRule(newRule);
        }
        else if (ApplyUser.Checked && SpecifyUser.Text != String.Empty)
        {
            newRule.Users.Add(SpecifyUser.Text);
            AddRule(newRule);
        }
        else if (ApplyAllUsers.Checked)
        {
            newRule.Users.Add("*");
            AddRule(newRule);
        }
        else if (ApplyAnonUser.Checked)
        {
            newRule.Users.Add("?");
            AddRule(newRule);
        }
    }
        public void WriteTopicRegularTopicDenied()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            // Grant the Read permission, which should not be enough.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.Read, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(allow));
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports, configuration);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            using (new TestSecurityContext("someuser", "somerole"))
            {
                UnqualifiedTopicRevision topic = new UnqualifiedTopicRevision("TopicOne");
                provider.WriteTopic(topic, "New content");
                Assert.Fail("A security exception should have been thrown.");
            }
        }
        public void WriteTopicDefinitionTopicAllowed()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            // Grant the ManageNamespace permission, which should be enough.
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.ManageNamespace, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(allow));
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleTopicNoImports, configuration);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            using (new TestSecurityContext("someuser", "somerole"))
            {
                provider.WriteTopic(new UnqualifiedTopicRevision(manager.DefinitionTopicName.LocalName), "New content");
            }
        }
        public void HasPermissionDefinitionTopic()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleEmptyNamespace, configuration);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Set it up so we have Edit but not ManageNamespace
            AuthorizationRule allowEdit = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Edit, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allowEdit.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                Assert.IsFalse(provider.HasPermission(new UnqualifiedTopicName(manager.DefinitionTopicName.LocalName),
                    TopicPermission.Edit),
                    "Checking that allowing edit is not enough to grant editpermisison on the definition topic.");
            }

            // Now try it where we're granted ManageNamespace
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.ManageNamespace, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            using (new TestSecurityContext("someuser", "somerole"))
            {
                Assert.IsTrue(provider.HasPermission(new UnqualifiedTopicName(manager.DefinitionTopicName.LocalName),
                    TopicPermission.Edit),
                    "Checking that granting ManageNamespace implies ability to edit definition topic.");
            }
        }
        public void WriteNewTopicDenied()
        {
            FederationConfiguration configuration = new FederationConfiguration();
            Federation federation = WikiTestUtilities.SetupFederation("test://AuthorizationProviderTests",
              TestContentSets.SingleEmptyNamespace, configuration);
            NamespaceManager manager = WikiTestUtilities.GetNamespaceManagerBypassingSecurity(federation, "NamespaceOne");
            AuthorizationProvider provider = GetSecurityProvider(manager);

            // Set it up so we have Read
            AuthorizationRule allow = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.User, "someuser"),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Namespace, SecurableAction.Read, 0);
            WikiTestUtilities.WriteTopicAndNewVersionBypassingSecurity(manager,
                manager.DefinitionTopicName.LocalName, allow.ToString("T"), "test");

            UnqualifiedTopicRevision revision = new UnqualifiedTopicRevision("NewTopic");
            string content = "New content to be written";
            using (new TestSecurityContext("someuser", "somerole"))
            {
                provider.WriteTopic(revision, content);
            }
        }
        public void SetUp()
        {
            _lm = new LinkMaker(c_siteUrl);
            FederationConfiguration configuration = new FederationConfiguration();
            AuthorizationRule rule = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.GenericAll, null),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.ManageNamespace, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(rule));
            MockWikiApplication application = new MockWikiApplication(
                configuration,
                _lm,
                OutputFormat.HTML,
                new MockTimeProvider(TimeSpan.FromSeconds(1)));

            Federation = new Federation(application);
            Federation.WikiTalkVersion = 1;

            _namespaceManager = WikiTestUtilities.CreateMockStore(Federation, "FlexWiki");
            //_namespaceManager.Title  = "Friendly Title";

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "_ContentBaseDefinition", "Title: Friendly Title", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "HomePage", "Home is where the heart is", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BigPolicy", "This is ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BigDog", "This is ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BigAddress", "This is ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BigBox", "This is ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeOne", "inc1", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeTwo", "!inc2", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeThree", "!!inc3", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeFour", "!inc4", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeNest", @"		{{IncludeNest1}}
            {{IncludeNest2}}", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TopicWithColor", "Color: Yellow", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeNest1", "!hey there", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeNest2", "!black dog", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "IncludeNestURI", @"wiki://IncludeNest1 wiki://IncludeNest2 ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "ResourceReference", @"URI: http://www.google.com/$$$", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "FlexWiki", "flex ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "InlineTestTopic", @"aaa @@""foo""@@ zzz", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "OneMinuteWiki", "one ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TestIncludesBehaviors", "@@ProductName@@ somthing @@Now@@ then @@Now@@", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "_Underscore", "Underscore", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TopicWithBehaviorProperties", @"
            Face: {""hello"".Length}
            one
            FaceWithArg: {arg | arg.Length }
            FaceSpanningLines:{ arg |

            arg.Length

            }

            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TestTopicWithBehaviorProperties", @"
            len=@@topics.TopicWithBehaviorProperties.Face@@
            lenWith=@@topics.TopicWithBehaviorProperties.FaceWithArg(""superb"")@@
            lenSpanning=@@topics.TopicWithBehaviorProperties.FaceSpanningLines(""parsing is wonderful"")@@
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TestTopicWithBehaviorProperty",
            @"lenSpanning=@@topics.TopicWithBehaviorProperties.FaceSpanningLines(""parsing is wonderful"")@@", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TopicWithInclude", "{{TopicOneNoRead}}", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TopicOneNoRead",
            @"DenyRead: all
            PropertyOne: ValueOne
            PropertyTwo: Value Two
            PropertyOne: List, of, values", _user);

            _externals = new ExternalReferencesMap();
        }
 public void AddRule(AuthorizationRule rule);
 public void CopyTo(AuthorizationRule[] rules, int index);
Example #60
0
        public void Init()
        {
            _lm = new LinkMaker(_base);
            FederationConfiguration configuration = new FederationConfiguration();
            AuthorizationRule rule = new AuthorizationRule(new AuthorizationRuleWho(AuthorizationRuleWhoType.GenericAll, null),
                AuthorizationRulePolarity.Allow, AuthorizationRuleScope.Wiki, SecurableAction.ManageNamespace, 0);
            configuration.AuthorizationRules.Add(new WikiAuthorizationRule(rule));
            MockWikiApplication application = new MockWikiApplication(
                configuration,
                _lm,
                OutputFormat.HTML,
                new MockTimeProvider(TimeSpan.FromSeconds(1)));

            Federation = new Federation(application);
            Federation.WikiTalkVersion = 1;

            string ns = "FlexWiki";
            string ns2 = "FlexWiki2";
            _namespaceManager = WikiTestUtilities.CreateMockStore(Federation, ns);
            _namespaceManager2 = WikiTestUtilities.CreateMockStore(Federation, ns2);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "HomePage", "", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, _namespaceManager.DefinitionTopicName.LocalName, @"Import: FlexWiki2", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "QualifiedLocalPropertyRef", @"
            Color: green
            color=@@topics.QualifiedLocalPropertyRef.Color@@", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "UnqualifiedLocalPropertyRef", @"
            Color: green
            color=@@Color@@", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "QualifiedLocalMethodRef", @"
            len=@@topics.QualifiedLocalMethodRef.DirectStringLength(""hello"")@@
            DirectStringLength: { str | str.Length }
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "UnqualifiedLocalMethodRef", @"
            len=@@DirectStringLength(""hello"")@@
            DirectStringLength: { str | str.Length }
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "LocalMethodIndirection", @"
            len=@@StringLength(""hello"")@@
            StringLength: { str | Len(str) }
            Len: { str | str.Length }
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "LocalMethodIndirection2", @"
            len=@@StringLength(""hello"")@@
            StringLength: { str | Len(str) }
            Len: { s | s.Length }
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "CallerBlockLocalsShouldBeInvisible", @"
            len=@@StringLength(""hello"")@@
            StringLength: { str | Len(str) }
            Len: { s | str.Length }
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager2, "Profile", @"Color: puce", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "ReferAcrossNamespaces", @"@@topics.Profile.Color@@", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "TestChecker", @"
            Test: { FearFactor }
            Color: green", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "CallTestChecker", @"
            FearFactor: nighttime
            test=@@topics.TestChecker.Test@@
            ", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "Topic1", @"
            Function: { arg1 | topics.Topic2.FunctionTwo( { arg1 } ) }
            ", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "Topic2", @"
            FunctionTwo: { someArg | 	someArg.Value }
            ", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "Topic3", @"@@topics.Topic1.Function(100)@@", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BlockCanSeeLexicalScopeCaller", @"
            result=@@ topics.BlockCanSeeLexicalScopeCallee.BlockValue( { Color } ) @@
            Color: green", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "BlockCanSeeLexicalScopeCallee", @"
            BlockValue: {aBlock | aBlock.Value }", _user);

            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "ThisTests", @"
            topicName=@@topicName.Name@@
            namespace=@@namespace.Name@@
            nscount=@@federation.Namespaces.Count@@
            color=@@this.Color@@
            Color: red
            ", _user);
            WikiTestUtilities.WriteTestTopicAndNewVersion(_namespaceManager, "WikiTalkHomeObject", @"
            @@topics@@
            namespace=@@namespace@@
            federation=@@federation@@
            color=@@this.Color@@
            Color: red
            true = @@true@@
            empty = @@empty@@(this is empty)
            false = @@false@@
            null = @@null@@
            ", _user);
        }