コード例 #1
0
ファイル: views.py プロジェクト: ob0420/python3-tutorial
def home_view(request):
	posts = Post.objects.filter(is_active=True)
	search = request.GET.get("search")
	if search:
		entry_query = get_query(search, ("title",))
		posts = posts.filter(entry_query)
	posts = paginate(posts, per_page=24, page=request.GET.get("page", 1))
	return render(request, "home.html", dict(posts=posts))
コード例 #2
0
 async def acl_check(self, ctx):
     """Check, if all commands are in database"""
     commands = self.get_free_commands(ctx.guild.id)
     output = utils.paginate(commands)
     for page in output:
         if len(page):
             await ctx.send("```" + page + "```")
     if len(commands):
         await ctx.send(self.text.get("check", "some", count=len(commands)))
     else:
         await ctx.send(self.text.get("check", "none"))
コード例 #3
0
    async def comments_list(self, ctx, user: Union[discord.Member,
                                                   discord.User]):
        comments: List[Comment] = Comment.get(ctx.guild.id, user.id)
        if not len(comments):
            return await ctx.reply(self.text.get("list", "none"))

        def format_comment(comment: Comment) -> str:
            timestamp: str = comment.timestamp.strftime("%Y-%m-%d %H:%M")
            author: discord.Member = ctx.guild.get_member(comment.author_id)
            author_name: str = (f"{comment.author_id}" if author is None else
                                discord.utils.escape_markdown(
                                    author.display_name))
            text: str = "\n".join(
                [f"> {line}" for line in comment.text.split("\n")])
            return f"**{author_name}**, {timestamp} (ID {comment.id}):\n{text}"

        response: str = "\n".join(
            [format_comment(comment) for comment in comments])
        stubs: List[str] = utils.paginate(response)
        await ctx.reply(stubs[0])
        if len(stubs) > 1:
            for stub in utils.paginate(response):
                await ctx.send(stub)
コード例 #4
0
    async def acl_audit(self, ctx, search: str = None):
        """Make security audit

        search: Only display commands containing the `search` string
        """
        rules = repo_a.get_rules(ctx.guild.id)
        if search is not None:
            rules = [r for r in rules if search in r.command]

        result = []
        for rule in sorted(rules, key=lambda r: r.command):
            result.append(self.get_rule_representation(rule))

        output = utils.paginate(result)
        for page in output:
            if len(page):
                await ctx.send("```" + page + "```")

        await ctx.send(self.text.get("audit"))
コード例 #5
0
ファイル: enum_views.py プロジェクト: hkmshb/centrak
def capture_index(request, tab=None):
    # clear fixed entry session
    request.session["paper_capture_fixed_entries"] = None

    # filter by current date if no date filter exists
    qs_GET = request.GET.copy()
    date_digitized = qs_GET.get("date_digitized", None)
    if not date_digitized:
        qs_GET["date_digitized"] = datetime.today().strftime("%Y-%m-%d")

    # retrieve paper captures
    status = Capture.EXISTING if not tab else Capture.NEW
    query = Q(medium=Capture.MEDIUM_PAPER) & Q(acct_status=status)

    if not request.user.is_superuser:
        p = request.user.profile
        region_name = p.location.name if p and p.location else ""
        query = query & Q(region_name=region_name) & Q(user_email=request.user.username)

    captures = Capture.objects(query).order_by("-date_digitized")
    filter = CaptureFilter(qs_GET, queryset=captures)
    page = paginate(request, filter)

    return render(request, "enumeration/capture_index.html", {"tab": tab, "captures": page, "filter": filter})
コード例 #6
0
ファイル: views.py プロジェクト: hkmshb/centrak
def accounts_list(request):
    page = paginate(request, Account.objects.all())
    return render(request, 'enumeration/admin/account_list.html', {
        'accts': page
    })
コード例 #7
0
    async def import_csv(self, ctx: commands.Context, path: str) -> bool:
        """Import rule csv"""
        all_commands = self.get_command_names()
        acl_groups = [g.name for g in repo_a.get_groups(ctx.guild.id)]

        skipped = []
        errors = {}
        done = []

        with open(path, newline="") as csvfile:
            reader = csv.DictReader(csvfile)

            for i, rule in enumerate(reader, 1):
                # skip comments
                if rule["command"].startswith("#"):
                    continue
                # detect misconfigured rows
                if len(rule) != 4:
                    skipped.append(
                        f"{i:>3} | wrong line    | {rule['command']}")
                    continue
                # detect misconfigured commands
                if rule["command"] not in all_commands:
                    skipped.append(
                        f"{i:>3} | no command    | {rule['command']}")
                    continue
                # detect misconfigured defaults
                if rule["default"] not in ("0", "1"):
                    skipped.append(
                        f"{i:>3} | wrong default | {rule['command']}: {rule['default']}"
                    )
                    continue
                # detect misconfigured groups
                groups_allowed = [
                    g for g in rule["allow"].split(" ") if len(g)
                ]
                groups_denied = [g for g in rule["deny"].split(" ") if len(g)]
                skip = False
                for group in groups_allowed + groups_denied:
                    if group not in acl_groups:
                        skipped.append(
                            f"{i:>3} | wrong group   | {rule['command']}: {group}"
                        )
                        skip = True
                        break
                if skip:
                    continue

                try:
                    repo_a.add_rule(ctx.guild.id, rule["command"],
                                    (rule["default"] == 1))
                    for group in groups_allowed:
                        repo_a.add_group_constraint(
                            guild_id=ctx.guild.id,
                            name=group,
                            command=rule["command"],
                            allow=True,
                        )
                    for group in groups_denied:
                        repo_a.add_group_constraint(
                            guild_id=ctx.guild.id,
                            name=group,
                            command=rule["command"],
                            allow=False,
                        )
                    done.append(rule["command"])
                except acl_repo.Duplicate:
                    skipped.append(
                        f"{i:>3} | already set   | {rule['command']}")
                except acl_repo.ACLException as e:
                    errors[rule["command"]] = str(e)

        if len(done):
            await ctx.send(self.text.get("csv_output", "new"))
            await ctx.send("```" + ", ".join(done) + "```")
        if len(skipped):
            await ctx.send(self.text.get("csv_output", "skipped"))
            for page in utils.paginate(skipped):
                await ctx.send("```" + page + "```")
        if len(errors):
            await ctx.send(self.text.get("csv_output", "errors"))
            output = []
            for command, error in errors.items():
                output.append(f"{command}: {error}")
            for page in utils.paginate(output):
                await ctx.send("```" + page + "```")