Example #1
0
        /// <summary>
        /// Gets the access level of the user, either directly or via roles
        /// </summary>
        public AccessLevel GetAccessLevel(ulong discordUserId, ulong discordGuildId)
        {
            using DBContext c = new DBContext();

            List <Permission> perms = c.Permission.Where(p => p.DiscordUserId == (long)discordUserId).ToList();

            //Check if we are dev
            for (int i = 1; i < perms.Count; i++)
            {
                if (perms[i].AccessLevel == (short)AccessLevel.Dev)
                {
                    return(AccessLevel.Dev);
                }
            }

            //default access level
            short access = (short)AccessLevel.User;

            if (discordGuildId != 0)
            {
                try
                {
                    DiscordGuild guild = DiscordHandler.GetGuildAsync(discordGuildId).Result;

                    //Check if user is owner
                    if (guild.Owner.Id == discordUserId)
                    {
                        return(AccessLevel.Host);
                    }

                    //check if any permission is higher than our old permission but only those that are for our guild
                    perms = perms.Where(p => p.DiscordGuildId == (long)guild.Id).ToList();

                    for (int i = 0; i < perms.Count; i++)
                    {
                        if (perms[i].AccessLevel > access)
                        {
                            access = perms[i].AccessLevel;
                        }
                    }

                    DiscordMember member = guild.GetMemberAsync(discordUserId).Result;

                    //Check if we have any roles binded
                    List <DiscordRole> roles = member.Roles.ToList();

                    for (int i = 0; i < roles.Count; i++)
                    {
                        DiscordRoleBind drb = c.DiscordRoleBind.FirstOrDefault(drb => drb.RoleId == (long)roles[i].Id);

                        if (drb == null)
                        {
                            continue;
                        }

                        if (access < drb.AccessLevel)
                        {
                            access = drb.AccessLevel;
                        }
                    }
                }
                catch (AggregateException ex)
                {
                    if (!ex.InnerExceptions.Any(e => e is NotFoundException))
                    {
                        throw;
                    }
                }
            }

            return((AccessLevel)access);
        }