示例#1
0
        public async Task <bool> BanUser(Models.BannedEntity user)
        {
            var newBan = await bbDAL.BanUser(new Models.BannedEntity[] { user });

            if (!newBan)
            {
                return(false);
            }

            string reason = $"Banned {user.UserName} : {user.BanReason}";

            //only used if changing to allowing banning of multiple users at a time.
            //if (reason.Length > 255) reason = $"Banned {string.Join(",", userEntities.Select(e => e.EntityString))} for {string.Join(",", userEntities.Select(e => e.BanReason).Distinct())} by {string.Join(",", userEntities.Select(e => e.BannedBy).Distinct())}";
            //if (reason.Length > 255) reason = "Banned lots of things and the summary is too long for the description.. RIP";

            bool done  = false;
            int  count = 1;

            var ident = await userManager.FindByNameAsync(user.BannedBy);

            var webAgent = await agentPool.GetOrCreateWebAgentAsync(user.BannedBy, (uname, uagent, rlimit) =>
            {
                return(Task.FromResult <RedditSharp.RefreshTokenPoolEntry>(new RedditSharp.RefreshTokenPoolEntry(uname, ident.RefreshToken, rlimit, uagent)));
            });

            if (!ident.HasWiki)
            {
                throw new UnauthorizedAccessException("Need Wiki Permissions");
            }
            if (!ident.HasConfig)
            {
                throw new UnauthorizedAccessException("Need Config Permissions");
            }
            RedditSharp.Reddit rd = new RedditSharp.Reddit(webAgent, true);

            var wiki = new RedditSharp.Wiki(webAgent, user.SubName);

            //var wiki = new RedditSharp.WikiPage()
            while (!done && count < 5)
            {
                try
                {
                    done = await SaveAutoModConfig(reason, wiki);
                }
                catch (WebException ex)
                {
                    if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Forbidden)
                    {
                        throw;
                    }
                    else
                    {
                        count++;
                    }
                    await Task.Delay(100);
                }
            }

            return(true);
        }
        public async Task <string[]> Get(string id)
        {
            if (!User.HasClaim("uri:snoonotes:admin", id.ToLower()))
            {
                throw new UnauthorizedAccessException("You are not an admin of this subreddit!");
            }
            var agent = await agentPool.GetOrCreateWebAgentAsync(User.Identity.Name, async (uname, uagent, rlimit) =>
            {
                var ident = await userManager.FindByNameAsync(User.Identity.Name);
                return(new RedditSharp.RefreshTokenPoolEntry(uname, ident.RefreshToken, rlimit, uagent));
            });

            var warningTypes = await RedditSharp.ToolBoxUserNotes.GetWarningKeys(agent, id);

            return(warningTypes.Select(s => s ?? "null").ToArray());
        }
示例#3
0
        public async Task <IEnumerable <string> > GetInactiveModeratedSubreddits()
        {
            var agent = await agentPool.GetOrCreateWebAgentAsync(User.Identity.Name, async (uname, uagent, rlimit) =>
            {
                var ident = await _userManager.FindByNameAsync(User.Identity.Name);
                return(new RedditSharp.RefreshTokenPoolEntry(uname, ident.RefreshToken, rlimit, uagent));
            });

            RedditSharp.Reddit rd = new RedditSharp.Reddit(agent, true);

            List <Models.Subreddit> activeSubs = await subBLL.GetActiveSubs(User);

            List <string> activeSubNames = activeSubs.Select(s => s.SubName.ToLower()).ToList();
            List <string> inactiveSubs   = new List <string>();
            await rd.User.GetModeratorSubreddits().ForEachAsync(s => { if (s.ModPermissions.HasFlag(RedditSharp.ModeratorPermission.All) && !activeSubNames.Contains(s.Name.ToLower()))
                                                                       {
                                                                           inactiveSubs.Add(s.Name);
                                                                       }
                                                                });

            return(inactiveSubs.OrderBy(s => s));
        }
示例#4
0
        public override async Task <bool> UpdateModsForSubAsync(Models.Subreddit sub, ClaimsPrincipal user)
        {
            if (!user.HasClaim("uri:snoonotes:admin", sub.SubName.ToLower()))
            {
                throw new UnauthorizedAccessException("You don't have 'Full' permissions to this subreddit!");
            }
            if (sub.SubName.ToLower() == Configuration["CabalSubreddit"].ToLower())
            {
                return(false);
            }

            sub = (await subDAL.GetSubreddits(new string[] { sub.SubName })).First();
            if (sub == null)
            {
                throw new Exception("Unrecognized subreddit");
            }
            string subName = sub.SubName.ToLower();
            //var usersWithAccess = userManager.Users.Where(u =>
            //    u.Claims.Where(c =>
            //        c.ClaimType == ClaimTypes.Role && c.ClaimValue == sub.SubName.ToLower()).Count() > 0).ToList();
            var usersWithAccess = await _userManager.GetUsersInRoleAsync(subName);

            //var x = userManager.Users.Where(u=>u.Claims.Select(c => c.ClaimValue).Contains("videos")).ToList();
            //var y = userManager.Users.Select(u => u.Claims);
            var ident = await _userManager.FindByNameAsync(user.Identity.Name);


            ClaimsIdentity curuser = user.Identity as ClaimsIdentity;

            RedditSharp.IWebAgent agent;
            if (ident.HasConfig)
            {
                agent = await agentPool.GetOrCreateWebAgentAsync(curuser.Name, (uname, uagent, rlimit) =>
                {
                    return(Task.FromResult(new RedditSharp.RefreshTokenPoolEntry(uname, ident.RefreshToken, rlimit, uagent)));
                });
            }
            else
            {
                agent = new RedditSharp.WebAgent();
            }
            RedditSharp.Reddit           rd = new RedditSharp.Reddit(agent);
            RedditSharp.Things.Subreddit subinfo;
            try
            {
                subinfo = await rd.GetSubredditAsync(sub.SubName);
            }
            catch
            {
                return(false);
            }
            var modsWithAccess = (await subinfo.GetModeratorsAsync()).Where(m => ((int)m.Permissions & sub.Settings.AccessMask) > 0);
            // get list of users to remove perms from
            var usersToRemove = usersWithAccess.Where(u => !modsWithAccess.Select(m => m.Name.ToLower()).Contains(u.UserName.ToLower())).ToList();

            foreach (var appuser in usersToRemove)
            {
                await _userManager.RemoveFromRoleAsync(appuser, subName);

                //if ( appuser.Claims.Where( c => c.ClaimType == "uri:snoonotes:admin" && c.ClaimValue == subName ).Count() > 0 ) {
                await _userManager.RemoveClaimAsync(appuser, new Claim("uri:snoonotes:admin", subName));

                //}
            }

            var usersToAdd = modsWithAccess.Where(m => ((int)m.Permissions & sub.Settings.AccessMask) > 0 && !usersWithAccess.Select(u => u.UserName.ToLower()).Contains(m.Name.ToLower()));

            foreach (var appuser in usersToAdd)
            {
                try
                {
                    var u = await _userManager.FindByNameAsync(appuser.Name);

                    if (u != null)
                    {
                        //assume it won't be adding a duplicate *holds breath*
                        if (appuser.Permissions.HasFlag(RedditSharp.ModeratorPermission.All))
                        {
                            await _userManager.AddToRoleAsync(u, subName);

                            await _userManager.AddClaimAsync(u, new Claim("uri:snoonotes:admin:", subName));
                        }
                        else if (((int)appuser.Permissions & sub.Settings.AccessMask) > 0)
                        {
                            await _userManager.AddToRoleAsync(u, subName);
                        }
                    }
                }
                catch
                {
                    //TODO something, mighta caught a non registered user?
                }
            }


            usersWithAccess = usersWithAccess.Union(await _userManager.GetUsersForClaimAsync(new Claim("uri:snoonotes:admin", subName))).ToList();

            var usersToCheckUpdates = usersWithAccess.Where(u => modsWithAccess.Select(m => m.Name.ToLower()).Contains(u.UserName.ToLower())).ToList();

            foreach (var appuser in usersToCheckUpdates)
            {
                var access = modsWithAccess.Where(m => m.Name.ToLower() == appuser.UserName.ToLower()).Single().Permissions;
                if (access == RedditSharp.ModeratorPermission.All)
                {
                    if (!appuser.Claims.Any(c => c.ClaimType == "uri:snoonotes:admin" && c.ClaimValue == subName))
                    {
                        await _userManager.AddClaimAsync(appuser, new Claim("uri:snoonotes:admin", subName));
                    }
                }
                else
                {
                    //if( appuser.Claims.Any( c => c.ClaimType == "uri:snoonotes:admin" && c.ClaimValue == subName ) ) {

                    await _userManager.RemoveClaimAsync(appuser, new Claim("uri:snoonotes:admin", subName));

                    //}
                }
            }
            return(true);
        }
示例#5
0
        public virtual async Task UpdateModeratedSubredditsAsync(ApplicationUser ident)
        {
            string cabalSubName = Configuration["CabalSubreddit"].ToLower();

            RedditSharp.IWebAgent agent = await agentPool.GetOrCreateWebAgentAsync(ident.UserName, (uname, uagent, rlimit) =>
            {
                return(Task.FromResult <RedditSharp.RefreshTokenPoolEntry>(new RedditSharp.RefreshTokenPoolEntry(uname, ident.RefreshToken, rlimit, uagent)));
            });

            RedditSharp.Reddit rd = new RedditSharp.Reddit(agent, true);
            var modSubs           = new List <RedditSharp.Things.Subreddit>();
            await rd.User.GetModeratorSubreddits().ForEachAsync(s => modSubs.Add(s));

            List <string>           currentRoles  = (await _userManager.GetRolesAsync(ident)).ToList();//ident.Roles.ToList();//ident.Claims.Where( x => x.ClaimType == roleType ).Select( r => r.ClaimValue ).ToList<string>();
            List <Claim>            currentClaims = (await _userManager.GetClaimsAsync(ident)).ToList();
            List <Models.Subreddit> activeSubs    = await subDAL.GetActiveSubs();

            //remove subs from the activeSubs list that user isn't a mod of.
            activeSubs = activeSubs.Where(sub => modSubs.Exists(modsub => modsub.Name.ToLower() == sub.SubName.ToLower())).ToList();

            List <string> activeSubNames = activeSubs.Select(s => s.SubName.ToLower()).ToList();
            //List<IdentityRole> allRoles = _roleManager.Roles.ToList();

            //List<IdentityUserClaim<string>> currentAdminRoles = ident.Claims.Where( c => c.ClaimType == ident. ).ToList();
            List <string> rolesToAdd     = new List <string>();
            List <Claim>  claimsToAdd    = new List <Claim>();
            List <string> rolesToRemove  = new List <string>();
            List <Claim>  claimsToRemove = new List <Claim>();

            rolesToAdd.AddRange(
                activeSubs.Where(sub =>
                                 modSubs.Exists(modsub =>
                                                modsub.Name.ToLower() == sub.SubName.ToLower() &&
                                                (modsub.ModPermissions.HasFlag(RedditSharp.ModeratorPermission.All) || ((int)modsub.ModPermissions & sub.Settings.AccessMask) > 0)
                                                )
                                 ).Select(sub => sub.SubName.ToLower())
                );
            claimsToAdd.AddRange(
                activeSubs.Where(sub =>
                                 modSubs.Exists(modsub =>
                                                modsub.Name.ToLower() == sub.SubName.ToLower() &&
                                                modsub.ModPermissions.HasFlag(RedditSharp.ModeratorPermission.All)
                                                )
                                 ).Select(sub => new Claim("uri:snoonotes:admin", sub.SubName.ToLower()))
                );
            //rolesToRemove = set of current roles - roles in rolesToAdd
            rolesToRemove.AddRange(
                currentRoles.Where(curRole =>
                                   !rolesToAdd.Contains(curRole)
                                   )
                );

            claimsToRemove.AddRange(
                ident.Claims.Where(curClaim =>
                                   curClaim.ClaimType == "uri:snoonotes:admin" &&
                                   !claimsToAdd.Exists(addClaim =>
                                                       addClaim.Value == curClaim.ClaimValue &&
                                                       addClaim.Type == curClaim.ClaimType
                                                       )
                                   ).Select(c => new Claim(c.ClaimType, c.ClaimValue))
                );
            //clean out roles that the user already has
            rolesToAdd  = rolesToAdd.Where(rta => !currentRoles.Contains(rta)).ToList();
            claimsToAdd = claimsToAdd.Where(aclaim => !currentClaims.Any(cclaim => cclaim.Value == aclaim.Value && cclaim.Type == aclaim.Type)).ToList();

            string cabalUsername = Configuration["CabalUsername"];

            if (!string.IsNullOrWhiteSpace(cabalUsername) && !string.IsNullOrWhiteSpace(cabalSubName))
            {
                RedditSharp.IWebAgent cabalAgent = await serviceAgentPool.GetOrCreateAgentAsync(cabalUsername, () =>
                {
                    return(Task.FromResult(
                               new RedditSharp.BotWebAgent(
                                   cabalUsername,
                                   Configuration["CabalPassword"],
                                   Configuration["CabalClientID"],
                                   Configuration["CabalSecret"],
                                   Configuration["CabalRedirectURI"]
                                   )
                               ));
                });

                RedditSharp.Reddit cabalReddit = new RedditSharp.Reddit(cabalAgent, true);
                var cabalSub = await cabalReddit.GetSubredditAsync(cabalSubName);

                bool hasCabal = await cabalSub.GetContributors().Any(c => c.Name.ToLower() == ident.UserName.ToLower());

                if (hasCabal && !currentClaims.Any(c => c.Type == "uri:snoonotes:cabal" && c.Value == "true"))
                {
                    claimsToAdd.Add(new Claim("uri:snoonotes:cabal", "true"));
                }
                else if (!hasCabal && !currentClaims.Any(c => c.Type == "uri:snoonotes:cabal" && c.Value == "true"))
                {
                    claimsToRemove.Add(new Claim("uri:snoonotes:cabal", "true"));
                }
            }

            await _userManager.RemoveFromRolesAsync(ident, rolesToRemove);

            await _userManager.RemoveClaimsAsync(ident, claimsToRemove);

            await _userManager.AddClaimsAsync(ident, claimsToAdd);

            try
            {
                await _userManager.AddToRolesAsync(ident, rolesToAdd);
            }
            catch (InvalidOperationException)
            {
                foreach (var role in rolesToAdd)
                {
                    if (await _roleManager.FindByNameAsync(role) == null)
                    {
                        await _roleManager.CreateAsync(new IdentityRole(role));
                    }
                }
                await _userManager.AddToRolesAsync(ident, rolesToAdd);
            }
            ident.LastUpdatedRoles = DateTime.UtcNow;
            await _userManager.UpdateAsync(ident);
        }