Compare commits
11 Commits
e656487d6d
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67b0a0f6b9 | ||
|
|
6066ce4169 | ||
|
|
c681560f73 | ||
|
|
d71e46ecd0 | ||
|
|
40feb92473 | ||
|
|
881188587d | ||
|
|
982925b699 | ||
|
|
c9e11c4bd1 | ||
|
|
ae208d6b39 | ||
|
|
3eb0688460 | ||
|
|
91a9be0868 |
17
.env.example
Normal file
17
.env.example
Normal file
@@ -0,0 +1,17 @@
|
||||
# Flask App
|
||||
FLASK_APP=run.py
|
||||
FLASK_CONFIG=development
|
||||
FLASK_DEBUG=1
|
||||
SECRET_KEY='bM2qE6aA0mB1iI0llaG0aM1bL1aI2eA6'
|
||||
|
||||
# 数据库 (MySQL) - 请替换为你的真实配置
|
||||
DB_USER='pt_blacklist'
|
||||
DB_PASSWORD='password'
|
||||
DB_HOST='127.0.0.1'
|
||||
DB_NAME='pt_blacklist'
|
||||
|
||||
# Redis for Session
|
||||
REDIS_URL='redis://127.0.0.1:6379/0'
|
||||
|
||||
# 日志配置
|
||||
LOG_RETENTION_DAYS=7
|
||||
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
by the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -3,42 +3,71 @@ from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_login import LoginManager
|
||||
from flask_session import Session
|
||||
from flask_wtf.csrf import CSRFProtect
|
||||
from config import config
|
||||
from flask_bootstrap import Bootstrap
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
import glob
|
||||
|
||||
# 初始化扩展,但此时不传入 app
|
||||
# 初始化扩展
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
login_manager = LoginManager()
|
||||
sess = Session()
|
||||
csrf = CSRFProtect()
|
||||
bootstrap = Bootstrap()
|
||||
# login_manager 的基本配置
|
||||
login_manager.login_view = 'auth.login' # 后面我们会创建一个叫 'auth' 的蓝图
|
||||
login_manager.login_view = 'auth.login'
|
||||
|
||||
def create_app(config_name='default'):
|
||||
"""
|
||||
应用工厂函数
|
||||
:param config_name: 配置名称 ('development', 'production')
|
||||
:return: Flask app instance
|
||||
"""
|
||||
"""应用工厂函数,创建并配置Flask应用实例"""
|
||||
app = Flask(__name__)
|
||||
|
||||
# 1. 加载配置
|
||||
# 加载配置
|
||||
app.config.from_object(config[config_name])
|
||||
config[config_name].init_app(app)
|
||||
# 2. 初始化扩展
|
||||
# 配置代理转发
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
|
||||
|
||||
# 初始化扩展
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
login_manager.init_app(app)
|
||||
sess.init_app(app)
|
||||
csrf.init_app(app)
|
||||
bootstrap.init_app(app)
|
||||
|
||||
# 注册自定义过滤器
|
||||
from .filters import translate_status
|
||||
app.jinja_env.filters['translate_status'] = translate_status
|
||||
# 配置日志
|
||||
if not os.path.exists('logs'):
|
||||
os.mkdir('logs')
|
||||
|
||||
# 3. 注册蓝图 (Blueprint)
|
||||
# 后面我们会在这里添加蓝图
|
||||
# 清理过期日志
|
||||
log_retention_days = int(os.environ.get('LOG_RETENTION_DAYS', 7))
|
||||
cutoff_time = datetime.now() - timedelta(days=log_retention_days)
|
||||
for log_file in glob.glob('logs/*.log*'):
|
||||
if os.path.getmtime(log_file) < cutoff_time.timestamp():
|
||||
os.remove(log_file)
|
||||
|
||||
file_handler = RotatingFileHandler('logs/pt_blacklist.log', maxBytes=10240000, backupCount=10)
|
||||
file_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
|
||||
))
|
||||
file_handler.setLevel(logging.INFO)
|
||||
app.logger.addHandler(file_handler)
|
||||
app.logger.setLevel(logging.INFO)
|
||||
app.logger.info('PT黑名单系统启动')
|
||||
|
||||
# 注册自定义过滤器
|
||||
from .filters import translate_status, translate_reason, translate_reasons_list, to_beijing_time
|
||||
app.jinja_env.filters['translate_status'] = translate_status
|
||||
app.jinja_env.filters['translate_reason'] = translate_reason
|
||||
app.jinja_env.filters['translate_reasons_list'] = translate_reasons_list
|
||||
app.jinja_env.filters['to_beijing_time'] = to_beijing_time
|
||||
|
||||
# 注册蓝图
|
||||
from .routes import main as main_blueprint
|
||||
app.register_blueprint(main_blueprint)
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from flask import render_template, redirect, url_for, flash, request
|
||||
from flask import render_template, redirect, url_for, flash, request, current_app
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from . import auth
|
||||
from .. import db
|
||||
@@ -7,6 +7,7 @@ from ..forms import LoginForm, RegistrationForm
|
||||
|
||||
@auth.route('/register', methods=['GET', 'POST'])
|
||||
def register():
|
||||
"""用户注册"""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('main.index'))
|
||||
form = RegistrationForm()
|
||||
@@ -18,36 +19,43 @@ def register():
|
||||
username=form.username.data,
|
||||
pt_site=form.pt_site.data,
|
||||
uid=form.uid.data,
|
||||
status='pending' # 新用户需要管理员审核
|
||||
status='pending'
|
||||
)
|
||||
user.set_password(form.password.data)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新用户注册: {user.username} ({user.email}) - 站点: {user.pt_site}')
|
||||
flash('注册申请已提交,请等待管理员审核。', 'info')
|
||||
return redirect(url_for('auth.login'))
|
||||
return render_template('auth/register.html', form=form)
|
||||
|
||||
@auth.route('/login', methods=['GET', 'POST'])
|
||||
def login():
|
||||
"""用户登录"""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('main.index'))
|
||||
form = LoginForm()
|
||||
if form.validate_on_submit():
|
||||
user = User.query.filter_by(email=form.email.data).first()
|
||||
if user is None or not user.check_password(form.password.data):
|
||||
current_app.logger.warning(f'登录失败: {form.email.data} - 无效的邮箱或密码')
|
||||
flash('无效的邮箱或密码。', 'danger')
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
if user.status != 'active':
|
||||
current_app.logger.warning(f'登录失败: {user.username} - 账户状态: {user.status}')
|
||||
flash(f'您的账户当前状态为 "{user.status}",无法登录。请联系管理员。', 'warning')
|
||||
return redirect(url_for('auth.login'))
|
||||
login_user(user, remember=form.remember_me.data)
|
||||
current_app.logger.info(f'用户登录: {user.username} ({user.email})')
|
||||
return redirect(url_for('main.index'))
|
||||
return render_template('auth/login.html', form=form)
|
||||
|
||||
@auth.route('/logout')
|
||||
@login_required
|
||||
def logout():
|
||||
"""用户登出"""
|
||||
current_app.logger.info(f'用户登出: {current_user.username}')
|
||||
logout_user()
|
||||
flash('您已成功登出。')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
"""权限装饰器"""
|
||||
from functools import wraps
|
||||
from flask import abort
|
||||
from flask_login import current_user
|
||||
|
||||
def admin_required(f):
|
||||
"""仅管理员可访问"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated or current_user.role != 'admin':
|
||||
abort(403) # HTTP 403 Forbidden error
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
# === 修正后的通用权限装饰器 ===
|
||||
def permission_required(*roles):
|
||||
"""指定角色可访问"""
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if not current_user.is_authenticated:
|
||||
abort(401) # Unauthorized
|
||||
abort(401)
|
||||
if current_user.role not in roles:
|
||||
abort(403) # Forbidden
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 正确的返回:返回包含了权限检查逻辑的包装函数
|
||||
return decorated_function # <--- 已修正
|
||||
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
@@ -1,27 +1,54 @@
|
||||
# app/filters.py
|
||||
# 状态翻译过滤器
|
||||
"""Jinja2模板过滤器"""
|
||||
from datetime import timedelta
|
||||
|
||||
STATUS_TRANSLATIONS = {
|
||||
# 举报状态
|
||||
'pending': '待审核',
|
||||
'in_review': '审核中',
|
||||
'approved': '已批准',
|
||||
'rejected': '已驳回',
|
||||
'revoked': '已撤销',
|
||||
'overturned': '已推翻',
|
||||
|
||||
# 申诉状态
|
||||
'awaiting_admin_reply': '等待管理员回复',
|
||||
'awaiting_user_reply': '等待用户回复',
|
||||
|
||||
# 用户状态
|
||||
'active': '正常',
|
||||
'disabled': '已禁用',
|
||||
|
||||
# 黑名单状态
|
||||
'expired': '已过期'
|
||||
}
|
||||
|
||||
REASON_TRANSLATIONS = {
|
||||
'cheating': '作弊 (刷上传/下载)',
|
||||
'trading': '账号交易/共享',
|
||||
'no_data': '注册后无数据',
|
||||
'failed_assessment': '考核未通过',
|
||||
'spam': '发布垃圾/违禁信息',
|
||||
'abusive': '辱骂/人身攻击',
|
||||
'low_ratio': '分享率过低',
|
||||
'hit_and_run': 'H&R (下载不做种)',
|
||||
'fake_seeding': '假做种',
|
||||
'multiple_accounts': '多账号/小号',
|
||||
'account_sharing': '账号共享',
|
||||
'reselling': '倒卖邀请',
|
||||
'harassment': '骚扰他人',
|
||||
'scamming': '诈骗行为',
|
||||
'other': '其他 (请在描述中详述)'
|
||||
}
|
||||
|
||||
def translate_status(status):
|
||||
"""将英文状态翻译为中文"""
|
||||
"""状态翻译过滤器"""
|
||||
return STATUS_TRANSLATIONS.get(status, status)
|
||||
|
||||
def translate_reason(reason):
|
||||
"""违规原因翻译过滤器"""
|
||||
return REASON_TRANSLATIONS.get(reason, reason)
|
||||
|
||||
def translate_reasons_list(reasons):
|
||||
"""违规原因列表翻译过滤器"""
|
||||
if not reasons:
|
||||
return []
|
||||
return [REASON_TRANSLATIONS.get(r, r) for r in reasons]
|
||||
|
||||
def to_beijing_time(utc_dt):
|
||||
"""UTC时间转北京时间(UTC+8)"""
|
||||
if utc_dt is None:
|
||||
return None
|
||||
return utc_dt + timedelta(hours=8)
|
||||
|
||||
22
app/forms.py
22
app/forms.py
@@ -3,9 +3,7 @@ from wtforms import StringField, SubmitField, PasswordField, BooleanField, TextA
|
||||
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Optional, URL
|
||||
from .models import User
|
||||
from wtforms_sqlalchemy.fields import QuerySelectField
|
||||
|
||||
def get_active_partner_sites():
|
||||
return PartnerSite.query.filter_by(is_active=True).order_by(PartnerSite.name)
|
||||
from .filters import REASON_TRANSLATIONS
|
||||
|
||||
class SearchForm(FlaskForm):
|
||||
search_term = StringField(
|
||||
@@ -38,11 +36,6 @@ class LoginForm(FlaskForm):
|
||||
remember_me = BooleanField('记住我')
|
||||
submit = SubmitField('登录')
|
||||
class ReportForm(FlaskForm):
|
||||
# reported_pt_site = StringField(
|
||||
# '被举报用户所在的 PT 站点',
|
||||
# validators=[DataRequired(), Length(min=2, max=100)],
|
||||
# render_kw={"placeholder": "例如:some.site.com"}
|
||||
# )
|
||||
reported_pt_site = SelectField('违规站点', validators=[DataRequired()])
|
||||
reported_username = StringField(
|
||||
'被举报的用户名',
|
||||
@@ -56,14 +49,7 @@ class ReportForm(FlaskForm):
|
||||
)
|
||||
reason_category = SelectField(
|
||||
'举报原因分类',
|
||||
choices=[
|
||||
('cheating', '作弊 (刷上传/下载)'),
|
||||
('trading', '账号交易/共享'),
|
||||
('spam', '发布垃圾/违禁信息'),
|
||||
('abusive', '辱骂/人身攻击'),
|
||||
('radio', '分享率过低'),
|
||||
('other', '其他 (请在描述中详述)')
|
||||
],
|
||||
choices=[(k, v) for k, v in REASON_TRANSLATIONS.items()],
|
||||
validators=[DataRequired()]
|
||||
)
|
||||
description = TextAreaField(
|
||||
@@ -88,8 +74,8 @@ class UpdateUserForm(FlaskForm):
|
||||
], validators=[DataRequired()])
|
||||
|
||||
status = SelectField('状态', choices=[
|
||||
('active', '激活 (Active)'),
|
||||
('disabled', '禁用 (Disabled)')
|
||||
('active', '正常'),
|
||||
('disabled', '已禁用')
|
||||
], validators=[DataRequired()])
|
||||
|
||||
submit = SubmitField('更新')
|
||||
|
||||
@@ -4,6 +4,7 @@ from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from app import db, login_manager
|
||||
|
||||
class PartnerSite(db.Model):
|
||||
"""合作PT站点模型"""
|
||||
__tablename__ = 'partner_sites'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
name = db.Column(db.String(100), unique=True, nullable=False, index=True)
|
||||
@@ -14,20 +15,23 @@ class PartnerSite(db.Model):
|
||||
|
||||
def __repr__(self):
|
||||
return f'<PartnerSite {self.name}>'
|
||||
|
||||
class User(UserMixin, db.Model):
|
||||
"""用户模型"""
|
||||
__tablename__ = 'users'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(64), unique=True, index=True, nullable=False)
|
||||
email = db.Column(db.String(120), unique=True, index=True, nullable=False)
|
||||
password_hash = db.Column(db.String(256))
|
||||
role = db.Column(db.String(16), default='user', index=True) # 'user', 'admin', 'trust_user'
|
||||
status = db.Column(db.String(16), default='pending', index=True) # 'pending', 'active', 'disabled'
|
||||
role = db.Column(db.String(16), default='user', index=True)
|
||||
status = db.Column(db.String(16), default='pending', index=True)
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
pt_site = db.Column(db.String(100)) # 注册时填写的站点
|
||||
uid = db.Column(db.String(50)) # 注册时填写的 UID
|
||||
pt_site = db.Column(db.String(100))
|
||||
uid = db.Column(db.String(50))
|
||||
reports = db.relationship('Report', backref='reporter', lazy='dynamic')
|
||||
comments = db.relationship('Comment', back_populates='author', lazy='dynamic')
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -42,6 +46,7 @@ def load_user(user_id):
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
class Report(db.Model):
|
||||
"""举报模型"""
|
||||
__tablename__ = 'reports'
|
||||
__table_args__ = (
|
||||
db.Index('idx_report_status_created', 'status', 'created_at'),
|
||||
@@ -52,24 +57,24 @@ class Report(db.Model):
|
||||
reported_pt_site = db.Column(db.String(100), nullable=False)
|
||||
reported_username = db.Column(db.String(50))
|
||||
reported_email = db.Column(db.String(120), index=True, nullable=False)
|
||||
reason_category = db.Column(db.String(16), nullable=False) # 'cheating', 'trading', 'spam', 'abusive', 'radio', 'other'
|
||||
reason_category = db.Column(db.String(16), nullable=False)
|
||||
description = db.Column(db.Text, nullable=False)
|
||||
status = db.Column(db.String(16), index=True, default='pending') # 'pending', 'approved', 'rejected', 'revoked', 'overturned'
|
||||
status = db.Column(db.String(16), index=True, default='pending')
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
comments = db.relationship('Comment', backref='report', lazy='dynamic', cascade='all, delete-orphan')
|
||||
evidences = db.relationship('Evidence', backref='report', lazy='dynamic', cascade='all, delete-orphan')
|
||||
blacklist_entry = db.relationship('Blacklist', backref='report', uselist=False)
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Report {self.id}>'
|
||||
|
||||
class Evidence(db.Model):
|
||||
"""证据模型"""
|
||||
__tablename__ = 'evidences'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id', ondelete='CASCADE'), nullable=False)
|
||||
file_url = db.Column(db.String(1024), nullable=False) # 存储OSS或本地路径
|
||||
file_type = db.Column(db.String(16)) # 'image', 'zip', 'text', 'image_url'
|
||||
file_url = db.Column(db.String(1024), nullable=False)
|
||||
file_type = db.Column(db.String(16))
|
||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -77,6 +82,7 @@ class Evidence(db.Model):
|
||||
return f'<Evidence {self.id} for Report {self.report_id}>'
|
||||
|
||||
class Blacklist(db.Model):
|
||||
"""黑名单模型"""
|
||||
__tablename__ = 'blacklist'
|
||||
__table_args__ = (
|
||||
db.Index('idx_blacklist_email_status', 'normalized_email', 'status'),
|
||||
@@ -86,18 +92,21 @@ class Blacklist(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(64), index=True)
|
||||
email = db.Column(db.String(120), index=True)
|
||||
normalized_email = db.Column(db.String(120), index=True) # 归一化后的邮箱
|
||||
normalized_email = db.Column(db.String(120), index=True)
|
||||
pt_site = db.Column(db.String(100), index=True)
|
||||
uid = db.Column(db.String(50))
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id'), unique=True) # 确保一个举报只对应一个黑名单条目
|
||||
status = db.Column(db.String(16), default='active', index=True) # 'active', 'revoked', 'expired'
|
||||
report_ids = db.Column(db.JSON, default=list, nullable=False)
|
||||
reason_categories = db.Column(db.JSON, default=list, nullable=False)
|
||||
status = db.Column(db.String(16), default='active', index=True)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
appeals = db.relationship('Appeal', backref='blacklist_entry', lazy='dynamic')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Blacklist {self.normalized_email} on {self.pt_site}>'
|
||||
|
||||
class Comment(db.Model):
|
||||
"""评论模型"""
|
||||
__tablename__ = 'comments'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
body = db.Column(db.Text)
|
||||
@@ -105,26 +114,30 @@ class Comment(db.Model):
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
report_id = db.Column(db.Integer, db.ForeignKey('reports.id', ondelete='CASCADE'))
|
||||
author = db.relationship('User', back_populates='comments')
|
||||
|
||||
class Appeal(db.Model):
|
||||
"""申诉模型"""
|
||||
__tablename__ = 'appeals'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
reason = db.Column(db.Text, nullable=False) # 用户最初的申诉理由
|
||||
status = db.Column(db.String(32), nullable=False, default='awaiting_admin_reply', index=True) # 'awaiting_admin_reply', 'awaiting_user_reply', 'approved', 'rejected'
|
||||
reason = db.Column(db.Text, nullable=False)
|
||||
status = db.Column(db.String(32), nullable=False, default='awaiting_admin_reply', index=True)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
appealer_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) # 申诉人
|
||||
blacklist_entry_id = db.Column(db.Integer, db.ForeignKey('blacklist.id', ondelete='SET NULL')) # 关联的黑名单条目
|
||||
appealer_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
blacklist_entry_id = db.Column(db.Integer, db.ForeignKey('blacklist.id', ondelete='SET NULL'))
|
||||
messages = db.relationship('AppealMessage', backref='appeal', lazy='dynamic', cascade='all, delete-orphan')
|
||||
appealer = db.relationship('User', backref='appeals')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Appeal {self.id}>'
|
||||
|
||||
class AppealMessage(db.Model):
|
||||
"""申诉消息模型"""
|
||||
__tablename__ = 'appeal_messages'
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
body = db.Column(db.Text, nullable=False)
|
||||
created_at = db.Column(db.DateTime, index=True, default=datetime.utcnow)
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) # 消息发送者
|
||||
author_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
|
||||
appeal_id = db.Column(db.Integer, db.ForeignKey('appeals.id', ondelete='CASCADE'))
|
||||
author = db.relationship('User', backref='appeal_messages')
|
||||
|
||||
|
||||
230
app/routes.py
230
app/routes.py
@@ -1,8 +1,9 @@
|
||||
from flask import abort, Blueprint, render_template, request, flash,redirect, url_for
|
||||
from flask import abort, Blueprint, render_template, request, flash, redirect, url_for, current_app
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from flask_login import login_required, current_user
|
||||
from app import db
|
||||
from app.forms import SearchForm, ReportForm, ReportForm, UpdateUserForm, CommentForm, RevokeForm, AppealForm, AppealMessageForm, PartnerSiteForm
|
||||
from app.forms import SearchForm, ReportForm, UpdateUserForm, CommentForm, RevokeForm, AppealForm, AppealMessageForm, PartnerSiteForm
|
||||
from app.models import Blacklist, Report, Evidence, User, Comment, AppealMessage, Appeal, PartnerSite
|
||||
from app.decorators import admin_required, permission_required
|
||||
from app.services.email_normalizer import normalize_email
|
||||
@@ -11,33 +12,32 @@ main = Blueprint('main', __name__)
|
||||
|
||||
@main.route('/', methods=['GET', 'POST'])
|
||||
def index():
|
||||
"""首页 - 黑名单查询"""
|
||||
form = SearchForm()
|
||||
search_result = None
|
||||
searched = False
|
||||
if form.validate_on_submit():
|
||||
# 在处理表单之前,检查用户是否已登录
|
||||
if not current_user.is_authenticated:
|
||||
flash('请登录后才能使用查询功能。', 'warning')
|
||||
# 重定向到登录页面,或者直接返回首页
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
# 如果用户已登录,则执行以下查询逻辑
|
||||
searched = True
|
||||
search_term = form.search_term.data
|
||||
normalized_email = normalize_email(search_term)
|
||||
|
||||
search_result = Blacklist.query.join(Report).filter(
|
||||
search_result = Blacklist.query.filter(
|
||||
or_(
|
||||
Blacklist.normalized_email == normalized_email,
|
||||
Blacklist.username == search_term
|
||||
),
|
||||
Blacklist.status == 'active',
|
||||
Report.status == 'approved'
|
||||
Blacklist.status == 'active'
|
||||
).first()
|
||||
|
||||
if search_result:
|
||||
current_app.logger.info(f'黑名单查询命中: {search_term} by {current_user.username}')
|
||||
flash(f'警告: 查询到与 "{search_term}" 相关的公开不良记录。详情如下。', 'warning')
|
||||
else:
|
||||
current_app.logger.info(f'黑名单查询未命中: {search_term} by {current_user.username}')
|
||||
flash(f'未查询到与 "{search_term}" 相关的公开不良记录。', 'info')
|
||||
|
||||
return render_template('index.html', form=form, search_result=search_result, searched=searched, Appeal=Appeal)
|
||||
@@ -45,11 +45,23 @@ def index():
|
||||
@main.route('/report/new', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def create_report():
|
||||
"""创建新举报"""
|
||||
if current_user.status != 'active':
|
||||
flash('您的账户尚未激活,无法提交举报。请等待管理员审核。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
form = ReportForm()
|
||||
active_sites = PartnerSite.query.filter_by(is_active=True).order_by(PartnerSite.name).all()
|
||||
form.reported_pt_site.choices = [(site.name, site.name) for site in active_sites]
|
||||
if form.validate_on_submit():
|
||||
# 1. 创建 Report 对象
|
||||
existing_report = Report.query.filter_by(
|
||||
reported_email=form.reported_email.data,
|
||||
status='pending'
|
||||
).first()
|
||||
if existing_report:
|
||||
current_app.logger.warning(f'重复举报: {form.reported_email.data} by {current_user.username}')
|
||||
flash(f'该邮箱已有待审核的举报 (#{existing_report.id}),请勿重复提交。', 'warning')
|
||||
return render_template('create_report.html', form=form)
|
||||
|
||||
new_report = Report(
|
||||
reporter_id=current_user.id,
|
||||
reported_pt_site=form.reported_pt_site.data,
|
||||
@@ -61,31 +73,29 @@ def create_report():
|
||||
)
|
||||
db.session.add(new_report)
|
||||
|
||||
# 2. 处理证据链接
|
||||
urls_text = form.evidences.data
|
||||
# 按行分割,并移除空白行和首尾空格
|
||||
evidence_urls = [url.strip() for url in urls_text.strip().splitlines() if url.strip()]
|
||||
if not evidence_urls:
|
||||
flash('必须提供至少一个有效的证据链接。', 'danger')
|
||||
return render_template('create_report.html', form=form)
|
||||
# 对每个 URL 进行简单的验证和保存
|
||||
|
||||
valid_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')
|
||||
for url in evidence_urls:
|
||||
if url.lower().startswith(('http://', 'https://')) and url.lower().endswith(valid_extensions):
|
||||
evidence = Evidence(
|
||||
file_url=url,
|
||||
file_type='image_url', # 标记类型为图片链接
|
||||
file_type='image_url',
|
||||
report=new_report
|
||||
)
|
||||
db.session.add(evidence)
|
||||
else:
|
||||
# 如果有任何一个链接格式不正确,则回滚并提示用户
|
||||
db.session.rollback()
|
||||
current_app.logger.error(f'无效证据链接: {url[:50]} by {current_user.username}')
|
||||
flash(f'链接 "{url[:50]}..." 格式不正确或不是支持的图片格式。请提供以 http/https 开头,以 .png, .jpg 等结尾的图片链接。', 'danger')
|
||||
return render_template('create_report.html', form=form)
|
||||
|
||||
# 3. 提交到数据库
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新举报提交: #{new_report.id} - {form.reported_email.data} by {current_user.username}')
|
||||
flash('举报提交成功,请等待管理员审核。', 'success')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
@@ -95,25 +105,26 @@ def create_report():
|
||||
@login_required
|
||||
@permission_required('admin', 'trust_user')
|
||||
def report_list():
|
||||
# 获取页码,默认为第一页
|
||||
"""举报列表(管理员/信任用户)"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
# 查询举报,按创建时间倒序排列,并进行分页
|
||||
# 每页显示 20 条记录
|
||||
query = Report.query
|
||||
if current_user.role == 'trust_user':
|
||||
query = query.filter_by(status='pending')
|
||||
reports_pagination = query.order_by(Report.created_at.desc()).paginate(
|
||||
page=page, per_page=20, error_out=False
|
||||
)
|
||||
return render_template(
|
||||
'admin/report_list.html',
|
||||
reports=reports_pagination
|
||||
)
|
||||
return render_template('admin/report_list.html', reports=reports_pagination)
|
||||
@main.route('/report/<int:report_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@permission_required('admin', 'trust_user') # 允许 admin 和 trust_user 访问
|
||||
def report_detail(report_id):
|
||||
"""举报详情"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
|
||||
# 权限检查:管理员、信任用户、或举报提交者本人可以查看
|
||||
if current_user.role not in ['admin', 'trust_user'] and report.reporter_id != current_user.id:
|
||||
flash('您无权查看此举报。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
|
||||
if current_user.role == 'trust_user' and report.status != 'pending':
|
||||
flash('您无权查看已处理的举报。', 'warning')
|
||||
return redirect(url_for('main.report_list'))
|
||||
@@ -130,24 +141,29 @@ def report_detail(report_id):
|
||||
)
|
||||
db.session.add(comment)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'举报评论: #{report.id} by {current_user.username}')
|
||||
flash('你的审核建议已成功提交。', 'success')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
|
||||
comments = report.comments.order_by(Comment.created_at.desc()).all()
|
||||
related_reports = Report.query.filter(
|
||||
Report.reported_email == report.reported_email,
|
||||
Report.id != report.id
|
||||
).order_by(Report.created_at.desc()).all()
|
||||
|
||||
return render_template(
|
||||
'admin/report_detail.html',
|
||||
report=report,
|
||||
form=comment_form,
|
||||
revoke_form=revoke_form,
|
||||
comments=comments
|
||||
comments=comments,
|
||||
related_reports=related_reports
|
||||
)
|
||||
# === 独立的举报处理视图 (仅限 Admin) ===
|
||||
# 这个视图只处理动作,不渲染页面。它接收来自详情页按钮的 POST 请求。
|
||||
@main.route('/admin/report/<int:report_id>/process', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def process_report(report_id):
|
||||
"""处理举报(批准/驳回)"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
action = request.form.get('action')
|
||||
|
||||
@@ -157,26 +173,64 @@ def process_report(report_id):
|
||||
|
||||
if action == 'confirm':
|
||||
report.status = 'approved'
|
||||
# 检查是否已在黑名单中
|
||||
existing_blacklist = Blacklist.query.filter_by(report_id=report.id).first()
|
||||
normalized = normalize_email(report.reported_email)
|
||||
existing_blacklist = Blacklist.query.filter_by(normalized_email=normalized, status='active').first()
|
||||
|
||||
if not existing_blacklist:
|
||||
# 创建新的黑名单记录
|
||||
new_blacklist_entry = Blacklist(
|
||||
email=report.reported_email,
|
||||
normalized_email=normalize_email(report.reported_email),
|
||||
normalized_email=normalized,
|
||||
pt_site=report.reported_pt_site,
|
||||
uid=report.reported_username,
|
||||
report_id=report.id,
|
||||
report_ids=[report.id],
|
||||
reason_categories=[report.reason_category],
|
||||
username=report.reported_username or None
|
||||
)
|
||||
db.session.add(new_blacklist_entry)
|
||||
current_app.logger.info(f'举报批准: #{report.id} - {report.reported_email} by {current_user.username}')
|
||||
flash('举报已批准,并已将相关信息添加到黑名单。', 'success')
|
||||
else:
|
||||
flash('举报状态已更新为“批准”。该举报已在黑名单中,无需重复添加。', 'info')
|
||||
if report.reason_category not in existing_blacklist.reason_categories:
|
||||
existing_blacklist.reason_categories.append(report.reason_category)
|
||||
existing_blacklist.report_ids.append(report.id)
|
||||
flag_modified(existing_blacklist, 'reason_categories')
|
||||
flag_modified(existing_blacklist, 'report_ids')
|
||||
current_app.logger.info(f'举报合并: #{report.id} 合并到黑名单#{existing_blacklist.id} - 新增原因: {report.reason_category}')
|
||||
flash(f'举报已批准并合并到现有黑名单记录(新增违规原因:{report.reason_category})。', 'success')
|
||||
else:
|
||||
current_app.logger.info(f'举报批准: #{report.id} - 相同原因已存在,不合并')
|
||||
flash('举报已批准。该用户已有相同违规原因的记录,未进行合并。', 'info')
|
||||
|
||||
other_pending = Report.query.filter(
|
||||
Report.reported_email == report.reported_email,
|
||||
Report.id != report.id,
|
||||
Report.status == 'pending'
|
||||
).all()
|
||||
|
||||
merged_count = 0
|
||||
for other_report in other_pending:
|
||||
other_report.status = 'approved'
|
||||
bl = existing_blacklist or new_blacklist_entry
|
||||
if other_report.reason_category not in bl.reason_categories:
|
||||
bl.reason_categories.append(other_report.reason_category)
|
||||
bl.report_ids.append(other_report.id)
|
||||
flag_modified(bl, 'reason_categories')
|
||||
flag_modified(bl, 'report_ids')
|
||||
merged_count += 1
|
||||
comment = Comment(
|
||||
body=f'该举报已自动批准(关联举报 #{report.id} 已确认违规)',
|
||||
report=other_report,
|
||||
author=current_user._get_current_object()
|
||||
)
|
||||
db.session.add(comment)
|
||||
|
||||
if other_pending:
|
||||
current_app.logger.info(f'自动批准关联举报: {len(other_pending)}个,合并{merged_count}个不同原因')
|
||||
flash(f'同时自动处理了 {len(other_pending)} 个相关举报(其中 {merged_count} 个不同原因已合并)。', 'info')
|
||||
elif action == 'invalidate':
|
||||
report.status = 'rejected'
|
||||
flash('举报状态已更新为“无效”。', 'success')
|
||||
|
||||
current_app.logger.info(f'举报驳回: #{report.id} by {current_user.username}')
|
||||
flash('举报状态已更新为"无效"。', 'success')
|
||||
else:
|
||||
flash('无效的操作。', 'danger')
|
||||
db.session.commit()
|
||||
@@ -185,44 +239,49 @@ def process_report(report_id):
|
||||
@login_required
|
||||
@admin_required
|
||||
def revoke_report(report_id):
|
||||
"""撤销已批准的举报"""
|
||||
report = Report.query.get_or_404(report_id)
|
||||
# 只有已批准的举报才能被撤销
|
||||
if report.status != 'approved':
|
||||
flash('错误:只有已批准的举报才能被撤销。', 'danger')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
form = RevokeForm()
|
||||
if form.validate_on_submit():
|
||||
# 1. 从黑名单中移除
|
||||
blacklist_entry = Blacklist.query.filter_by(report_id=report.id).first()
|
||||
if blacklist_entry:
|
||||
normalized = normalize_email(report.reported_email)
|
||||
blacklist_entry = Blacklist.query.filter_by(normalized_email=normalized, status='active').first()
|
||||
|
||||
if blacklist_entry and report.id in blacklist_entry.report_ids:
|
||||
blacklist_entry.report_ids.remove(report.id)
|
||||
if report.reason_category in blacklist_entry.reason_categories:
|
||||
blacklist_entry.reason_categories.remove(report.reason_category)
|
||||
flag_modified(blacklist_entry, 'report_ids')
|
||||
flag_modified(blacklist_entry, 'reason_categories')
|
||||
|
||||
if len(blacklist_entry.report_ids) == 0:
|
||||
db.session.delete(blacklist_entry)
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} - 黑名单记录已删除')
|
||||
flash('举报已成功撤销,并已从黑名单中移除。', 'success')
|
||||
else:
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} - 从黑名单中移除该举报')
|
||||
flash(f'举报已成功撤销,已从黑名单中移除该违规原因(剩余 {len(blacklist_entry.report_ids)} 个举报)。', 'success')
|
||||
|
||||
# 2. 更新举报状态
|
||||
report.status = 'revoked'
|
||||
|
||||
# 3. 将撤销理由记录为一条特殊的评论(审计日志)
|
||||
revocation_comment = Comment(
|
||||
body=f"[系统操作:撤销批准]\n理由:{form.reason.data}",
|
||||
report=report,
|
||||
author=current_user._get_current_object()
|
||||
)
|
||||
db.session.add(revocation_comment)
|
||||
|
||||
db.session.commit()
|
||||
flash('举报已成功撤销,并已从黑名单中移除。', 'success')
|
||||
current_app.logger.warning(f'举报撤销: #{report.id} by {current_user.username} - 理由: {form.reason.data[:50]}')
|
||||
else:
|
||||
# 如果表单验证失败(例如理由为空),显示错误信息
|
||||
flash('撤销失败:' + ' '.join(form.reason.errors), 'danger')
|
||||
return redirect(url_for('main.report_detail', report_id=report.id))
|
||||
@main.route('/admin/users')
|
||||
@login_required
|
||||
@admin_required
|
||||
def manage_users():
|
||||
# 查询所有非待审核的用户
|
||||
"""用户管理"""
|
||||
users = User.query.filter(User.status != 'pending').order_by(User.created_at.desc()).all()
|
||||
|
||||
# 为每个用户创建一个预填充了当前数据的表单实例
|
||||
# 这样在模板中可以直接渲染,并且下拉框会默认选中用户的当前角色/状态
|
||||
forms = {}
|
||||
for user in users:
|
||||
forms[user.id] = UpdateUserForm(obj=user)
|
||||
@@ -231,13 +290,13 @@ def manage_users():
|
||||
@login_required
|
||||
@admin_required
|
||||
def update_user(user_id):
|
||||
"""更新用户角色和状态"""
|
||||
if user_id == 1:
|
||||
flash('错误:禁止修改初始管理员账户的角色和状态。', 'danger')
|
||||
return redirect(url_for('main.manage_users'))
|
||||
user = User.query.get_or_404(user_id)
|
||||
form = UpdateUserForm() # 创建一个空的表单来接收 POST 数据
|
||||
form = UpdateUserForm()
|
||||
if form.validate_on_submit():
|
||||
# 安全检查:防止管理员误操作禁用或降级自己
|
||||
if user == current_user:
|
||||
if form.role.data != 'admin' or form.status.data != 'active':
|
||||
flash('警告:您不能禁用或降级自己的管理员账户。', 'danger')
|
||||
@@ -245,9 +304,9 @@ def update_user(user_id):
|
||||
user.role = form.role.data
|
||||
user.status = form.status.data
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'用户更新: {user.username} - 角色:{user.role} 状态:{user.status} by {current_user.username}')
|
||||
flash(f'用户 {user.username} 的信息已成功更新。', 'success')
|
||||
else:
|
||||
# 如果表单验证失败,也给出提示
|
||||
flash('更新失败,请检查提交的数据。', 'danger')
|
||||
return redirect(url_for('main.manage_users'))
|
||||
|
||||
@@ -255,37 +314,47 @@ def update_user(user_id):
|
||||
@login_required
|
||||
@admin_required
|
||||
def pending_users():
|
||||
"""待审核用户列表"""
|
||||
users_to_review = User.query.filter_by(status='pending').order_by(User.created_at.asc()).all()
|
||||
return render_template('admin/pending_users.html', users=users_to_review)
|
||||
|
||||
@main.route('/admin/user/<int:user_id>/approve', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def approve_user(user_id):
|
||||
"""批准用户注册"""
|
||||
user = User.query.get_or_404(user_id)
|
||||
user.status = 'active'
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'用户注册批准: {user.username} ({user.email}) by {current_user.username}')
|
||||
flash(f'用户 {user.username} 的注册申请已被批准。', 'success')
|
||||
return redirect(url_for('main.pending_users'))
|
||||
|
||||
@main.route('/admin/user/<int:user_id>/reject', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def reject_user(user_id):
|
||||
"""拒绝用户注册"""
|
||||
user = User.query.get_or_404(user_id)
|
||||
username = user.username
|
||||
email = user.email
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
flash(f'用户 {user.username} 的注册申请已被拒绝并删除。', 'success')
|
||||
current_app.logger.info(f'用户注册拒绝: {username} ({email}) by {current_user.username}')
|
||||
flash(f'用户 {username} 的注册申请已被拒绝并删除。', 'success')
|
||||
return redirect(url_for('main.pending_users'))
|
||||
|
||||
@main.route('/appeal/create/<int:blacklist_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def create_appeal(blacklist_id):
|
||||
"""创建申诉"""
|
||||
blacklist_entry = Blacklist.query.get_or_404(blacklist_id)
|
||||
|
||||
# 安全检查:确保用户只能为自己的黑名单记录申诉(邮箱匹配 或 UID+站点匹配)
|
||||
if not (current_user.email == blacklist_entry.email or
|
||||
(current_user.uid == blacklist_entry.uid and current_user.pt_site == blacklist_entry.pt_site)):
|
||||
current_app.logger.warning(f'非法申诉尝试: 用户{current_user.username} 尝试申诉黑名单#{blacklist_id}')
|
||||
abort(403)
|
||||
# 检查是否已有进行中的申诉
|
||||
|
||||
if blacklist_entry.appeals.filter(Appeal.status.in_(['awaiting_admin_reply', 'awaiting_user_reply'])).first():
|
||||
flash('您已有一个正在进行中的申诉,请勿重复提交。', 'warning')
|
||||
return redirect(url_for('main.index'))
|
||||
@@ -298,19 +367,18 @@ def create_appeal(blacklist_id):
|
||||
)
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新申诉提交: #{appeal.id} - 黑名单#{blacklist_id} by {current_user.username}')
|
||||
flash('您的申诉已成功提交,请等待管理员审核。', 'success')
|
||||
# 提交成功后,跳转到申诉详情页
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
|
||||
# 如果是 GET 请求,或表单验证失败,则渲染创建页面
|
||||
return render_template('create_appeal.html', form=form, entry=blacklist_entry)
|
||||
@main.route('/appeal/<int:appeal_id>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def appeal_detail(appeal_id):
|
||||
"""申诉详情和对话"""
|
||||
appeal = Appeal.query.get_or_404(appeal_id)
|
||||
|
||||
# 权限检查:只有申诉人或管理员可以查看
|
||||
if appeal.appealer_id != current_user.id and not current_user.role=='admin': # 假设你有 MANAGE_REPORTS 权限
|
||||
if appeal.appealer_id != current_user.id and not current_user.role=='admin':
|
||||
abort(403)
|
||||
form = AppealMessageForm()
|
||||
if form.validate_on_submit():
|
||||
@@ -322,7 +390,6 @@ def appeal_detail(appeal_id):
|
||||
author_id=current_user.id,
|
||||
appeal_id=appeal.id
|
||||
)
|
||||
# 更新申诉状态
|
||||
if current_user.role=='admin':
|
||||
appeal.status = 'awaiting_user_reply'
|
||||
else:
|
||||
@@ -330,16 +397,17 @@ def appeal_detail(appeal_id):
|
||||
|
||||
db.session.add(msg)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'申诉消息: #{appeal.id} by {current_user.username}')
|
||||
flash('消息已发送。', 'success')
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
messages = appeal.messages.order_by(AppealMessage.created_at.asc()).all()
|
||||
return render_template('appeal_detail.html', appeal=appeal, messages=messages, form=form)
|
||||
@main.route('/admin/appeals')
|
||||
@login_required
|
||||
@permission_required('admin') # 或者你的管理权限
|
||||
@permission_required('admin')
|
||||
def appeal_list():
|
||||
"""申诉列表(管理员)"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
# 优先显示待处理的
|
||||
appeals_pagination = Appeal.query.order_by(
|
||||
db.case(
|
||||
(Appeal.status == 'awaiting_admin_reply', 0),
|
||||
@@ -350,46 +418,48 @@ def appeal_list():
|
||||
).paginate(page=page, per_page=20, error_out=False)
|
||||
|
||||
return render_template('admin/appeal_list.html', appeals=appeals_pagination)
|
||||
|
||||
@main.route('/appeal/<int:appeal_id>/decide', methods=['POST'])
|
||||
@login_required
|
||||
@permission_required('admin') # 必须是管理员
|
||||
@permission_required('admin')
|
||||
def decide_appeal(appeal_id):
|
||||
"""处理申诉(批准/驳回)"""
|
||||
appeal = Appeal.query.get_or_404(appeal_id)
|
||||
if appeal.status in ['approved', 'rejected']:
|
||||
flash('该申诉已处理,无法重复操作。', 'warning')
|
||||
return redirect(url_for('main.appeal_detail', appeal_id=appeal.id))
|
||||
action = request.form.get('action')
|
||||
if action == 'approve':
|
||||
# 批准申诉:删除黑名单记录,更新申诉状态
|
||||
blacklist_entry = appeal.blacklist_entry
|
||||
blacklist_entry.status = 'revoked' # 将黑名单条目状态改为"已撤销"
|
||||
appeal.status = 'approved' # 同时更新申诉本身的状态
|
||||
if blacklist_entry.report:
|
||||
# 使用 'overturned' (已推翻) 可能比 'revoked' 更能描述 Report 的状态
|
||||
blacklist_entry.report.status = 'overturned'
|
||||
db.session.add(blacklist_entry.report)
|
||||
blacklist_entry.status = 'revoked'
|
||||
appeal.status = 'approved'
|
||||
for report_id in blacklist_entry.report_ids:
|
||||
report = Report.query.get(report_id)
|
||||
if report:
|
||||
report.status = 'overturned'
|
||||
db.session.add(report)
|
||||
db.session.add(blacklist_entry)
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
|
||||
# --- 修改结束 ---
|
||||
current_app.logger.info(f'申诉批准: #{appeal.id} by {current_user.username}')
|
||||
flash(f'申诉 #{appeal.id} 已被批准,对应的黑名单条目已撤销。', 'success')
|
||||
|
||||
elif action == 'reject':
|
||||
# 驳回申诉:仅更新申诉状态
|
||||
appeal.status = 'rejected'
|
||||
db.session.add(appeal)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'申诉驳回: #{appeal.id} by {current_user.username}')
|
||||
flash(f'已驳回申诉 #{appeal.id}。', 'info')
|
||||
else:
|
||||
flash('无效操作。', 'danger')
|
||||
return redirect(url_for('main.appeal_list'))
|
||||
|
||||
db.session.commit()
|
||||
return redirect(url_for('main.appeal_list'))
|
||||
|
||||
@main.route('/my/reports')
|
||||
@login_required
|
||||
def my_reports():
|
||||
"""我的举报列表"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
reports_pagination = Report.query.filter_by(reporter_id=current_user.id).order_by(
|
||||
Report.created_at.desc()
|
||||
@@ -399,6 +469,7 @@ def my_reports():
|
||||
@main.route('/my/appeals')
|
||||
@login_required
|
||||
def my_appeals():
|
||||
"""我的申诉列表"""
|
||||
page = request.args.get('page', 1, type=int)
|
||||
appeals_pagination = Appeal.query.filter_by(appealer_id=current_user.id).order_by(
|
||||
Appeal.created_at.desc()
|
||||
@@ -409,9 +480,9 @@ def my_appeals():
|
||||
@login_required
|
||||
@admin_required
|
||||
def manage_sites():
|
||||
"""站点管理"""
|
||||
form = PartnerSiteForm()
|
||||
if form.validate_on_submit():
|
||||
# ... (添加站点的逻辑保持不变)
|
||||
existing_site = PartnerSite.query.filter_by(name=form.name.data).first()
|
||||
if existing_site:
|
||||
flash('该站点名称已存在。', 'danger')
|
||||
@@ -419,32 +490,39 @@ def manage_sites():
|
||||
new_site = PartnerSite(name=form.name.data, url=form.url.data)
|
||||
db.session.add(new_site)
|
||||
db.session.commit()
|
||||
current_app.logger.info(f'新站点添加: {form.name.data} by {current_user.username}')
|
||||
flash(f'合作站点 "{form.name.data}" 已成功添加。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
|
||||
sites = PartnerSite.query.order_by(PartnerSite.name.asc()).all()
|
||||
return render_template('admin/manage_sites.html', sites=sites, form=form)
|
||||
# 添加用于删除和切换状态的路由
|
||||
|
||||
@main.route('/admin/site/<int:site_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def delete_site(site_id):
|
||||
"""删除站点"""
|
||||
site = PartnerSite.query.get_or_404(site_id)
|
||||
user_count = User.query.filter_by(pt_site=site.name).count()
|
||||
if user_count > 0:
|
||||
flash(f'无法删除站点 "{site.name}",因为已有 {user_count} 名用户关联到该站点。请先将其禁用。', 'danger')
|
||||
else:
|
||||
site_name = site.name
|
||||
db.session.delete(site)
|
||||
db.session.commit()
|
||||
flash(f'站点 "{site.name}" 已被删除。', 'success')
|
||||
current_app.logger.info(f'站点删除: {site_name} by {current_user.username}')
|
||||
flash(f'站点 "{site_name}" 已被删除。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
|
||||
@main.route('/admin/site/<int:site_id>/toggle_active', methods=['POST'])
|
||||
@login_required
|
||||
@admin_required
|
||||
def toggle_site_active(site_id):
|
||||
"""切换站点启用状态"""
|
||||
site = PartnerSite.query.get_or_404(site_id)
|
||||
site.is_active = not site.is_active
|
||||
db.session.commit()
|
||||
status = "启用" if site.is_active else "禁用"
|
||||
current_app.logger.info(f'站点状态切换: {site.name} - {status} by {current_user.username}')
|
||||
flash(f'站点 "{site.name}" 已被{status}。', 'success')
|
||||
return redirect(url_for('main.manage_sites'))
|
||||
@@ -34,7 +34,7 @@
|
||||
{{ appeal.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ appeal.updated_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.updated_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.appeal_detail', appeal_id=appeal.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<small class="text-muted">{{ user.email }}</small>
|
||||
</td>
|
||||
<td>{{ user.pt_site }} / {{ user.uid }}</td>
|
||||
<td>{{ user.created_at.strftime('%Y-%m-%d') }}</td>
|
||||
<td>{{ (user.created_at | to_beijing_time).strftime('%Y-%m-%d') }}</td>
|
||||
{% if user.id == 1 %}
|
||||
<td>
|
||||
<div>角色: <span class="badge bg-danger">{{ user.role }}</span></div>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<td>{{ user.email }}</td>
|
||||
<td>{{ user.pt_site }}</td>
|
||||
<td>{{ user.uid }}</td>
|
||||
<td>{{ user.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (user.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<form action="{{ url_for('main.approve_user', user_id=user.id) }}" method="POST" class="d-inline">
|
||||
<button type="submit" class="btn btn-sm btn-success">批准</button>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<li class="list-group-item"><strong>被举报邮箱:</strong> {{ report.reported_email }}</li>
|
||||
<li class="list-group-item"><strong>被举报用户名:</strong> {{ report.reported_username or 'N/A' }}</li>
|
||||
<li class="list-group-item"><strong>所属站点:</strong> {{ report.reported_pt_site }}</li>
|
||||
<li class="list-group-item"><strong>举报理由:</strong> {{ report.reason_category }}</li>
|
||||
<li class="list-group-item"><strong>举报理由:</strong> {{ report.reason_category | translate_reason }}</li>
|
||||
<li class="list-group-item"><strong>举报人:</strong> {{ report.reporter.username }}</li>
|
||||
<li class="list-group-item"><strong>状态:</strong> <strong class="text-capitalize">{{ report.status | translate_status }}</strong></li>
|
||||
<li class="list-group-item"><strong>详细描述:</strong><br><span style="white-space: pre-wrap;">{{ report.description }}</span></li>
|
||||
@@ -34,10 +34,11 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if current_user.role == 'admin' %}
|
||||
{% if current_user.role in ['admin', 'trust_user'] %}
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header"><h5 class="mb-0">管理员操作</h5></div>
|
||||
<div class="card-header"><h5 class="mb-0">{% if current_user.role == 'admin' %}管理员操作{% else %}信任用户操作{% endif %}</h5></div>
|
||||
<div class="card-body d-grid gap-2">
|
||||
{% if current_user.role == 'admin' %}
|
||||
{% if report.status == 'pending' or report.status == 'in_review' %}
|
||||
<form action="{{ url_for('main.process_report', report_id=report.id) }}" method="POST" class="d-grid">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
@@ -56,12 +57,33 @@
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">该举报已处理完毕,无更多操作。</p>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="text-muted mb-0">您可以在下方添加审核建议。</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if current_user.role in ['admin'] and related_reports %}
|
||||
<div class="card shadow-sm mb-4">
|
||||
<div class="card-header"><h5 class="mb-0">相关举报 (同一邮箱)</h5></div>
|
||||
<div class="list-group list-group-flush">
|
||||
{% for r in related_reports %}
|
||||
<a href="{{ url_for('main.report_detail', report_id=r.id) }}" class="list-group-item list-group-item-action">
|
||||
<div class="d-flex justify-content-between">
|
||||
<span><strong>#{{ r.id }}</strong> - {{ r.reason_category | translate_reason }}</span>
|
||||
<span class="badge bg-secondary">{{ r.status | translate_status }}</span>
|
||||
</div>
|
||||
<small class="text-muted">{{ (r.created_at | to_beijing_time).strftime('%Y-%m-%d') }} | 举报人: {{ r.reporter.username }}</small>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 右侧评论区 -->
|
||||
{% if current_user.role in ['admin', 'trust_user'] %}
|
||||
<div class="col-lg-7">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header"><h5 class="mb-0">审核与讨论</h5></div>
|
||||
@@ -73,7 +95,7 @@
|
||||
<div class="p-2 bg-light rounded">
|
||||
<p class="small mb-0">{{ comment.body | safe }}</p>
|
||||
</div>
|
||||
<small class="text-muted">{{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small class="text-muted">{{ (comment.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
</div>
|
||||
</div>
|
||||
{% else %}
|
||||
@@ -98,6 +120,7 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 撤销操作的 Modal -->
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
</td>
|
||||
<td>{{ report.reporter.username }}</td>
|
||||
<td><span class="badge bg-info text-dark">{{ report.status | translate_status }}</span></td>
|
||||
<td>{{ report.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (report.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td><a href="{{ url_for('main.report_detail', report_id=report.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a></td>
|
||||
</tr>
|
||||
{% else %}
|
||||
|
||||
@@ -24,6 +24,18 @@
|
||||
{% if appeal.blacklist_entry %}
|
||||
<p class="mb-0"><strong>站点:</strong> {{ appeal.blacklist_entry.pt_site }}</p>
|
||||
<p class="mb-0"><strong>UID:</strong> {{ appeal.blacklist_entry.uid }}</p>
|
||||
<p class="mb-1"><strong>违规原因:</strong></p>
|
||||
{% if appeal.blacklist_entry.reason_categories and appeal.blacklist_entry.reason_categories|length > 0 %}
|
||||
<ul class="mb-0">
|
||||
{% for reason in appeal.blacklist_entry.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% elif appeal.blacklist_entry.report %}
|
||||
<p class="mb-0">{{ appeal.blacklist_entry.report.reason_category | translate_reason }}</p>
|
||||
{% else %}
|
||||
<p class="mb-0 text-muted">未知</p>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="mb-0 text-muted">黑名单记录已删除</p>
|
||||
{% endif %}
|
||||
@@ -56,7 +68,7 @@
|
||||
<div class="message user-message mb-3">
|
||||
<div class="message-header">
|
||||
<strong>{{ appeal.appealer.username }}</strong>
|
||||
<small>{{ appeal.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (appeal.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
</div>
|
||||
<div class="message-body">
|
||||
<p class="fw-bold">[初始申诉理由]</p>
|
||||
@@ -70,10 +82,10 @@
|
||||
<div class="message-header">
|
||||
{% if message.author.role == 'admin' %}
|
||||
<strong>{{ message.author.username }} (管理员)</strong>
|
||||
<small>{{ message.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (message.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
{% else %}
|
||||
<strong>{{ message.author.username }}</strong>
|
||||
<small>{{ message.created_at.strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
<small>{{ (message.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</small>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="message-body">
|
||||
|
||||
@@ -14,9 +14,20 @@
|
||||
<li class="list-group-item"><strong>UID:</strong> {{ entry.uid }}</li>
|
||||
<li class="list-group-item"><strong>邮箱:</strong> {{ entry.email }}</li>
|
||||
<li class="list-group-item"><strong>站点:</strong> {{ entry.pt_site }}</li>
|
||||
{% if entry.report %}
|
||||
<li class="list-group-item"><strong>违规原因:</strong> {{ entry.report.reason_category }}</li>
|
||||
<li class="list-group-item">
|
||||
<strong>违规原因:</strong>
|
||||
{% if entry.reason_categories and entry.reason_categories|length > 0 %}
|
||||
<ul class="mb-0 mt-1">
|
||||
{% for reason in entry.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% elif entry.report %}
|
||||
{{ entry.report.reason_category | translate_reason }}
|
||||
{% else %}
|
||||
未知
|
||||
{% endif %}
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<form method="POST" novalidate>
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
{{ form.evidences.label(class="form-label") }}
|
||||
{{ form.evidences(class="form-control", rows=3, placeholder="每行一个证据链接(请使用图床!)") }}
|
||||
{{ form.evidences(class="form-control", rows=3, placeholder="每行一个证据链接(请使用图床!)链接应为:png,jpg,jpeg,gif,bmp,webp结尾。") }}
|
||||
<div class="form-text">请提供所有相关证据的URL,每行一个。</div>
|
||||
{% for error in form.evidences.errors %}<div class="invalid-feedback d-block">{{ error }}</div>{% endfor %}
|
||||
</div>
|
||||
|
||||
@@ -45,10 +45,19 @@
|
||||
</div>
|
||||
<ul class="list-group list-group-flush">
|
||||
<li class="list-group-item"><strong>违规站点:</strong> {{ search_result.pt_site }}</li>
|
||||
{% if search_result.report %}
|
||||
<li class="list-group-item"><strong>违规原因:</strong> {{ search_result.report.reason_category }}</li>
|
||||
<li class="list-group-item">
|
||||
<strong>违规原因:</strong>
|
||||
{% if search_result.reason_categories and search_result.reason_categories|length > 0 %}
|
||||
<ul class="mb-0 mt-1">
|
||||
{% for reason in search_result.reason_categories %}
|
||||
<li>{{ reason | translate_reason }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
未知
|
||||
{% endif %}
|
||||
<li class="list-group-item"><strong>记录时间:</strong> {{ search_result.created_at.strftime('%Y-%m-%d') }}</li>
|
||||
</li>
|
||||
<li class="list-group-item"><strong>记录时间:</strong> {{ (search_result.created_at | to_beijing_time).strftime('%Y-%m-%d') }}</li>
|
||||
</ul>
|
||||
<p class="text-muted small mt-3">为保护隐私,仅展示必要的脱敏信息。具体违规描述不对外公开。</p>
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@
|
||||
{{ appeal.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ appeal.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ appeal.updated_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (appeal.updated_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.appeal_detail', appeal_id=appeal.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<td>#{{ report.id }}</td>
|
||||
<td>{{ report.reported_pt_site }}</td>
|
||||
<td>{{ report.reported_email }}</td>
|
||||
<td>{{ report.reason_category }}</td>
|
||||
<td>{{ report.reason_category | translate_reason }}</td>
|
||||
<td>
|
||||
<span class="badge
|
||||
{% if report.status == 'approved' %} bg-success
|
||||
@@ -36,7 +36,7 @@
|
||||
{{ report.status | translate_status }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ report.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>{{ (report.created_at | to_beijing_time).strftime('%Y-%m-%d %H:%M') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('main.report_detail', report_id=report.id) }}" class="btn btn-sm btn-outline-primary">查看详情</a>
|
||||
</td>
|
||||
|
||||
86
batch_report.py
Normal file
86
batch_report.py
Normal file
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
import pymysql
|
||||
from datetime import datetime
|
||||
|
||||
# 数据库配置
|
||||
DB_CONFIG = {
|
||||
"host": "localhost",
|
||||
"user": "your_db_user",
|
||||
"password": "your_db_password",
|
||||
"database": "your_db_name",
|
||||
"charset": "utf8mb4"
|
||||
}
|
||||
|
||||
# 举报配置
|
||||
REPORT_CONFIG = {
|
||||
"reporter_id": 1, # 举报人的用户ID
|
||||
"reported_pt_site": "站点名称",
|
||||
"reason_category": "scam",
|
||||
"description": "详细情况描述",
|
||||
"evidences": [
|
||||
"https://example.com/image1.png",
|
||||
"https://example.com/image2.jpg"
|
||||
]
|
||||
}
|
||||
|
||||
def load_users(json_file):
|
||||
with open(json_file, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
def insert_report(cursor, username, email):
|
||||
now = datetime.utcnow()
|
||||
cursor.execute(
|
||||
"INSERT INTO reports (reporter_id, reported_pt_site, reported_username, reported_email, "
|
||||
"reason_category, description, status, created_at, updated_at) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, 'pending', %s, %s)",
|
||||
(REPORT_CONFIG["reporter_id"], REPORT_CONFIG["reported_pt_site"], username, email,
|
||||
REPORT_CONFIG["reason_category"], REPORT_CONFIG["description"], now, now)
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
def insert_evidences(cursor, report_id):
|
||||
now = datetime.utcnow()
|
||||
for url in REPORT_CONFIG["evidences"]:
|
||||
cursor.execute(
|
||||
"INSERT INTO evidences (report_id, file_url, file_type, created_at, updated_at) "
|
||||
"VALUES (%s, %s, 'image_url', %s, %s)",
|
||||
(report_id, url, now, now)
|
||||
)
|
||||
|
||||
def main():
|
||||
users = load_users("users.json")
|
||||
conn = pymysql.connect(**DB_CONFIG)
|
||||
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
print(f"开始批量写入,共 {len(users)} 个用户\n")
|
||||
|
||||
success_count = 0
|
||||
for idx, user in enumerate(users, 1):
|
||||
username = user.get("username")
|
||||
email = user.get("email")
|
||||
|
||||
if not email:
|
||||
print(f"[{idx}] 跳过: 缺少邮箱")
|
||||
continue
|
||||
|
||||
print(f"[{idx}] 写入: {username or '(无)'} ({email})...", end=" ")
|
||||
|
||||
try:
|
||||
report_id = insert_report(cursor, username, email)
|
||||
insert_evidences(cursor, report_id)
|
||||
conn.commit()
|
||||
print(f"✓ 成功 (ID: {report_id})")
|
||||
success_count += 1
|
||||
except Exception as e:
|
||||
conn.rollback()
|
||||
print(f"✗ 失败: {e}")
|
||||
|
||||
print(f"\n完成! 成功: {success_count}/{len(users)}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
13
config.py
13
config.py
@@ -1,17 +1,18 @@
|
||||
"""应用配置"""
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import redis
|
||||
|
||||
# 加载 .env 文件中的环境变量
|
||||
basedir = os.path.abspath(os.path.dirname(__file__))
|
||||
load_dotenv(os.path.join(basedir, '.env'))
|
||||
|
||||
class Config:
|
||||
"""基础配置类"""
|
||||
"""基础配置"""
|
||||
SECRET_KEY = os.environ.get('SECRET_KEY') or 'a-hard-to-guess-string'
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
|
||||
# Session 配置
|
||||
WTF_CSRF_ENABLED = True
|
||||
WTF_CSRF_TIME_LIMIT = None
|
||||
WTF_CSRF_CHECK_DEFAULT = False
|
||||
SESSION_TYPE = 'redis'
|
||||
SESSION_PERMANENT = False
|
||||
SESSION_USE_SIGNER = True
|
||||
@@ -24,7 +25,6 @@ class Config:
|
||||
class DevelopmentConfig(Config):
|
||||
"""开发环境配置"""
|
||||
DEBUG = True
|
||||
# 数据库 URI
|
||||
DB_USER = os.environ.get('DB_USER')
|
||||
DB_PASSWORD = os.environ.get('DB_PASSWORD')
|
||||
DB_HOST = os.environ.get('DB_HOST')
|
||||
@@ -34,15 +34,12 @@ class DevelopmentConfig(Config):
|
||||
class ProductionConfig(Config):
|
||||
"""生产环境配置"""
|
||||
DEBUG = False
|
||||
# 数据库 URI
|
||||
DB_USER = os.environ.get('DB_USER')
|
||||
DB_PASSWORD = os.environ.get('DB_PASSWORD')
|
||||
DB_HOST = os.environ.get('DB_HOST')
|
||||
DB_NAME = os.environ.get('DB_NAME')
|
||||
SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}'
|
||||
|
||||
|
||||
# 方便地通过字典来选择配置
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""merge multiple reports for same user
|
||||
|
||||
Revision ID: db2662009e3d
|
||||
Revises:
|
||||
Create Date: 2025-11-24 22:33:03.614231
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'db2662009e3d'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('blacklist',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=64), nullable=True),
|
||||
sa.Column('email', sa.String(length=120), nullable=True),
|
||||
sa.Column('normalized_email', sa.String(length=120), nullable=True),
|
||||
sa.Column('pt_site', sa.String(length=100), nullable=True),
|
||||
sa.Column('uid', sa.String(length=50), nullable=True),
|
||||
sa.Column('report_ids', sa.JSON(), nullable=False),
|
||||
sa.Column('reason_categories', sa.JSON(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('blacklist', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_blacklist_email_status', ['normalized_email', 'status'], unique=False)
|
||||
batch_op.create_index('idx_blacklist_username_status', ['username', 'status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_email'), ['email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_normalized_email'), ['normalized_email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_pt_site'), ['pt_site'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_blacklist_username'), ['username'], unique=False)
|
||||
|
||||
op.create_table('partner_sites',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('url', sa.String(length=255), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('partner_sites', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_partner_sites_is_active'), ['is_active'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_partner_sites_name'), ['name'], unique=True)
|
||||
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('username', sa.String(length=64), nullable=False),
|
||||
sa.Column('email', sa.String(length=120), nullable=False),
|
||||
sa.Column('password_hash', sa.String(length=256), nullable=True),
|
||||
sa.Column('role', sa.String(length=16), nullable=True),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pt_site', sa.String(length=100), nullable=True),
|
||||
sa.Column('uid', sa.String(length=50), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_users_email'), ['email'], unique=True)
|
||||
batch_op.create_index(batch_op.f('ix_users_role'), ['role'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_users_status'), ['status'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_users_username'), ['username'], unique=True)
|
||||
|
||||
op.create_table('appeals',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('reason', sa.Text(), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('appealer_id', sa.Integer(), nullable=True),
|
||||
sa.Column('blacklist_entry_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['appealer_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['blacklist_entry_id'], ['blacklist.id'], ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('appeals', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_appeals_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_appeals_status'), ['status'], unique=False)
|
||||
|
||||
op.create_table('reports',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('reporter_id', sa.Integer(), nullable=False),
|
||||
sa.Column('reported_pt_site', sa.String(length=100), nullable=False),
|
||||
sa.Column('reported_username', sa.String(length=50), nullable=True),
|
||||
sa.Column('reported_email', sa.String(length=120), nullable=False),
|
||||
sa.Column('reason_category', sa.String(length=16), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['reporter_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('reports', schema=None) as batch_op:
|
||||
batch_op.create_index('idx_report_status_created', ['status', 'created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_created_at'), ['created_at'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_reported_email'), ['reported_email'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_reports_status'), ['status'], unique=False)
|
||||
|
||||
op.create_table('appeal_messages',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('author_id', sa.Integer(), nullable=True),
|
||||
sa.Column('appeal_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['appeal_id'], ['appeals.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('appeal_messages', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_appeal_messages_created_at'), ['created_at'], unique=False)
|
||||
|
||||
op.create_table('comments',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('body', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('author_id', sa.Integer(), nullable=True),
|
||||
sa.Column('report_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['report_id'], ['reports.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
with op.batch_alter_table('comments', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_comments_created_at'), ['created_at'], unique=False)
|
||||
|
||||
op.create_table('evidences',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('report_id', sa.Integer(), nullable=False),
|
||||
sa.Column('file_url', sa.String(length=1024), nullable=False),
|
||||
sa.Column('file_type', sa.String(length=16), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['report_id'], ['reports.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('evidences')
|
||||
with op.batch_alter_table('comments', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_comments_created_at'))
|
||||
|
||||
op.drop_table('comments')
|
||||
with op.batch_alter_table('appeal_messages', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_appeal_messages_created_at'))
|
||||
|
||||
op.drop_table('appeal_messages')
|
||||
with op.batch_alter_table('reports', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_reports_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_reports_reported_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_reports_created_at'))
|
||||
batch_op.drop_index('idx_report_status_created')
|
||||
|
||||
op.drop_table('reports')
|
||||
with op.batch_alter_table('appeals', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_appeals_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_appeals_created_at'))
|
||||
|
||||
op.drop_table('appeals')
|
||||
with op.batch_alter_table('users', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_users_username'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_role'))
|
||||
batch_op.drop_index(batch_op.f('ix_users_email'))
|
||||
|
||||
op.drop_table('users')
|
||||
with op.batch_alter_table('partner_sites', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_partner_sites_name'))
|
||||
batch_op.drop_index(batch_op.f('ix_partner_sites_is_active'))
|
||||
|
||||
op.drop_table('partner_sites')
|
||||
with op.batch_alter_table('blacklist', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_username'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_status'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_pt_site'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_normalized_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_email'))
|
||||
batch_op.drop_index(batch_op.f('ix_blacklist_created_at'))
|
||||
batch_op.drop_index('idx_blacklist_username_status')
|
||||
batch_op.drop_index('idx_blacklist_email_status')
|
||||
|
||||
op.drop_table('blacklist')
|
||||
# ### end Alembic commands ###
|
||||
13
run.py
13
run.py
@@ -1,3 +1,4 @@
|
||||
"""应用启动入口"""
|
||||
import os
|
||||
import click
|
||||
from app import create_app, db
|
||||
@@ -13,14 +14,14 @@ def make_shell_context():
|
||||
@click.argument("username")
|
||||
@click.argument("email")
|
||||
@click.argument("password")
|
||||
@click.option("--admin", is_flag=True, help="Flag to create an admin user.")
|
||||
@click.option("--admin", is_flag=True, help="创建管理员用户")
|
||||
def create_user(username, email, password, admin):
|
||||
"""Creates a new user."""
|
||||
"""创建新用户"""
|
||||
if User.query.filter_by(email=email).first():
|
||||
print(f"Error: Email {email} already exists.")
|
||||
print(f"错误: 邮箱 {email} 已存在")
|
||||
return
|
||||
if User.query.filter_by(username=username).first():
|
||||
print(f"Error: Username {username} already exists.")
|
||||
print(f"错误: 用户名 {username} 已存在")
|
||||
return
|
||||
|
||||
user = User(username=username, email=email, status='active')
|
||||
@@ -30,6 +31,6 @@ def create_user(username, email, password, admin):
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
print(f"User {username} created successfully.")
|
||||
print(f"用户 {username} 创建成功")
|
||||
if admin:
|
||||
print("Role: Admin")
|
||||
print("角色: 管理员")
|
||||
|
||||
Reference in New Issue
Block a user