Esempio n. 1
0
        public async Task ResetAuthCode()
        {
            string newCode = GenerateRandomPassword();
            var    user    = await _userManager.FindByNameAsync(User.Identity.Name);

            RedditSharp.IWebAgent cabalAgent = await serviceAgentPool.GetOrCreateAgentAsync(Configuration["CabalUsername"], () =>
            {
                return(Task.FromResult(
                           new RedditSharp.BotWebAgent(
                               Configuration["CabalUsername"],
                               Configuration["CabalPassword"],
                               Configuration["CabalClientID"],
                               Configuration["CabalSecret"],
                               Configuration["CabalRedirectURI"]
                               )
                           ));
            });

            RedditSharp.Reddit cabalReddit = new RedditSharp.Reddit(cabalAgent, true);

            await _userManager.RemovePasswordAsync(user);

            await _userManager.AddPasswordAsync(user, newCode);

            await cabalReddit.ComposePrivateMessageAsync("SnooNotes User Key",
                                                         $@"This is your key to allow a bot/thirdparty to access SnooNotes on your behalf. Guard it carefully!

#Key: `{newCode}`

If you did not request this, panic, then hit up /u/meepster23 to help sort it out.
", User.Identity.Name);
        }
Esempio n. 2
0
        private async Task <string> GetRedditUsername(RedditSharp.IWebAgent webagent, string name)
        {
            try {
                var user = await RedditSharp.Things.RedditUser.GetUserAsync(webagent, name).ConfigureAwait(false);

                if (name == user.Name)
                {
                    return(null);
                }
                return(user.Name);
            }
            catch {
                return(null);
            }
        }
Esempio n. 3
0
        static IEnumerable <RedditSharp.ModeratorUser> GetModerators(string subName, RedditSharp.IWebAgent agent, RedditSharp.Reddit reddit)
        {
            var request        = agent.CreateGet(string.Format(ModeratorsUrl, subName));
            var response       = request.GetResponse();
            var responseString = agent.GetResponseString(response.GetResponseStream());
            var json           = JObject.Parse(responseString);
            var type           = json["kind"].ToString();

            if (type != "UserList")
            {
                throw new FormatException("Reddit responded with an object that is not a user listing.");
            }
            var data   = json["data"];
            var mods   = data["children"].ToArray();
            var result = new RedditSharp.ModeratorUser[mods.Length];

            for (var i = 0; i < mods.Length; i++)
            {
                var mod = new RedditSharp.ModeratorUser(reddit, mods[i]);
                result[i] = mod;
            }
            return(result);
        }
Esempio n. 4
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);
        }