Example #1
0
        public Post AddNewPost(string postContent, Topic topic, User user, out PermissionSet permissions)
        {
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                throw new ApplicationException("");
            }

            var comment = new Post
            {
                PostContent = postContent,
                User = user,
                Topic = topic,
                IpAddress = StringUtils.GetUsersIpAddress(),
                PostType = PostType.comment.ToString(),
                DateCreated = DateTime.UtcNow,
                DateEdited = DateTime.UtcNow
            };

            comment = SanitizePost(comment);

            Add(comment);

            return comment;
        }
Example #2
0
    public RadTreeNodeData[] GetNodes (RadTreeNodeData node, object context)
    {
        if (node.Attributes.ContainsKey("perm"))
        {
            int persID = int.Parse(node.Attributes["uid"].ToString());
            authority = Person.FromIdentity(persID).GetAuthority();
            PermissionSet ps = new PermissionSet(node.Attributes["perm"].ToString());
            requiredPermission = ps.permsList[0].perm;
        }


        List<RadTreeNodeData> nodes = new List<RadTreeNodeData>();
        int parentId = Organization.RootIdentity;
        int.TryParse(node.Value, out parentId);
        Organizations orgs = Organization.FromIdentity(parentId).Children;
        foreach (Organization org in orgs)
        {
            RadTreeNodeData nodeData = new RadTreeNodeData();
            nodeData.Text = org.Name;
            nodeData.Value = org.Identity.ToString();
            Organizations orgs2 = Organization.FromIdentity(org.Identity).Children;
            if (orgs2.Count > 0)
                nodeData.ExpandMode = TreeNodeExpandMode.WebService;

            SetAuthorityForNode(nodeData);

            nodes.Add(nodeData);
        }
        return nodes.ToArray();
    }
Example #3
0
        public void AddPost()
        {
            var postRepository = Substitute.For<IPostRepository>();
            var topicRepository = Substitute.For<ITopicRepository>();
            var roleService = Substitute.For<IRoleService>();
            var membershipUserPointsService = Substitute.For<IMembershipUserPointsService>();
            var settingsService = Substitute.For<ISettingsService>();
            settingsService.GetSettings().Returns(new Settings { PointsAddedPerPost = 20 });
            var localisationService = Substitute.For<ILocalizationService>();
            var postService = new PostService(membershipUserPointsService, settingsService, roleService, postRepository, topicRepository, localisationService, _api);

            var category = new Category();
            var role = new MembershipRole{RoleName = "TestRole"};

            var categoryPermissionForRoleSet = new List<CategoryPermissionForRole>
                                                   {
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionEditPosts }, IsTicked = true},
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionDenyAccess }, IsTicked = false},
                                                       new CategoryPermissionForRole { Permission = new Permission { Name = AppConstants.PermissionReadOnly  }, IsTicked = false}
                                                   };

            var permissionSet = new PermissionSet(categoryPermissionForRoleSet);
            roleService.GetPermissions(category, role).Returns(permissionSet);

            var topic = new Topic { Name = "Captain America", Category = category};
            var user = new MembershipUser {
                UserName = "SpongeBob",
                Roles = new List<MembershipRole>{role}
            };

            var newPost = postService.AddNewPost("A test post", topic, user, out permissionSet);

            Assert.AreEqual(newPost.User, user);
            Assert.AreEqual(newPost.Topic, topic);
        }
Example #4
0
        public PEXInspector(string path)
        {
            _mode = PEXMode.File;
            _filePath = path;

            _permissions = new PermissionSet();
        }
Example #5
0
		public override PolicyStatement Resolve (Evidence evidence)
		{
			if (null == evidence)
				throw new ArgumentNullException("evidence");

			if (!MembershipCondition.Check (evidence))
				return null;

			PermissionSet ps = null;
			if (this.PolicyStatement == null)
				ps = new PermissionSet (PermissionState.None);
			else
				ps = this.PolicyStatement.PermissionSet.Copy ();

			if (this.Children.Count > 0) {
				foreach (CodeGroup child_cg in this.Children) {
					PolicyStatement child_pst = child_cg.Resolve (evidence);
					if (child_pst != null) {
						ps = ps.Union (child_pst.PermissionSet);
					}
				}
			}

			PolicyStatement pst = null;
			if (this.PolicyStatement != null)
				pst = this.PolicyStatement.Copy ();
			else
				pst = PolicyStatement.Empty ();
			pst.PermissionSet = ps;
			return pst;
		}
Example #6
0
    public static void Main()
    {
        var CreateSomeFile = CSScript.LoadMethod(
                        @"using System.IO;
                          public static void Test()
                          {
                              try
                              {
                                  using (var f = File.Open(""somefile.txt"", FileMode.OpenOrCreate))
                                    Console.WriteLine(""File.Open: success"");
                               }
                               catch (Exception e)
                               {
                                   Console.WriteLine(e.GetType().ToString() + "": "" + e.Message);
                               }
                          }")
                         .GetStaticMethod();

        var permissionSet = new PermissionSet(PermissionState.None);
        permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

        CreateSomeFile(); //call will secceed as as the set of permisions is a default permissions set for this assembly

        Sandbox.With(SecurityPermissionFlag.Execution) //call will fail as the set of permissions is insufficient
               .Execute(()=>CreateSomeFile());

        CreateSomeFile(); //call will secceed as as the set of permisions set back to default

        //this is a logical equivalent of Sandbox.With.Execute syntactic sugar
        ExecuteInSandbox(permissionSet,               //call will fail as the set of permissions is insufficient
                        ()=>CreateSomeFile());

        CreateSomeFile(); //call will secceed as as the set of permisions set back to default
    }
Example #7
0
    static void Main(String[] args) {
        if (args.Length < 2) {
            Console.WriteLine("Usage: sandbox <directory> <assembly> [allowed_files ...]");
            return;
        }

        AppDomainSetup adSetup = new AppDomainSetup();
        adSetup.ApplicationBase = Path.GetFullPath(args[0]);

        PermissionSet permSet = new PermissionSet(PermissionState.None);
        permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
        permSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
        permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.GetFullPath(args[1])));

        for (int i = 2; i < args.Length; ++i)
            permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, args[i]));

        StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();

        AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);
        ObjectHandle handle = Activator.CreateInstanceFrom(
            newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
            typeof(Sandboxer).FullName
        );
        Sandboxer newDomainInstance = (Sandboxer) handle.Unwrap();

        Environment.Exit(newDomainInstance.ExecuteUntrustedCode(Path.GetFullPath(args[1])));
    }
Example #8
0
        public JintEngine(Options options)
        {
            visitor = new ExecutionVisitor(options);
            AllowClr = true;
            permissionSet = new PermissionSet(PermissionState.None);
            MaxRecursions = 400;

            JsObject global = visitor.Global as JsObject;

            global["ToBoolean"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Boolean>(Convert.ToBoolean));
            global["ToByte"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Byte>(Convert.ToByte));
            global["ToChar"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Char>(Convert.ToChar));
            global["ToDateTime"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, DateTime>(Convert.ToDateTime));
            global["ToDecimal"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Decimal>(Convert.ToDecimal));
            global["ToDouble"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Double>(Convert.ToDouble));
            global["ToInt16"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Int16>(Convert.ToInt16));
            global["ToInt32"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Int32>(Convert.ToInt32));
            global["ToInt64"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Int64>(Convert.ToInt64));
            global["ToSByte"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, SByte>(Convert.ToSByte));
            global["ToSingle"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, Single>(Convert.ToSingle));
            global["ToString"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, String>(Convert.ToString));
            global["ToUInt16"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, UInt16>(Convert.ToUInt16));
            global["ToUInt32"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, UInt32>(Convert.ToUInt32));
            global["ToUInt64"] = visitor.Global.FunctionClass.New(new Delegates.Func<object, UInt64>(Convert.ToUInt64));

            BreakPoints = new List<BreakPoint>();
        }
Example #9
0
	static void Save (string filename, PermissionSet ps)
	{
		using (StreamWriter sw = new StreamWriter (filename)) {
			sw.WriteLine (ps.ToXml ().ToString ());
			sw.Close ();
		}
	}
Example #10
0
    protected void Page_Load (object sender, EventArgs e)
    {
        ((MasterV4Base)this.Master).CurrentPageAllowed = true;

        AdminPermsMainGridTable t = new AdminPermsMainGridTable();

        t.LoadTable(MainTab);

        string innerContent = t[0, t.firstcol].Cell.InnerHtml;



        foreach (RoleType role in Enum.GetValues(typeof(RoleType)))
        {
                t.AddRole(role);
        }

        t[0, t.firstcol].Cell.InnerHtml = innerContent;

        foreach (Permission perm in Enum.GetValues(typeof(Permission)))
        {
            if (perm != Permission.Undefined)
                t.AddPermission(perm);
        }
        Person viewingPerson = Person.FromIdentity(Int32.Parse(HttpContext.Current.User.Identity.Name));
        Authority authority = viewingPerson.GetAuthority();
        PermissionSet EditPerms = new PermissionSet(Permission.CanEditPermissions);

        bool hasPermission = authority.HasPermission(EditPerms,Authorization.Flag.Default );
        hasPermission |= authority.HasRoleType(RoleType.SystemAdmin);

        HttpContext.Current.Session["AllowedToEditPermissions"] = hasPermission;

        BasicPermission[] loadedPermissions = Activizr.Database.PirateDb.GetDatabase().GetPermissionsTable();
        foreach (RoleType role in Enum.GetValues(typeof(RoleType)))
        {
                foreach (Permission perm in Enum.GetValues(typeof(Permission)))
                {
                    if (perm != Permission.Undefined)
                        t.AddResult(role, perm, false, hasPermission);
                }
        }

        foreach (BasicPermission bp in loadedPermissions)
        {

            t.AddResult(bp.RoleType, bp.PermissionType, true, hasPermission);
        }

        for (int c = t.firstcol + 1; c < t.Columns.Count; ++c)
        {
            if (t.Columns[c - 1][1].Cell.InnerText.Trim() == t.Columns[c][1].Cell.InnerText.Trim())
                t.Columns[c - 1][1].JoinCell(CellJoinDirection.RIGHT);

            t.Columns[c - 1][0].JoinCell(CellJoinDirection.RIGHT);
        }


        t.GetHTMLTable(ref MainTab, true);
    }
Example #11
0
 public static ViewPostViewModel MapPostViewModel(PermissionSet permissions, 
                                                     Post post, Member currentMember, 
                                                         DialogueSettings settings, Topic topic,
                                                             List<Vote> allPostVotes, List<Favourite> favourites, bool showTopicLinks = false)
 {
     var postViewModel = new ViewPostViewModel
     {
         Permissions = permissions,
         Post = post,
         User = currentMember,
         ParentTopic = topic,
         Votes = allPostVotes.Where(x => x.Post.Id == post.Id).ToList(),
         LoggedOnMemberId = currentMember != null ? currentMember.Id : 0,
         AllowedToVote = (currentMember != null && currentMember.Id != post.MemberId &&
                          currentMember.TotalPoints > settings.AmountOfPointsBeforeAUserCanVote),
         PostCount = post.Member.PostCount,
         IsAdminOrMod = HttpContext.Current.User.IsInRole(AppConstants.AdminRoleName) || permissions[AppConstants.PermissionModerate].IsTicked,
         HasFavourited = favourites.Any(x => x.PostId == post.Id),
         IsTopicStarter = post.IsTopicStarter,
         ShowTopicLinks = showTopicLinks
     };
     postViewModel.UpVotes = postViewModel.Votes.Count(x => x.Amount > 0);
     postViewModel.DownVotes = postViewModel.Votes.Count(x => x.Amount < 0);
     return postViewModel;
 }
Example #12
0
		public PolicyStatement (PermissionSet permSet, PolicyStatementAttribute attributes) 
		{
			if (permSet != null) {
				this.perms = permSet.Copy ();
				this.perms.SetReadOnly (true);
			}
			this.attrs = attributes;
		}
Example #13
0
 public PermissionSet AddLevel(PermissionSet lowerLevel)
 {
     return new PermissionSet(
         accountNegative: lowerLevel.AccountNegative == Access.Unset ? AccountNegative : lowerLevel.AccountNegative,
         accountSpend: lowerLevel.AccountSpend == Access.Unset ? AccountSpend : lowerLevel.AccountSpend,
         accountModify: lowerLevel.AccountModify == Access.Unset ? AccountModify : lowerLevel.AccountModify,
         dataModify: lowerLevel.DataModify == Access.Unset ? DataModify : lowerLevel.DataModify);
 }
Example #14
0
 public PermissionSet Add(PermissionSet added)
 {
     return new PermissionSet(
         accountNegative: Or(AccountNegative, added.AccountNegative),
         accountSpend: Or(AccountSpend, added.AccountSpend),
         accountModify: Or(AccountModify, added.AccountModify),
         dataModify: Or(DataModify, added.DataModify));
 }
	// Constructor
	public PermissionRequestEvidence(PermissionSet request,
									 PermissionSet optional,
									 PermissionSet denied)
			{
				this.request = request;
				this.optional = optional;
				this.denied = denied;
			}
 private void AssertPermissionSet(Access expected, PermissionSet permissions)
 {
     Assert.Equal(expected, permissions.AccountModify);
     Assert.Equal(expected, permissions.AccountNegative);
     Assert.Equal(expected, permissions.AccountSpend);
     Assert.Equal(expected, permissions.AccountCreate);
     Assert.Equal(expected, permissions.DataModify);
 }
Example #17
0
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
                               {
                                   PostContent = postContent,
                                   User = user,
                                   Topic = topic,
                                   IpAddress = StringUtils.GetUsersIpAddress(),
                                   DateCreated = DateTime.UtcNow,
                                   DateEdited = DateTime.UtcNow
                               };

            // Sort the search field out

            var category = topic.Category;
            if (category.ModeratePosts == true)
            {
                newPost.Pending = true;
            }

            var e = new PostMadeEventArgs { Post = newPost };
            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                                                     {
                                                         Points = _settingsService.GetSettings().PointsAddedPerPost,
                                                         User = user,
                                                         PointsFor = PointsFor.Post,
                                                         PointsForId = newPost.Id
                                                     });

                // add the last post to the topic
                topic.LastPost = newPost;

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost });

                return newPost;
            }

            return newPost;
        }
Example #18
0
    public static void Main()
    {
        //创建文件 IO 读取权限
        FileIOPermission FileIOReadPermission = new FileIOPermission(PermissionState.None);
        FileIOReadPermission.AllLocalFiles = FileIOPermissionAccess.Read;

        //创建基本权限集
        PermissionSet BasePermissionSet = new PermissionSet(PermissionState.None); // PermissionState.Unrestricted 用于完全信任
        BasePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

        PermissionSet grantset = BasePermissionSet.Copy();
        grantset.AddPermission(FileIOReadPermission);

        //编写示例源文件以读取
        System.IO.File.WriteAllText("TEST.TXT", "File Content");

        //-------- 完全信任地调用方法 --------
        try
        {
            Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName);
            ReadFileMethod();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        //-------- 创建具有文件 IO 读取权限的 AppDomain --------
        AppDomain sandbox = AppDomain.CreateDomain("Sandboxed AppDomain With FileIO.Read permission", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, grantset, null);
        try
        {
            Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName);
            sandbox.DoCallBack(new CrossAppDomainDelegate(ReadFileMethod));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        //-------- 创建没有文件 IO 读取权限的 AppDomain --------
        //应当引发安全异常
        PermissionSet grantset2 = BasePermissionSet.Copy();
        AppDomain sandbox2 = AppDomain.CreateDomain("Sandboxed AppDomain Without FileIO.Read permission", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, grantset2, null);
        try
        {
            Console.WriteLine("App Domain Name: " + AppDomain.CurrentDomain.FriendlyName);
            sandbox2.DoCallBack(new CrossAppDomainDelegate(ReadFileMethod));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        Console.WriteLine("");
        Console.WriteLine("Press any key to end.");
        Console.ReadKey();
    }
		public PermissionRequestEvidence (PermissionSet request, PermissionSet optional, PermissionSet denied) 
		{
			if (request != null)
				this.requested = new PermissionSet (request);
			if (optional != null)
				this.optional = new PermissionSet (optional);
			if (denied != null)
				this.denied = new PermissionSet (denied);
		}
Example #20
0
 public static void PermissionRequestEvidenceCallMethods()
 {
     PermissionSet ps = new PermissionSet(new PermissionState());
     PermissionRequestEvidence pre = new PermissionRequestEvidence(ps, ps, ps);
     PermissionRequestEvidence obj = pre.Copy();
     string str = ps.ToString();
     SecurityElement se = new SecurityElement("");
     ps.FromXml(se);
     se = ps.ToXml();
 }
Example #21
0
        // Sets up the default grant set for all constructors. Extracted to avoid the cost of
        // IEnumerable virtual dispatches on startup when there are no fullTrustAssemblies (CoreCLR)
        private void InitDefaultGrantSet(PermissionSet defaultGrantSet) {
            if (defaultGrantSet == null) {
                throw new ArgumentNullException(nameof(defaultGrantSet));
            }

            // Creating a PolicyStatement copies the incoming permission set, so we don't have to worry
            // about the PermissionSet parameter changing underneath us after we've calculated the
            // permisison flags in the DefaultGrantSet setter.
            DefaultGrantSet = new PolicyStatement(defaultGrantSet);
        }
Example #22
0
        public PEXInspector(string host, int port, string user, string pass, string db)
        {
            _mode = PEXMode.MySQL;
            _host = host;
            _port = port;
            _user = user;
            _pass = pass;
            _db = db;

            _permissions = new PermissionSet();
        }
Example #23
0
   private static void SecurityExample() {
      ProxyType highSecurityObject = new ProxyType();
      highSecurityObject.AttemptAccess("High");   // Works OK

      PermissionSet grantSet = new PermissionSet(PermissionState.None);
      grantSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
      AppDomain lowSecurityAppDomain = AppDomain.CreateDomain("LowSecurity", null, new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }, grantSet, null);
      ProxyType lowSecurityObject = (ProxyType)lowSecurityAppDomain.CreateInstanceAndUnwrap(typeof(ProxyType).Assembly.ToString(), typeof(ProxyType).FullName);
      lowSecurityObject.DoSomething(highSecurityObject);
      Console.ReadLine();
   }
Example #24
0
 /// Run the code with less permissions than usual
 /// (so it can't read/write to files).
 /// This is a false sense of security... the program can still run unmanaged
 /// code. But shhh don't worry about that.
 static int Main(string[] args)
 {
     String path = args[0];
     PermissionSet ps = new PermissionSet(PermissionState.None);
     AppDomainSetup setup = new AppDomainSetup();
     Evidence ev = new Evidence();
     AppDomain sandbox = AppDomain.CreateDomain("Sandbox",
         ev,
         setup,
         ps);
     sandbox.ExecuteAssembly(path);
     return 0;
 }
Example #25
0
 public static void AddPermissions(SPListItem item, PermissionSet set)
 {
     foreach (Permission p in set)
     {
         if (p.PermissionType == PermissionType.Edit)
         {
             AddManageListItemPermission(item, p.Identity);
            // AddModifyFilePermission(item, p.Identity);
         }
         else
             AddViewListItemPermission(item, p.Identity);
     }
 }
Example #26
0
        /// <summary>
        /// Add a new post
        /// </summary>
        /// <param name="postContent"> </param>
        /// <param name="topic"> </param>
        /// <param name="user"></param>
        /// <param name="permissions"> </param>
        /// <returns>True if post added</returns>
        public Post AddNewPost(string postContent, Topic topic, MembershipUser user, out PermissionSet permissions)
        {
            // Get the permissions for the category that this topic is in
            permissions = _roleService.GetPermissions(topic.Category, UsersRole(user));

            // Check this users role has permission to create a post
            if (permissions[AppConstants.PermissionDenyAccess].IsTicked || permissions[AppConstants.PermissionReadOnly].IsTicked)
            {
                // Throw exception so Ajax caller picks it up
                throw new ApplicationException(_localizationService.GetResourceString("Errors.NoPermission"));
            }

            // Has permission so create the post
            var newPost = new Post
                               {
                                   PostContent = postContent,
                                   User = user,
                                   Topic = topic,
                                   IpAddress = StringUtils.GetUsersIpAddress()
                               };

            newPost = SanitizePost(newPost);

            var e = new PostMadeEventArgs { Post = newPost, Api = _api };
            EventManager.Instance.FireBeforePostMade(this, e);

            if (!e.Cancel)
            {
                // create the post
                Add(newPost);

                // Update the users points score and post count for posting
                _membershipUserPointsService.Add(new MembershipUserPoints
                                                     {
                                                         Points = _settingsService.GetSettings().PointsAddedPerPost,
                                                         User = user
                                                     });

                // add the last post to the topic
                topic.LastPost = newPost;

                // Removed as its updated via the commit
                //_topicRepository.Update(topic);

                EventManager.Instance.FireAfterPostMade(this, new PostMadeEventArgs { Post = newPost, Api = _api });

                return newPost;
            }

            return newPost;
        }
Example #27
0
 /// <summary>
 /// Maps the posts for a specific topic
 /// </summary>
 /// <param name="posts"></param>
 /// <param name="votes"></param>
 /// <param name="permission"></param>
 /// <param name="topic"></param>
 /// <param name="loggedOnUser"></param>
 /// <param name="settings"></param>
 /// <param name="favourites"></param>
 /// <returns></returns>
 public static List<PostViewModel> CreatePostViewModels(IEnumerable<Post> posts, List<Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List<Favourite> favourites)
 {
     var viewModels = new List<PostViewModel>();
     var groupedVotes = votes.ToLookup(x => x.Post.Id);
     var groupedFavourites = favourites.ToLookup(x => x.Post.Id);
     foreach (var post in posts)
     {
         var id = post.Id;
         var postVotes = (groupedVotes.Contains(id) ? groupedVotes[id].ToList() : new List<Vote>());
         var postFavs = (groupedFavourites.Contains(id) ? groupedFavourites[id].ToList() : new List<Favourite>());
         viewModels.Add(CreatePostViewModel(post, postVotes, permission, topic, loggedOnUser, settings, postFavs));
     }
     return viewModels;
 }
Example #28
0
    public static void Main(string[] args)
    {
        try
        {
            // Create a new, empty permission set so we don't mistakenly grant some permission we don't want
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);
            // Set the permissions that you will allow, in this case we only want to allow execution of code
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            // Make sure we have the permissions currently
            permissionSet.Demand();

            // Create the security policy level for this application domain
            PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel();
            // Give the policy level's root code group a new policy statement based on the new permission set.
            policyLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permissionSet);

            CSScript.GlobalSettings.AddSearchDir(Environment.CurrentDirectory);

            File.Copy("Danger.cs", "Danger1.cs", true);
            var script = new AsmHelper(CSScript.Load("Danger.cs"));

            // Update the application domain's policy now
            AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel);

            var script1 = new AsmHelper(CSScript.Load("Danger1.cs"));

            Console.WriteLine();
            Console.WriteLine("Access local file from host application assembly...");
            using (FileStream f = File.Open("somefile.txt", FileMode.OpenOrCreate)) //OK because executing assembly was loaded before the new policy set
                Console.WriteLine("  Ok");
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (before security policy set)...");
            script.Invoke("*.SayHello"); //OK because executing assembly was loaded before the new policy set
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (after security policy set)...\n");
            script1.Invoke("*.SayHello"); //ERROR because executing assembly was loaded after the new policy set

            Console.WriteLine("The end...");
        }
        catch (Exception e)
        {
            Console.WriteLine();
            Console.WriteLine(e.Message);
            Console.WriteLine();
        }
    }
Example #29
0
 static void ExecuteInSandbox(PermissionSet permissionSet, Action action)
 {
     permissionSet.PermitOnly();
     try
     {
         action();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.GetType().ToString() + ": " + e.Message);
     }
     finally
     {
         CodeAccessPermission.RevertPermitOnly();
     }
 }
#pragma warning restore 169
    
        public PermissionRequestEvidence(PermissionSet request, PermissionSet optional, PermissionSet denied)
        {
            if (request == null)
                m_request = null;
            else
                m_request = request.Copy();
                
            if (optional == null)
                m_optional = null;
            else
                m_optional = optional.Copy();
                
            if (denied == null)
                m_denied = null;
            else
                m_denied = denied.Copy();
        }