Esempio n. 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;
        }
Esempio n. 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();
    }
Esempio n. 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 = "******",
                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);
        }
Esempio n. 4
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;
 }
Esempio n. 5
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);
    }
Esempio n. 6
0
        public PEXInspector(string path)
        {
            _mode = PEXMode.File;
            _filePath = path;

            _permissions = new PermissionSet();
        }
Esempio n. 7
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>();
        }
Esempio n. 8
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
    }
Esempio n. 9
0
	static void Save (string filename, PermissionSet ps)
	{
		using (StreamWriter sw = new StreamWriter (filename)) {
			sw.WriteLine (ps.ToXml ().ToString ());
			sw.Close ();
		}
	}
Esempio n. 10
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;
		}
Esempio n. 11
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])));
    }
Esempio n. 12
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));
 }
Esempio n. 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);
 }
	// 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);
 }
Esempio n. 16
0
		public PolicyStatement (PermissionSet permSet, PolicyStatementAttribute attributes) 
		{
			if (permSet != null) {
				this.perms = permSet.Copy ();
				this.perms.SetReadOnly (true);
			}
			this.attrs = attributes;
		}
Esempio n. 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;
        }
Esempio n. 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();
    }
Esempio n. 19
0
		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);
		}
Esempio n. 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();
 }
Esempio n. 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);
        }
Esempio n. 22
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();
   }
Esempio n. 23
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();
        }
Esempio n. 24
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);
     }
 }
Esempio n. 25
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;
 }
Esempio n. 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;
        }
Esempio n. 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;
 }
Esempio n. 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();
        }
    }
Esempio n. 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();
        }
 public static void SetPermissionsSet(this AppDomain appDomain, PermissionSet permissions)
 {
     //PolicyLevel policy = PolicyLevel.CreateAppDomainLevel();
     //policy.RootCodeGroup.PolicyStatement = new PolicyStatement(permissions);
     //appDomain.SetAppDomainPolicy(policy);
 }
Esempio n. 32
0
        public static PostViewModel CreatePostViewModel(Post post, List <Vote> votes, PermissionSet permission, Topic topic, MembershipUser loggedOnUser, Settings settings, List <Favourite> favourites)
        {
            var allowedToVote = (loggedOnUser != null && loggedOnUser.Id != post.User.Id);

            if (allowedToVote && settings.EnablePoints)
            {
                // We need to check if points are enabled that they have enough points to vote
                allowedToVote = loggedOnUser.TotalPoints >= settings.PointsAllowedToVoteAmount;
            }

            // Remove votes where no VotedBy has been recorded
            votes.RemoveAll(x => x.VotedByMembershipUser == null);

            var hasVotedUp    = false;
            var hasVotedDown  = false;
            var hasFavourited = false;

            if (loggedOnUser != null && loggedOnUser.Id != post.User.Id)
            {
                hasFavourited = favourites.Any(x => x.Member.Id == loggedOnUser.Id);
                hasVotedUp    = votes.Count(x => x.Amount > 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
                hasVotedDown  = votes.Count(x => x.Amount < 0 && x.VotedByMembershipUser.Id == loggedOnUser.Id) > 0;
            }

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-AppConstants.TimeSpanInMinutesToShowMembers);

            return(new PostViewModel
            {
                Permissions = permission,
                Votes = votes,
                Post = post,
                ParentTopic = topic,
                AllowedToVote = allowedToVote,
                MemberHasFavourited = hasFavourited,
                Favourites = favourites,
                PermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", post.Id),
                MemberIsOnline = post.User.LastActivityDate > date,
                HasVotedDown = hasVotedDown,
                HasVotedUp = hasVotedUp
            });
        }
Esempio n. 33
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);
        }
Esempio n. 34
0
        private static EraInfo[] GetErasFromRegistry()
        {
            int newSize = 0;

            EraInfo[] array = (EraInfo[])null;
            try
            {
                PermissionSet      permissionSet      = new PermissionSet(PermissionState.None);
                RegistryPermission registryPermission = new RegistryPermission(RegistryPermissionAccess.Read, "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Nls\\Calendars\\Japanese\\Eras");
                permissionSet.AddPermission((IPermission)registryPermission);
                permissionSet.Assert();
                RegistryKey registryKey = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey("System\\CurrentControlSet\\Control\\Nls\\Calendars\\Japanese\\Eras", false);
                if (registryKey == null)
                {
                    return((EraInfo[])null);
                }
                string[] valueNames = registryKey.GetValueNames();
                if (valueNames != null)
                {
                    if (valueNames.Length != 0)
                    {
                        array = new EraInfo[valueNames.Length];
                        for (int index = 0; index < valueNames.Length; ++index)
                        {
                            EraInfo eraFromValue = JapaneseCalendar.GetEraFromValue(valueNames[index], registryKey.GetValue(valueNames[index]).ToString());
                            if (eraFromValue != null)
                            {
                                array[newSize] = eraFromValue;
                                ++newSize;
                            }
                        }
                    }
                }
            }
            catch (SecurityException ex)
            {
                return((EraInfo[])null);
            }
            catch (IOException ex)
            {
                return((EraInfo[])null);
            }
            catch (UnauthorizedAccessException ex)
            {
                return((EraInfo[])null);
            }
            if (newSize < 4)
            {
                return((EraInfo[])null);
            }
            Array.Resize <EraInfo>(ref array, newSize);
            Array.Sort <EraInfo>(array, new Comparison <EraInfo>(JapaneseCalendar.CompareEraRanges));
            for (int index = 0; index < array.Length; ++index)
            {
                array[index].era = array.Length - index;
                if (index == 0)
                {
                    array[0].maxEraYear = 9999 - array[0].yearOffset;
                }
                else
                {
                    array[index].maxEraYear = array[index - 1].yearOffset + 1 - array[index].yearOffset;
                }
            }
            return(array);
        }
Esempio n. 35
0
 /// <summary>
 /// Generates a permission set by computed the zone default permission set and adding any included permissions.
 /// </summary>
 /// <param name="targetZone">Specifies a zone default permission set, which is obtained from machine policy. Valid values are "Internet", "LocalIntranet", or "Custom". If "Custom" is specified, the generated permission set is based only on the includedPermissionSet parameter.</param>
 /// <param name="includedPermissionSet">A PermissionSet object containing the set of permissions to be explicitly included in the generated permission set. Permissions specified in this parameter will be included verbatim in the generated permission set, regardless of targetZone parameter.</param>
 /// <param name="excludedPermissions">This property is no longer used.</param>
 /// <returns>The generated permission set.</returns>
 public static PermissionSet ComputeZonePermissionSet(string targetZone, PermissionSet includedPermissionSet, string[] excludedPermissions)
 {
     return(ComputeZonePermissionSetHelper(targetZone, includedPermissionSet, null, string.Empty));
 }
Esempio n. 36
0
        /// <summary>Initializes a new instance of the <see cref="RazorTemplater" /> class.</summary>
        /// <param name="templateAssemblyPath">The template assembly path. This is the path where the generated templates are stored/cached.
        /// If shadow copy is enabled this path will be ignored and the shadow copy path will be used.</param>
        /// <param name="renderTimeout">The render timeout. This is the time in ms a template is allowed to render itself.</param>
        /// <param name="templateNamespace">The template namespace.</param>
        /// <param name="allowedDirectories">The directories the templates are allowed to read from.</param>
        /// <param name="baseType">Type of the template base class. Defaults to <see cref="TemplateBase" />.</param>
        /// <param name="defaultNamespaces">The default namespaces. Defaults to "System", "System.Collections.Generic", "System.Linq" and "System.Text".</param>
        /// <param name="forbiddenTypes">The forbidden types (FQDN). Defaults to "Task", "Thread", "System.Activator" and "System.Reflection.Assembly".</param>
        /// <param name="language">The language. Defaults to C#.</param>
        /// <param name="sponsor">The sponsor to keep the object alive.</param>
        /// <param name="persistTemplates">If set to <c>true</c> the generated templates are persisted over multiple application runs. Otherwise they are deleted when disposing.</param>
        public RazorTemplater(string templateAssemblyPath, int renderTimeout = 5000, string templateNamespace = "IsolatedRazor.RazorTemplate", List <string> allowedDirectories = null,
                              Type baseType = null, List <string> defaultNamespaces = null, List <string> forbiddenTypes = null, RazorCodeLanguage language = null, ClientSponsor sponsor = null, bool persistTemplates = false)
        {
            RenderTimeout          = renderTimeout;
            this.templateNamespace = templateNamespace;
            this.persistTemplates  = persistTemplates;
            DefaultNamespaces      = defaultNamespaces ?? new List <string>()
            {
                "System", "System.Collections.Generic", "System.Net", "System.Linq", "System.Text", "IsolatedRazor"
            };
            ForbiddenTypes = forbiddenTypes ?? new List <string>()
            {
                "System.Threading.Tasks.Task", "System.Threading.Tasks.Task`1", "System.Threading.Thread", "System.Activator", "System.Reflection.Assembly"
            };
            clientSponsor = sponsor ?? new ClientSponsor(TimeSpan.FromMinutes(1));

            defaultBaseClass = (baseType ?? typeof(TemplateBase)).FullName;
            var host = new RazorEngineHost(language ?? new CSharpRazorCodeLanguage())
            {
                DefaultNamespace = templateNamespace
            };

            DefaultNamespaces.ForEach(n => host.NamespaceImports.Add(n));
            engine   = new RazorTemplateEngine(host);
            provider = host.CodeLanguage.LanguageName == "vb" ?
                       (CodeDomProvider) new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider() :
                       new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            adSetup = new AppDomainSetup();
            if (AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles == "true")
            {
                isShadowCopied = true;
                templatePath   = Path.Combine(AppDomain.CurrentDomain.SetupInformation.CachePath, AppDomain.CurrentDomain.SetupInformation.ApplicationName);

                var shadowCopyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (shadowCopyDir.Contains("assembly"))
                {
                    shadowCopyDir = shadowCopyDir.Substring(0, shadowCopyDir.LastIndexOf("assembly"));
                }

                var privatePaths = new List <string>();
                foreach (var assemblyLocation in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.Location.StartsWith(shadowCopyDir)).Select(a => a.Location))
                {
                    privatePaths.Add(Path.GetDirectoryName(assemblyLocation));
                }

                adSetup.ApplicationBase = shadowCopyDir;
                adSetup.PrivateBinPath  = String.Join(";", privatePaths);
            }
            else
            {
                isShadowCopied          = false;
                templatePath            = templateAssemblyPath;
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                adSetup.PrivateBinPath  = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            }

            var resolver = new DefaultAssemblyResolver();

            resolver.AddSearchDirectory(Path.GetDirectoryName(adSetup.ApplicationBase));
            readerParameters = new ReaderParameters()
            {
                AssemblyResolver = resolver
            };

            if (templateCache == null)
            {
                var path = Path.Combine(templatePath, TEMPLATE_CACHE_FILE);
                if (persistTemplates && File.Exists(path))
                {
                    using (var filestream = File.Open(path, FileMode.Open))
                    {
                        var formatter = new BinaryFormatter();
                        templateCache = (TemplateCache)formatter.Deserialize(filestream);
                    }
                }
                else
                {
                    templateCache = new TemplateCache();
                }
            }

            Directory.CreateDirectory(templatePath);

            permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));                              // run the code
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration));                  // remoting lifetime (sponsor)
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, templatePath));                       // read templates
            permissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));             // support dynamic

            if (allowedDirectories != null)
            {
                allowedDirectories.ForEach(dir => permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, dir)));
            }

            RecycleAppDomain();
        }
Esempio n. 37
0
 /// <inheritdoc />
 public IAppDomain CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup info, PermissionSet grantSet, params StrongName[] fullTrustAssemblies)
 {
     return(new AppDomainWrap(AppDomain.CreateDomain(friendlyName, securityInfo, info, grantSet, fullTrustAssemblies)));
 }
Esempio n. 38
0
 public PermissionSet Union(PermissionSet other)
 {
 }
Esempio n. 39
0
 public bool IsSubsetOf(PermissionSet target)
 {
 }
Esempio n. 40
0
 public void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady)
 {
     permissionSet = new PermissionSet(null);
     isHostReady   = true;
 }
Esempio n. 41
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            Console.InputEncoding  = Encoding.UTF8;

            string pathToUntrusted   = args[0].Replace("|_|", " ");
            string untrustedAssembly = args[1];
            string entryPointString  = args[2];

            string[] parts       = entryPointString.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            string   name_space  = parts[0];
            string   class_name  = parts[1];
            string   method_name = parts[2];

            //Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder
            //other than the one in which the sandboxer resides.
            AppDomainSetup adSetup = new AppDomainSetup();

            adSetup.ApplicationBase = Path.GetFullPath(pathToUntrusted);

            //Setting the permissions for the AppDomain. We give the permission to execute and to
            //read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            permSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlThread));
            permSet.AddPermission(new NetworkInformationPermission(PermissionState.Unrestricted));
            permSet.AddPermission(new WebPermission(PermissionState.Unrestricted));

            //if (untrustedAssembly.StartsWith("fsharp_"))
            //{
            //    //for F# printf to work
            //    var fileio = new FileIOPermission(PermissionState.None);
            //    fileio.AllLocalFiles = FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery;
            //    permSet.AddPermission(fileio);
            //}
            //We want the sandboxer assembly's strong name, so that we can add it to the full trust list.
            //StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();


            var a1 = typeof(System.ComponentModel.DataAnnotations.DisplayAttribute).Assembly.GetName();
            var a2 = typeof(System.ComponentModel.Composition.ImportAttribute).Assembly.GetName();
            var a3 = typeof(System.Web.HttpRequest).Assembly.GetName();
            var a4 = typeof(System.Net.Http.HttpClient).Assembly.GetName();
            var a5 = typeof(System.Drawing.Image).Assembly.GetName();
            var a6 = typeof(Newtonsoft.Json.JsonSerializer).Assembly.GetName();


            adSetup.PartialTrustVisibleAssemblies = new string[]
            {
                string.Format("{0}, PublicKey={1}", a1.Name, ByteArrayToString(a1.GetPublicKey()).ToUpper()),
                string.Format("{0}, PublicKey={1}", a2.Name, ByteArrayToString(a2.GetPublicKey()).ToUpper()),
                string.Format("{0}, PublicKey={1}", a3.Name, ByteArrayToString(a3.GetPublicKey()).ToUpper()),
                string.Format("{0}, PublicKey={1}", a4.Name, ByteArrayToString(a4.GetPublicKey()).ToUpper()),
                string.Format("{0}, PublicKey={1}", a5.Name, ByteArrayToString(a5.GetPublicKey()).ToUpper()),
                string.Format("{0}, PublicKey={1}", a6.Name, ByteArrayToString(a6.GetPublicKey()).ToUpper()),
            };

            //Now we have everything we need to create the AppDomain, so let's create it.
            AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, /*fullTrustAssembly*/ null);

            //Use CreateInstanceFrom to load an instance of the Sandboxer class into the
            //new AppDomain.
            ObjectHandle handle = Activator.CreateInstanceFrom(
                newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
                typeof(Sandboxer).FullName
                );
            //Unwrap the new domain instance into a reference in this domain and use it to execute the
            //untrusted code.
            Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

            Job    job    = new Job(newDomainInstance, untrustedAssembly, name_space, class_name, method_name, parameters);
            Thread thread = new Thread(new ThreadStart(job.DoJob));

            thread.Start();
            thread.Join(10000);
            if (thread.ThreadState != ThreadState.Stopped)
            {
                thread.Abort();
                Console.Error.WriteLine("Job taking too long. Aborted.");
            }
            AppDomain.Unload(newDomain);
        }
Esempio n. 42
0
 public static string[] PermissionSetToIdentityList(PermissionSet permissionSet)
 {
     throw new NotImplementedException();
 }
Esempio n. 43
0
 public static PermissionSet ComputeZonePermissionSet(string targetZone,
                                                      PermissionSet includedPermissionSet,
                                                      string[] excludedPermissions)
 {
     throw new NotImplementedException();
 }
Esempio n. 44
0
        private AppDto CreateLinks(ApiController controller, PermissionSet permissions)
        {
            var values = new { app = Name };

            AddGetLink("ping", controller.Url <PingController>(x => nameof(x.GetAppPing), values));

            if (controller.HasPermission(AllPermissions.AppDelete, Name, permissions: permissions))
            {
                AddDeleteLink("delete", controller.Url <AppsController>(x => nameof(x.DeleteApp), values));
            }

            if (controller.HasPermission(AllPermissions.AppAssetsRead, Name, permissions: permissions))
            {
                AddGetLink("assets", controller.Url <AssetsController>(x => nameof(x.GetAssets), values));
            }

            if (controller.HasPermission(AllPermissions.AppBackupsRead, Name, permissions: permissions))
            {
                AddGetLink("backups", controller.Url <BackupsController>(x => nameof(x.GetBackups), values));
            }

            if (controller.HasPermission(AllPermissions.AppClientsRead, Name, permissions: permissions))
            {
                AddGetLink("clients", controller.Url <AppClientsController>(x => nameof(x.GetClients), values));
            }

            if (controller.HasPermission(AllPermissions.AppContributorsRead, Name, permissions: permissions))
            {
                AddGetLink("contributors", controller.Url <AppContributorsController>(x => nameof(x.GetContributors), values));
            }

            if (controller.HasPermission(AllPermissions.AppCommon, Name, permissions: permissions))
            {
                AddGetLink("languages", controller.Url <AppLanguagesController>(x => nameof(x.GetLanguages), values));
            }

            if (controller.HasPermission(AllPermissions.AppCommon, Name, permissions: permissions))
            {
                AddGetLink("patterns", controller.Url <AppPatternsController>(x => nameof(x.GetPatterns), values));
            }

            if (controller.HasPermission(AllPermissions.AppPlansRead, Name, permissions: permissions))
            {
                AddGetLink("plans", controller.Url <AppPlansController>(x => nameof(x.GetPlans), values));
            }

            if (controller.HasPermission(AllPermissions.AppRolesRead, Name, permissions: permissions))
            {
                AddGetLink("roles", controller.Url <AppRolesController>(x => nameof(x.GetRoles), values));
            }

            if (controller.HasPermission(AllPermissions.AppRulesRead, Name, permissions: permissions))
            {
                AddGetLink("rules", controller.Url <RulesController>(x => nameof(x.GetRules), values));
            }

            if (controller.HasPermission(AllPermissions.AppCommon, Name, permissions: permissions))
            {
                AddGetLink("schemas", controller.Url <SchemasController>(x => nameof(x.GetSchemas), values));
            }

            if (controller.HasPermission(AllPermissions.AppWorkflowsRead, Name, permissions: permissions))
            {
                AddGetLink("workflows", controller.Url <AppWorkflowsController>(x => nameof(x.GetWorkflows), values));
            }

            if (controller.HasPermission(AllPermissions.AppSchemasCreate, Name, permissions: permissions))
            {
                AddPostLink("schemas/create", controller.Url <SchemasController>(x => nameof(x.PostSchema), values));
            }

            if (controller.HasPermission(AllPermissions.AppAssetsCreate, Name, permissions: permissions))
            {
                AddPostLink("assets/create", controller.Url <SchemasController>(x => nameof(x.PostSchema), values));
            }

            return(this);
        }
Esempio n. 45
0
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///     Create an AppDomain that contains policy restricting code to execute
        ///     with only the permissions granted by a named permission set
        /// </summary>
        /// <param name="permissionSetName">name of the permission set to restrict to</param>
        /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
        /// <param name="ads"></param>
        /// <exception cref="ArgumentNullException">
        ///     if <paramref name="permissionSetName" /> is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     if <paramref name="permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///     Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///     Valid permissionSetName values are:
        ///     * FullTrust
        ///     * SkipVerification
        ///     * Execution
        ///     * Nothing
        ///     * LocalIntranet
        ///     * Internet
        ///     * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
            {
                throw new ArgumentNullException("permissionSetName");
            }
            if (permissionSetName.Length == 0)
            {
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");
            }

            // Default to all code getting everything
            PermissionSet setIntersection  = new PermissionSet(PermissionState.Unrestricted);
            AppDomain     restrictedDomain = null;

#if LINUX
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup  policyRoot  = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool foundName = false;
            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                        {
                            setIntersection = setIntersection.Intersect(levelSet);
                        }
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
            {
                setIntersection = new PermissionSet(PermissionState.None);
            }
            else
            {
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
            }

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));

            PolicyStatement permissions = new PolicyStatement(setIntersection);
            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
            appDomainLevel.RootCodeGroup = policyRoot;

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);
#else
            SecurityZone zone = SecurityZone.MyComputer;
            try
            {
                zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
            }
            catch
            {
                zone = SecurityZone.MyComputer;
            }

            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(zone));
            setIntersection = SecurityManager.GetStandardSandbox(ev);
            setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(
                new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#endif

            return(restrictedDomain);
        }
Esempio n. 46
0
        private AppDto CreateLinks(IAppEntity app, Resources resources, PermissionSet permissions, bool isContributor)
        {
            var values = new { app = Name };

            AddGetLink("ping", resources.Url <PingController>(x => nameof(x.GetAppPing), values));

            if (app.Image != null)
            {
                AddGetLink("image", resources.Url <AppsController>(x => nameof(x.GetImage), new { app = app.Name }));
            }

            if (isContributor)
            {
                AddDeleteLink("leave", resources.Url <AppContributorsController>(x => nameof(x.DeleteMyself), values));
            }

            if (resources.IsAllowed(P.AppDelete, Name, additional: permissions))
            {
                AddDeleteLink("delete", resources.Url <AppsController>(x => nameof(x.DeleteApp), values));
            }

            if (resources.IsAllowed(P.AppUpdate, Name, additional: permissions))
            {
                AddPutLink("update", resources.Url <AppsController>(x => nameof(x.UpdateApp), values));
            }

            if (resources.IsAllowed(P.AppAssetsRead, Name, additional: permissions))
            {
                AddGetLink("assets", resources.Url <AssetsController>(x => nameof(x.GetAssets), values));
            }

            if (resources.IsAllowed(P.AppBackupsRead, Name, additional: permissions))
            {
                AddGetLink("backups", resources.Url <BackupsController>(x => nameof(x.GetBackups), values));
            }

            if (resources.IsAllowed(P.AppClientsRead, Name, additional: permissions))
            {
                AddGetLink("clients", resources.Url <AppClientsController>(x => nameof(x.GetClients), values));
            }

            if (resources.IsAllowed(P.AppContributorsRead, Name, additional: permissions))
            {
                AddGetLink("contributors", resources.Url <AppContributorsController>(x => nameof(x.GetContributors), values));
            }

            if (resources.IsAllowed(P.AppLanguagesRead, Name, additional: permissions))
            {
                AddGetLink("languages", resources.Url <AppLanguagesController>(x => nameof(x.GetLanguages), values));
            }

            if (resources.IsAllowed(P.AppPatternsRead, Name, additional: permissions))
            {
                AddGetLink("patterns", resources.Url <AppPatternsController>(x => nameof(x.GetPatterns), values));
            }

            if (resources.IsAllowed(P.AppPlansRead, Name, additional: permissions))
            {
                AddGetLink("plans", resources.Url <AppPlansController>(x => nameof(x.GetPlans), values));
            }

            if (resources.IsAllowed(P.AppRolesRead, Name, additional: permissions))
            {
                AddGetLink("roles", resources.Url <AppRolesController>(x => nameof(x.GetRoles), values));
            }

            if (resources.IsAllowed(P.AppRulesRead, Name, additional: permissions))
            {
                AddGetLink("rules", resources.Url <RulesController>(x => nameof(x.GetRules), values));
            }

            if (resources.IsAllowed(P.AppSchemasRead, Name, additional: permissions))
            {
                AddGetLink("schemas", resources.Url <SchemasController>(x => nameof(x.GetSchemas), values));
            }

            if (resources.IsAllowed(P.AppWorkflowsRead, Name, additional: permissions))
            {
                AddGetLink("workflows", resources.Url <AppWorkflowsController>(x => nameof(x.GetWorkflows), values));
            }

            if (resources.IsAllowed(P.AppSchemasCreate, Name, additional: permissions))
            {
                AddPostLink("schemas/create", resources.Url <SchemasController>(x => nameof(x.PostSchema), values));
            }

            if (resources.IsAllowed(P.AppAssetsCreate, Name, additional: permissions))
            {
                AddPostLink("assets/create", resources.Url <SchemasController>(x => nameof(x.PostSchema), values));
            }

            if (resources.IsAllowed(P.AppUpdateImage, Name, additional: permissions))
            {
                AddPostLink("image/upload", resources.Url <AppsController>(x => nameof(x.UploadImage), values));

                AddDeleteLink("image/delete", resources.Url <AppsController>(x => nameof(x.DeleteImage), values));
            }

            return(this);
        }
Esempio n. 47
0
        static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set)
        {
            set = null;

            if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1)
            {
                return(false);
            }

            var security_attribute = declaration.SecurityAttributes [0];

            if (!security_attribute.AttributeType.IsTypeOf("System.Security.Permissions", "PermissionSetAttribute"))
            {
                return(false);
            }

            var attribute = new SSP.PermissionSetAttribute((SSP.SecurityAction)declaration.Action);

            var    named_argument = security_attribute.Properties [0];
            string value          = (string)named_argument.Argument.Value;

            switch (named_argument.Name)
            {
            case "XML":
                attribute.XML = value;
                break;

            case "Name":
                attribute.Name = value;
                break;

            default:
                throw new NotImplementedException(named_argument.Name);
            }

            set = attribute.CreatePermissionSet();
            return(true);
        }
Esempio n. 48
0
 /// <summary>
 /// Don't change the method name and parameters order. It is used by mcs
 /// </summary>
 internal void AddPermissionRequests(PermissionSet required, PermissionSet optional, PermissionSet refused)
 {
     throw new NotImplementedException();
 }
Esempio n. 49
0
 public PermissionSet Intersect(PermissionSet other)
 {
 }
Esempio n. 50
0
        internal ApplicationTrust(PermissionSet defaultGrantSet)
        {
            InitDefaultGrantSet(defaultGrantSet);

            m_fullTrustAssemblies = new List <StrongName>().AsReadOnly();
        }
Esempio n. 51
0
 public NamedPermissionSet(string name, PermissionSet permSet)
 {
 }
Esempio n. 52
0
 public JintEngine EnableSecurity()
 {
     permissionSet = new PermissionSet(PermissionState.None);
     return(this);
 }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing complete;

            if (requestMsg != null)
            {
                return(this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders;

            responseHeaders = null;
            responseStream  = null;
            string str         = null;
            string str2        = null;
            bool   flag        = true;
            string contentType = null;

            if (headers != null)
            {
                contentType = headers.ContentType;
            }
            else
            {
                contentType = requestHeaders["Content-Type"] as string;
            }
            if (contentType != null)
            {
                string str4;
                HttpChannelHelper.ParseContentType(contentType, out str2, out str4);
            }
            if ((str2 != null) && (string.Compare(str2, "text/xml", StringComparison.Ordinal) != 0))
            {
                flag = false;
            }
            if (this._protocol == Protocol.Http)
            {
                str = (string)requestHeaders["__RequestVerb"];
                if (!str.Equals("POST") && !str.Equals("M-POST"))
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                if (this._nextSink != null)
                {
                    return(this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
                }
                if (this._protocol != Protocol.Http)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                }
                responseHeaders = new TransportHeaders();
                responseHeaders["__HttpStatusCode"]   = "400";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                responseStream = null;
                responseMsg    = null;
                return(ServerProcessing.Complete);
            }
            bool bClientIsClr = true;

            try
            {
                string str7;
                string uRI = null;
                if (headers != null)
                {
                    uRI = headers.RequestUri;
                }
                else
                {
                    uRI = (string)requestHeaders["__RequestUri"];
                }
                if (RemotingServices.GetServerTypeForUri(uRI) == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                if (this._protocol == Protocol.Http)
                {
                    string str6 = (string)requestHeaders["User-Agent"];
                    if (str6 != null)
                    {
                        if (str6.IndexOf("MS .NET Remoting") == -1)
                        {
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }
                bool   data = true;
                object obj2 = requestHeaders["__CustomErrorsEnabled"];
                if ((obj2 != null) && (obj2 is bool))
                {
                    data = (bool)obj2;
                }
                CallContext.SetData("__CustomErrorsEnabled", data);
                Header[]      channelHeaders = this.GetChannelHeaders(requestHeaders, out str7);
                PermissionSet set            = null;
                if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full)
                {
                    set = new PermissionSet(PermissionState.None);
                    set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }
                try
                {
                    if (set != null)
                    {
                        set.PermitOnly();
                    }
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, channelHeaders, this._strictBinding, this.TypeFilterLevel);
                }
                finally
                {
                    if (set != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();
                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                if ((str7 != null) && !SoapServices.IsSoapActionValidForMethodBase(str7, ((IMethodMessage)requestMsg).MethodBase))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"), new object[] { str7 }));
                }
                sinkStack.Push(this, null);
                complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
                if (responseStream != null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                switch (complete)
                {
                case ServerProcessing.Complete:
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }
                    break;

                case ServerProcessing.OneWay:
                    sinkStack.Pop(this);
                    return(complete);

                case ServerProcessing.Async:
                    sinkStack.Store(this, null);
                    return(complete);

                default:
                    return(complete);
                }
                sinkStack.Pop(this);
                this.SerializeResponse(sinkStack, responseMsg, bClientIsClr, ref responseHeaders, out responseStream);
                return(complete);
            }
            catch (Exception exception)
            {
                complete    = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage)requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, this._includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0L;
                responseHeaders         = new TransportHeaders();
                if (this._protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = "text/xml; charset=\"utf-8\"";
                }
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
            return(complete);
        }
Esempio n. 54
0
 public JintEngine DisableSecurity()
 {
     permissionSet = new PermissionSet(PermissionState.Unrestricted);
     return(this);
 }
Esempio n. 55
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
            };

            newPost = SanitizePost(newPost);

            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
                });

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

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

                return(newPost);
            }

            return(newPost);
        }
Esempio n. 56
0
 public XmlSecureResolver(
     XmlResolver resolver, PermissionSet permissionSet)
 {
     this.resolver      = resolver;
     this.permissionSet = permissionSet;
 }
Esempio n. 57
0
        internal static PermissionSet ComputeZonePermissionSetHelper(string targetZone, PermissionSet includedPermissionSet, ITaskItem[] dependencies, string targetFrameworkMoniker)
        {
            // Custom Set.
            if (String.IsNullOrEmpty(targetZone) || String.Equals(targetZone, Custom, StringComparison.OrdinalIgnoreCase))
            {
                // just return the included set, no magic
                return(includedPermissionSet.Copy());
            }

            PermissionSet retSet = GetNamedPermissionSetFromZone(targetZone, targetFrameworkMoniker);

            return(retSet);
        }
Esempio n. 58
0
 public virtual void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady)
 {
     host.GetRestrictedPermissions(configRecord, out permissionSet, out isHostReady);
 }
Esempio n. 59
0
 /// <summary>When implemented by a derived class, returns a permission that represents access to isolated storage from within a permission set.</summary><returns>An <see cref="T:System.Security.Permissions.IsolatedStoragePermission" /> object.</returns><param name="ps">The <see cref="T:System.Security.PermissionSet" /> object that contains the set of permissions granted to code attempting to use isolated storage. </param>
 protected abstract IsolatedStoragePermission GetPermission(PermissionSet ps);
Esempio n. 60
0
        public static TopicViewModel CreateTopicViewModel(Topic topic,
                                                          PermissionSet permission,
                                                          List <Post> posts,
                                                          Post starterPost,
                                                          int?pageIndex,
                                                          int?totalCount,
                                                          int?totalPages,
                                                          MembershipUser loggedOnUser,
                                                          Settings settings,
                                                          bool getExtendedData = false)
        {
            var topicNotificationService = ServiceFactory.Get <ITopicNotificationService>();
            var pollAnswerService        = ServiceFactory.Get <IPollAnswerService>();
            var voteService      = ServiceFactory.Get <IVoteService>();
            var favouriteService = ServiceFactory.Get <IFavouriteService>();

            var userIsAuthenticated = loggedOnUser != null;

            // Check for online status
            var date = DateTime.UtcNow.AddMinutes(-AppConstants.TimeSpanInMinutesToShowMembers);

            var viewModel = new TopicViewModel
            {
                Permissions       = permission,
                Topic             = topic,
                Views             = topic.Views,
                DisablePosting    = loggedOnUser != null && (loggedOnUser.DisablePosting == true),
                PageIndex         = pageIndex,
                TotalCount        = totalCount,
                TotalPages        = totalPages,
                LastPostPermaLink = string.Concat(topic.NiceUrl, "?", AppConstants.PostOrderBy, "=", AppConstants.AllPosts, "#comment-", topic.LastPost.Id),
                MemberIsOnline    = topic.User.LastActivityDate > date,
            };

            if (starterPost == null)
            {
                starterPost = posts.FirstOrDefault(x => x.IsTopicStarter);
            }

            // Get votes for all posts
            var postIds = posts.Select(x => x.Id).ToList();

            postIds.Add(starterPost.Id);

            // Get all votes by post
            var votes = voteService.GetVotesByPosts(postIds);

            // Get all favourites for this user
            var allFavourites = favouriteService.GetByTopic(topic.Id);

            // Map the votes
            var startPostVotes = votes.Where(x => x.Post.Id == starterPost.Id).ToList();
            var startPostFavs  = allFavourites.Where(x => x.Post.Id == starterPost.Id).ToList();

            // Create the starter post viewmodel
            viewModel.StarterPost = CreatePostViewModel(starterPost, startPostVotes, permission, topic, loggedOnUser, settings, startPostFavs);

            // Map data from the starter post viewmodel
            viewModel.VotesUp   = startPostVotes.Count(x => x.Amount > 0);
            viewModel.VotesDown = startPostVotes.Count(x => x.Amount < 0);
            viewModel.Answers   = totalCount != null ? (int)totalCount : posts.Count() - 1;

            // Create the ALL POSTS view models
            viewModel.Posts = CreatePostViewModels(posts, votes, permission, topic, loggedOnUser, settings, allFavourites);

            // ########### Full topic need everything

            if (getExtendedData)
            {
                // See if the user has subscribed to this topic or not
                var isSubscribed = userIsAuthenticated && (topicNotificationService.GetByUserAndTopic(loggedOnUser, topic).Any());
                viewModel.IsSubscribed = isSubscribed;

                // See if the topic has a poll, and if so see if this user viewing has already voted
                if (topic.Poll != null)
                {
                    // There is a poll and a user
                    // see if the user has voted or not

                    viewModel.Poll = new PollViewModel
                    {
                        Poll = topic.Poll,
                        UserAllowedToVote = permission[SiteConstants.Instance.PermissionVoteInPolls].IsTicked
                    };

                    var answers = pollAnswerService.GetAllPollAnswersByPoll(topic.Poll);
                    if (answers.Any())
                    {
                        var pollvotes = answers.SelectMany(x => x.PollVotes).ToList();
                        if (userIsAuthenticated)
                        {
                            viewModel.Poll.UserHasAlreadyVoted = (pollvotes.Count(x => x.User.Id == loggedOnUser.Id) > 0);
                        }
                        viewModel.Poll.TotalVotesInPoll = pollvotes.Count();
                    }
                }
            }

            return(viewModel);
        }