From 4fe71f6561ace28d7df226504a9274f7ddad7078 Mon Sep 17 00:00:00 2001 From: mcbloch Date: Sun, 18 Apr 2021 20:58:18 +0200 Subject: [PATCH] Init commit --- .editorconfig | 18 + .gitignore | 5 + Dockerfile | 12 + LICENSE | 661 +++++++++++++++ MSRS/__init__.py | 1 + MSRS/asgi.py | 16 + MSRS/settings.py | 153 ++++ MSRS/urls.py | 24 + MSRS/wsgi.py | 16 + Makefile | 30 + README.md | 26 + docker-compose.yml | 31 + events/__init__.py | 3 + events/admin.py | 22 + events/apps.py | 5 + events/migrations/0001_initial.py | 33 + events/migrations/0002_auto_20210418_2026.py | 27 + events/migrations/__init__.py | 0 events/models.py | 41 + events/templates/events/index.html | 28 + events/templates/events/registrations.html | 17 + events/templatetags/__init__.py | 0 events/templatetags/events_extras.py | 10 + events/tests.py | 3 + events/urls.py | 10 + events/views.py | 42 + fixtures.yaml | 790 ++++++++++++++++++ identifier.sqlite | 0 manage.py | 21 + oauth/__init__.py | 0 oauth/templates/oauth/failed.html | 11 + oauth/urls.py | 10 + oauth/views.py | 86 ++ requirements.txt | 23 + scripts/wait_for_service | 12 + static/dracula.css | 91 ++ static/main.css | 228 +++++ templates/base.html | 58 ++ users/__init__.py | 0 users/admin.py | 28 + users/forms.py | 77 ++ users/managers.py | 33 + users/migrations/0001_initial.py | 34 + .../0002_seed_admin_and_zeus_board.py | 72 ++ users/migrations/__init__.py | 0 users/models.py | 25 + users/templates/users/profile.html | 19 + users/urls.py | 9 + users/views.py | 9 + web.env | 10 + 50 files changed, 2880 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 MSRS/__init__.py create mode 100644 MSRS/asgi.py create mode 100644 MSRS/settings.py create mode 100644 MSRS/urls.py create mode 100644 MSRS/wsgi.py create mode 100644 Makefile create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100644 events/__init__.py create mode 100644 events/admin.py create mode 100644 events/apps.py create mode 100644 events/migrations/0001_initial.py create mode 100644 events/migrations/0002_auto_20210418_2026.py create mode 100644 events/migrations/__init__.py create mode 100644 events/models.py create mode 100644 events/templates/events/index.html create mode 100644 events/templates/events/registrations.html create mode 100644 events/templatetags/__init__.py create mode 100644 events/templatetags/events_extras.py create mode 100644 events/tests.py create mode 100644 events/urls.py create mode 100644 events/views.py create mode 100644 fixtures.yaml create mode 100644 identifier.sqlite create mode 100755 manage.py create mode 100644 oauth/__init__.py create mode 100644 oauth/templates/oauth/failed.html create mode 100644 oauth/urls.py create mode 100644 oauth/views.py create mode 100644 requirements.txt create mode 100755 scripts/wait_for_service create mode 100644 static/dracula.css create mode 100644 static/main.css create mode 100644 templates/base.html create mode 100644 users/__init__.py create mode 100644 users/admin.py create mode 100644 users/forms.py create mode 100644 users/managers.py create mode 100644 users/migrations/0001_initial.py create mode 100644 users/migrations/0002_seed_admin_and_zeus_board.py create mode 100644 users/migrations/__init__.py create mode 100644 users/models.py create mode 100644 users/templates/users/profile.html create mode 100644 users/urls.py create mode 100644 users/views.py create mode 100644 web.env diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..912ad38 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# https://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab + +[*.py] +indent_style = space +indent_size = 4 + +# 2 spaces in YAML +[*.{yaml,yml}] +indent_style = space +indent_size = 2 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..eceaa75 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +venv/ +.idea/ +**/__pycache__/** +*.sqlite3 +*.pyc diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..90c10c2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.8.5-alpine3.12 + +RUN mkdir code +WORKDIR code + +RUN apk add --no-cache gcc musl-dev linux-headers mariadb-dev + + +COPY requirements.txt requirements.txt +RUN pip install -r requirements.txt + +COPY . . diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..711199f --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + KeRS + Copyright (C) 2020 bestuur + + 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 . + +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 +. diff --git a/MSRS/__init__.py b/MSRS/__init__.py new file mode 100644 index 0000000..01e6d4f --- /dev/null +++ b/MSRS/__init__.py @@ -0,0 +1 @@ +from __future__ import absolute_import, unicode_literals diff --git a/MSRS/asgi.py b/MSRS/asgi.py new file mode 100644 index 0000000..5b602bc --- /dev/null +++ b/MSRS/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for KeRS project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MSRS.settings") + +application = get_asgi_application() diff --git a/MSRS/settings.py b/MSRS/settings.py new file mode 100644 index 0000000..75c2a1e --- /dev/null +++ b/MSRS/settings.py @@ -0,0 +1,153 @@ +""" +Django settings for MSRS project. + +Generated by 'django-admin startproject' using Django 3.0.8. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.getenv( + "SECRET_KEY", "i%k^vq3e#$+d2ap18z1(@%ua@7u*)_$!+++k)22@9x7%^jvd(0" +) + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = os.getenv("DEBUG", "1") == "1" + +_allowed_hosts = os.getenv("ALLOWED_HOSTS") +ALLOWED_HOSTS = _allowed_hosts.split(",") if _allowed_hosts else [] + +# Application definition + +OWN_APPS = ["events", "users", "oauth"] + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", +] + OWN_APPS + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", +] + +ROOT_URLCONF = "MSRS.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [os.path.join(BASE_DIR, "templates")], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ], + }, + }, +] + +WSGI_APPLICATION = "MSRS.wsgi.application" + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +if os.getenv("MSRS_DB_BACKEND", "mysql") == "sqlite3": + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": os.getenv("MSRS_SQLITE_FILE", "msrs.sqlite3"), + } + } +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.mysql", + "NAME": os.getenv("DATABASE_NAME", "msrs"), + "USER": os.getenv("DATABASE_USER", "msrs"), + "PASSWORD": os.getenv("DATABASE_PASSWORD", "msrs"), + "HOST": os.getenv("DATABASE_HOST", "127.0.0.1"), + "PORT": os.getenv("DATABASE_PORT", "3306"), + } + } + +# Password validation +# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + }, +] + +# Internationalization +# https://docs.djangoproject.com/en/3.0/topics/i18n/ + +LANGUAGE_CODE = "nl-be" + +TIME_ZONE = "Europe/Brussels" + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.0/howto/static-files/ + +STATIC_URL = "/static/" +STATICFILES_DIRS = [ + os.path.join(BASE_DIR, "static"), +] + +STATIC_ROOT = os.getenv("STATIC_ROOT") + +# OAuth + +BASE_URL = os.getenv("BASE_URL", "http://localhost:8000") + +AUTH_USER_MODEL = "users.CustomUser" + +_BASE_OAUTH_URL = os.getenv("OAUTH_BASE_URL", "https://adams.ugent.be/oauth") + +OAUTH = { + "USER_API_URI": f"{_BASE_OAUTH_URL}/api/current_user/", + "ACCESS_TOKEN_URI": f"{_BASE_OAUTH_URL}/oauth2/token/", + "AUTHORIZE_URI": f"{_BASE_OAUTH_URL}/oauth2/authorize/", + "REDIRECT_URI": f"{BASE_URL}/login/zeus/authorized", + "CLIENT_ID": os.getenv("OAUTH_CLIENT_ID", "tomtest"), + "CLIENT_SECRET": os.getenv("OAUTH_CLIENT_SECRET", "blargh"), +} diff --git a/MSRS/urls.py b/MSRS/urls.py new file mode 100644 index 0000000..59cd182 --- /dev/null +++ b/MSRS/urls.py @@ -0,0 +1,24 @@ +"""KeRS URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path("", include("events.urls")), + path("admin/", admin.site.urls), + path("login/zeus/", include("oauth.urls")), + path("user/", include("users.urls")), +] diff --git a/MSRS/wsgi.py b/MSRS/wsgi.py new file mode 100644 index 0000000..a046bcd --- /dev/null +++ b/MSRS/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for KeRS project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MSRS.settings") + +application = get_wsgi_application() diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7240977 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +MSRS_DB_BACKEND ?= mysql +MSRS_SQLITE_FILE ?= msrs.sqlite3 + +# Discover virtualenv location +PYTHON ?= $(shell find -mindepth 3 -maxdepth 3 -path "*/bin/python") +ifeq ($(PYTHON),) +$(error No virtualenv found) +endif +VENVBIN := $(dir $(PYTHON)) + + +.PHONY: server celery beat +server: + $(PYTHON) manage.py runserver + +.PHONY: migrations migrate +migrations: + $(PYTHON) manage.py makemigrations +migrate: + $(PYTHON) manage.py migrate + +.PHONY: reset_db rewrite_migrations +reset_db: + @case "$(MSRS_DB_BACKEND)" in \ + mysql) printf "Please drop your MySQL/MariaDB tables and press enter"; read; ;; \ + sqlite3) echo 'rm -f "$(MSRS_SQLITE_FILE)"'; rm -f "$(MSRS_SQLITE_FILE)"; ;; \ + esac + make migrate +rewrite_migrations: + @echo "We have data in production. This is not allowed any more."; exit 1 diff --git a/README.md b/README.md new file mode 100644 index 0000000..1030f4e --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# MSRS - Membership registration system + +## Development + +Install Python and virtualenv if not already available. + +If you choose SQLite3, set the environment variable `MSRS_DB_BACKEND` to sqlite3. To do so, you can +add `export MSRS_DB_BACKEND=sqlite3` to your shell's init file (e.g. `~/.bashrc`) and restart your +shell. + +If you choose MySQL/MariaDB, set up the server, and look in `KeRS/settings.py` for the possible +environment variables you can set (e.g. `DATABASE_NAME`). + +Set up the development environment: + +```bash +python -m virtualenv venv +venv/bin/pip install -r requirements +make migrate +``` + +To run the development server: + +```bash +make +``` diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..6005ed4 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,31 @@ +version: "3" +services: + web: + build: . + ports: + - "8000:8000" + env_file: "web.env" + restart: on-failure + depends_on: + - database + volumes: + - /var/www/msrs/static:/static + command: > + sh -c "./scripts/wait_for_service database 3306 && + python manage.py collectstatic --no-input + python manage.py migrate && + python manage.py runserver 0.0.0.0:8000" + + # Db stuff + database: + image: mariadb:10.5.4-focal + restart: on-failure + environment: + MYSQL_ROOT_PASSWORD: example + MYSQL_DATABASE: msrs + MYSQL_USER: msrs + MYSQL_PASSWORD: msrs + volumes: + - msrsdb:/var/lib/mysql +volumes: + msrsdb: diff --git a/events/__init__.py b/events/__init__.py new file mode 100644 index 0000000..4bd3b15 --- /dev/null +++ b/events/__init__.py @@ -0,0 +1,3 @@ +from django import template + +register = template.Library() diff --git a/events/admin.py b/events/admin.py new file mode 100644 index 0000000..b6562e2 --- /dev/null +++ b/events/admin.py @@ -0,0 +1,22 @@ +from django import forms +from django.contrib import admin + +from .models import Event, EventRegistration + + +class RegistrationFormSet(forms.BaseInlineFormSet): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + +class RegistrationInline(admin.TabularInline): + model = EventRegistration + extra = 1 + formset = RegistrationFormSet + + +class EventAdmin(admin.ModelAdmin): + inlines = [RegistrationInline] + + +admin.site.register(Event, EventAdmin) diff --git a/events/apps.py b/events/apps.py new file mode 100644 index 0000000..3854644 --- /dev/null +++ b/events/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class EventsConfig(AppConfig): + name = 'events' diff --git a/events/migrations/0001_initial.py b/events/migrations/0001_initial.py new file mode 100644 index 0000000..e97a07e --- /dev/null +++ b/events/migrations/0001_initial.py @@ -0,0 +1,33 @@ +# Generated by Django 3.0.8 on 2021-04-18 18:26 + +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone +import model_utils.fields + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Event', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('start_year', models.IntegerField(default=2020)), + ], + ), + migrations.CreateModel( + name='EventRegistration', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), + ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), + ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.Event')), + ], + ), + ] diff --git a/events/migrations/0002_auto_20210418_2026.py b/events/migrations/0002_auto_20210418_2026.py new file mode 100644 index 0000000..dcc0a20 --- /dev/null +++ b/events/migrations/0002_auto_20210418_2026.py @@ -0,0 +1,27 @@ +# Generated by Django 3.0.8 on 2021-04-18 18:26 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('events', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='eventregistration', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), + ), + migrations.AddConstraint( + model_name='eventregistration', + constraint=models.UniqueConstraint(fields=('event', 'user'), name='register_only_once_per_event'), + ), + ] diff --git a/events/migrations/__init__.py b/events/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/events/models.py b/events/models.py new file mode 100644 index 0000000..48507b5 --- /dev/null +++ b/events/models.py @@ -0,0 +1,41 @@ +from django.db import models +from model_utils.models import TimeStampedModel + +from users.models import CustomUser + + +class Event(models.Model): + start_year = models.IntegerField(default=2020) + + def __str__(self): + return f"{self.start_year}-{self.start_year + 1}" + + def count_registrations(self): + return self.eventregistration_set.count() + + def registration_of(self, user): + if not user.is_authenticated: + return None + + registrations = self.eventregistration_set.filter(user=user).all() + if not registrations: + return None + assert ( + len(registrations) == 1 + ), "Registrations should be unique per user and event" + return registrations[0] + + +class EventRegistration(TimeStampedModel): + event = models.ForeignKey(Event, on_delete=models.CASCADE) + user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["event", "user"], name="register_only_once_per_event" + ), + ] + + def __str__(self): + return f"Reservation[{self.user.username}:{self.event.start_year}]" diff --git a/events/templates/events/index.html b/events/templates/events/index.html new file mode 100644 index 0000000..9b3247b --- /dev/null +++ b/events/templates/events/index.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} + +{% load events_extras %} + +{% block title %}Memberships{% endblock %} + +{% block content %} +

Membership

+ +{% if events %} +
    + {% for x in events %} +
  • +

    {{ x.event }} + {% if user.is_staff %} + Modificeren + {% endif %} +

    + + {% include "events/registrations.html" with event=x.event my_registration=x.my_registration %} + +
  • + {% endfor %} +
+{% else %} +

Geen enkel jaar om lid te zijn...? :thinking:

+{% endif %} +{% endblock %} diff --git a/events/templates/events/registrations.html b/events/templates/events/registrations.html new file mode 100644 index 0000000..b2d3e1d --- /dev/null +++ b/events/templates/events/registrations.html @@ -0,0 +1,17 @@ +{% if not my_registration %} +
+{% else %} + +{% endif %} + {% csrf_token %} +

{{ event.count_registrations }} + registratie{% if event.count_registrations != 1 %}s{%endif%}

+ + {% if not user.is_authenticated %} +

Je moet inloggen voor je je kan inschrijven.

+ {% elif not my_registration %} + + {% else %} + + {% endif %} +
diff --git a/events/templatetags/__init__.py b/events/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/events/templatetags/events_extras.py b/events/templatetags/events_extras.py new file mode 100644 index 0000000..abfae11 --- /dev/null +++ b/events/templatetags/events_extras.py @@ -0,0 +1,10 @@ +from django.utils.safestring import mark_safe +from markdown import markdown + +from events import register + + +@register.filter(name='markdown_to_html', needs_autoescape=False) +def markdown_to_html(value): + result = markdown(value, extensions=['codehilite']) + return mark_safe(result) diff --git a/events/tests.py b/events/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/events/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/events/urls.py b/events/urls.py new file mode 100644 index 0000000..812d2d2 --- /dev/null +++ b/events/urls.py @@ -0,0 +1,10 @@ +from django.urls import path + +from . import views + +app_name = "events" +urlpatterns = [ + path("", views.index, name="index"), + path("/register", views.register, name="register"), + path("/deregister", views.deregister, name="deregister"), +] diff --git a/events/views.py b/events/views.py new file mode 100644 index 0000000..69d249b --- /dev/null +++ b/events/views.py @@ -0,0 +1,42 @@ +from django.http import HttpResponse, HttpResponseRedirect +from django.shortcuts import render, get_object_or_404 +from django.urls import reverse + +from .models import Event, EventRegistration + + +def index(request): + events = Event.objects.order_by("-start_year")[:20] + + events_data = [ + { + "event": event, + "my_registration": event.registration_of(request.user), + } + for event in events + ] + return render(request, "events/index.html", {"events": events_data}) + + +def register(request, event_id): + if request.method != "POST": + return HttpResponse(status_code=405) + + event = get_object_or_404(Event, id=event_id) + + event.eventregistration_set.create( + event=event, + user=request.user, + ) + return HttpResponseRedirect(reverse("events:index") + f"#{event.id}") + + +def deregister(request, event_id): + if request.method != "POST": + return HttpResponse(status_code=405) + + registration = get_object_or_404( + EventRegistration, event=event_id, user=request.user + ) + registration.delete() + return HttpResponseRedirect(reverse("events:index") + f"#{event_id}") diff --git a/fixtures.yaml b/fixtures.yaml new file mode 100644 index 0000000..0430bc7 --- /dev/null +++ b/fixtures.yaml @@ -0,0 +1,790 @@ +- model: contenttypes.contenttype + pk: 1 + fields: + app_label: admin + model: logentry +- model: contenttypes.contenttype + pk: 2 + fields: + app_label: auth + model: permission +- model: contenttypes.contenttype + pk: 3 + fields: + app_label: auth + model: group +- model: contenttypes.contenttype + pk: 4 + fields: + app_label: contenttypes + model: contenttype +- model: contenttypes.contenttype + pk: 5 + fields: + app_label: sessions + model: session +- model: contenttypes.contenttype + pk: 6 + fields: + app_label: events + model: event +- model: contenttypes.contenttype + pk: 7 + fields: + app_label: events + model: eventregistration +- model: contenttypes.contenttype + pk: 8 + fields: + app_label: users + model: customuser +- model: contenttypes.contenttype + pk: 9 + fields: + app_label: django_celery_beat + model: crontabschedule +- model: contenttypes.contenttype + pk: 10 + fields: + app_label: django_celery_beat + model: intervalschedule +- model: contenttypes.contenttype + pk: 11 + fields: + app_label: django_celery_beat + model: periodictask +- model: contenttypes.contenttype + pk: 12 + fields: + app_label: django_celery_beat + model: periodictasks +- model: contenttypes.contenttype + pk: 13 + fields: + app_label: django_celery_beat + model: solarschedule +- model: contenttypes.contenttype + pk: 14 + fields: + app_label: django_celery_beat + model: clockedschedule +- model: sessions.session + pk: hj9wkvybqgoq1qcnnydxhwlg9n71p702 + fields: + session_data: ZTQ0NzdhODk3MjhkN2MzNjBkOGU5MzlhZjA5MTk2YzMzYjMwNDdjZjp7Il9hdXRoX3VzZXJfaWQiOiIxIiwiX2F1dGhfdXNlcl9iYWNrZW5kIjoiZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmQiLCJfYXV0aF91c2VyX2hhc2giOiIzZDNiODIzNWI0ODUzYjI1NjY0MTI5MTkxZjIyYzJmOGY4MmFlNjNmIn0= + expire_date: 2020-08-04 22:49:00.102057+00:00 +- model: django_celery_beat.crontabschedule + pk: 1 + fields: + minute: '0' + hour: '4' + day_of_week: '*' + day_of_month: '*' + month_of_year: '*' + timezone: UTC +- model: django_celery_beat.crontabschedule + pk: 3 + fields: + minute: '*' + hour: '*' + day_of_week: '*' + day_of_month: '*' + month_of_year: '*' + timezone: UTC +- model: django_celery_beat.periodictasks + pk: 1 + fields: + last_update: 2020-07-22 00:30:05.069702+00:00 +- model: django_celery_beat.periodictask + pk: 1 + fields: + name: celery.backend_cleanup + task: celery.backend_cleanup + interval: null + crontab: 1 + solar: null + clocked: null + args: '[]' + kwargs: '{}' + queue: null + exchange: null + routing_key: null + headers: '{}' + priority: null + expires: null + expire_seconds: 43200 + one_off: false + start_time: null + enabled: true + last_run_at: null + total_run_count: 0 + date_changed: 2020-07-22 00:27:15.238491+00:00 + description: '' +- model: django_celery_beat.periodictask + pk: 2 + fields: + name: Every minute yeeet + task: KeRS.celery.debug_task + interval: null + crontab: 3 + solar: null + clocked: null + args: '[]' + kwargs: '{}' + queue: null + exchange: null + routing_key: null + headers: '{}' + priority: null + expires: null + expire_seconds: null + one_off: false + start_time: null + enabled: true + last_run_at: 2020-07-22 00:45:00.000965+00:00 + total_run_count: 15 + date_changed: 2020-07-22 00:45:45.060737+00:00 + description: '' +- model: events.event + pk: 1 + fields: + date: 2020-07-23 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 2 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 3 + fields: + date: 2020-07-24 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 4 + fields: + date: 2020-07-25 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 5 + fields: + date: 2020-07-23 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 6 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 7 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 8 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 9 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 10 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 11 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 12 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 13 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 14 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 15 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 16 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 17 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 18 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 19 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 20 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 21 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 22 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 23 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 24 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 25 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 26 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 27 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 28 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 29 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 30 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 31 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 32 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 33 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 34 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 35 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 36 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 37 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 38 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 39 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 40 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: events.event + pk: 41 + fields: + date: 2020-07-22 01:51:45+00:00 + capacity: 10 +- model: auth.permission + pk: 1 + fields: + name: Can add log entry + content_type: 1 + codename: add_logentry +- model: auth.permission + pk: 2 + fields: + name: Can change log entry + content_type: 1 + codename: change_logentry +- model: auth.permission + pk: 3 + fields: + name: Can delete log entry + content_type: 1 + codename: delete_logentry +- model: auth.permission + pk: 4 + fields: + name: Can view log entry + content_type: 1 + codename: view_logentry +- model: auth.permission + pk: 5 + fields: + name: Can add permission + content_type: 2 + codename: add_permission +- model: auth.permission + pk: 6 + fields: + name: Can change permission + content_type: 2 + codename: change_permission +- model: auth.permission + pk: 7 + fields: + name: Can delete permission + content_type: 2 + codename: delete_permission +- model: auth.permission + pk: 8 + fields: + name: Can view permission + content_type: 2 + codename: view_permission +- model: auth.permission + pk: 9 + fields: + name: Can add group + content_type: 3 + codename: add_group +- model: auth.permission + pk: 10 + fields: + name: Can change group + content_type: 3 + codename: change_group +- model: auth.permission + pk: 11 + fields: + name: Can delete group + content_type: 3 + codename: delete_group +- model: auth.permission + pk: 12 + fields: + name: Can view group + content_type: 3 + codename: view_group +- model: auth.permission + pk: 13 + fields: + name: Can add content type + content_type: 4 + codename: add_contenttype +- model: auth.permission + pk: 14 + fields: + name: Can change content type + content_type: 4 + codename: change_contenttype +- model: auth.permission + pk: 15 + fields: + name: Can delete content type + content_type: 4 + codename: delete_contenttype +- model: auth.permission + pk: 16 + fields: + name: Can view content type + content_type: 4 + codename: view_contenttype +- model: auth.permission + pk: 17 + fields: + name: Can add session + content_type: 5 + codename: add_session +- model: auth.permission + pk: 18 + fields: + name: Can change session + content_type: 5 + codename: change_session +- model: auth.permission + pk: 19 + fields: + name: Can delete session + content_type: 5 + codename: delete_session +- model: auth.permission + pk: 20 + fields: + name: Can view session + content_type: 5 + codename: view_session +- model: auth.permission + pk: 21 + fields: + name: Can add event + content_type: 6 + codename: add_event +- model: auth.permission + pk: 22 + fields: + name: Can change event + content_type: 6 + codename: change_event +- model: auth.permission + pk: 23 + fields: + name: Can delete event + content_type: 6 + codename: delete_event +- model: auth.permission + pk: 24 + fields: + name: Can view event + content_type: 6 + codename: view_event +- model: auth.permission + pk: 25 + fields: + name: Can add event registration + content_type: 7 + codename: add_eventregistration +- model: auth.permission + pk: 26 + fields: + name: Can change event registration + content_type: 7 + codename: change_eventregistration +- model: auth.permission + pk: 27 + fields: + name: Can delete event registration + content_type: 7 + codename: delete_eventregistration +- model: auth.permission + pk: 28 + fields: + name: Can view event registration + content_type: 7 + codename: view_eventregistration +- model: auth.permission + pk: 29 + fields: + name: Can add custom user + content_type: 8 + codename: add_customuser +- model: auth.permission + pk: 30 + fields: + name: Can change custom user + content_type: 8 + codename: change_customuser +- model: auth.permission + pk: 31 + fields: + name: Can delete custom user + content_type: 8 + codename: delete_customuser +- model: auth.permission + pk: 32 + fields: + name: Can view custom user + content_type: 8 + codename: view_customuser +- model: auth.permission + pk: 33 + fields: + name: Can add crontab + content_type: 9 + codename: add_crontabschedule +- model: auth.permission + pk: 34 + fields: + name: Can change crontab + content_type: 9 + codename: change_crontabschedule +- model: auth.permission + pk: 35 + fields: + name: Can delete crontab + content_type: 9 + codename: delete_crontabschedule +- model: auth.permission + pk: 36 + fields: + name: Can view crontab + content_type: 9 + codename: view_crontabschedule +- model: auth.permission + pk: 37 + fields: + name: Can add interval + content_type: 10 + codename: add_intervalschedule +- model: auth.permission + pk: 38 + fields: + name: Can change interval + content_type: 10 + codename: change_intervalschedule +- model: auth.permission + pk: 39 + fields: + name: Can delete interval + content_type: 10 + codename: delete_intervalschedule +- model: auth.permission + pk: 40 + fields: + name: Can view interval + content_type: 10 + codename: view_intervalschedule +- model: auth.permission + pk: 41 + fields: + name: Can add periodic task + content_type: 11 + codename: add_periodictask +- model: auth.permission + pk: 42 + fields: + name: Can change periodic task + content_type: 11 + codename: change_periodictask +- model: auth.permission + pk: 43 + fields: + name: Can delete periodic task + content_type: 11 + codename: delete_periodictask +- model: auth.permission + pk: 44 + fields: + name: Can view periodic task + content_type: 11 + codename: view_periodictask +- model: auth.permission + pk: 45 + fields: + name: Can add periodic tasks + content_type: 12 + codename: add_periodictasks +- model: auth.permission + pk: 46 + fields: + name: Can change periodic tasks + content_type: 12 + codename: change_periodictasks +- model: auth.permission + pk: 47 + fields: + name: Can delete periodic tasks + content_type: 12 + codename: delete_periodictasks +- model: auth.permission + pk: 48 + fields: + name: Can view periodic tasks + content_type: 12 + codename: view_periodictasks +- model: auth.permission + pk: 49 + fields: + name: Can add solar event + content_type: 13 + codename: add_solarschedule +- model: auth.permission + pk: 50 + fields: + name: Can change solar event + content_type: 13 + codename: change_solarschedule +- model: auth.permission + pk: 51 + fields: + name: Can delete solar event + content_type: 13 + codename: delete_solarschedule +- model: auth.permission + pk: 52 + fields: + name: Can view solar event + content_type: 13 + codename: view_solarschedule +- model: auth.permission + pk: 53 + fields: + name: Can add clocked + content_type: 14 + codename: add_clockedschedule +- model: auth.permission + pk: 54 + fields: + name: Can change clocked + content_type: 14 + codename: change_clockedschedule +- model: auth.permission + pk: 55 + fields: + name: Can delete clocked + content_type: 14 + codename: delete_clockedschedule +- model: auth.permission + pk: 56 + fields: + name: Can view clocked + content_type: 14 + codename: view_clockedschedule +- model: users.customuser + pk: 1 + fields: + password: pbkdf2_sha256$180000$GH6m0IflBlrZ$Wqf06UOx6ONiiCKqcBhMfU8qIfPRYmZ4IE8T4Lg0+IY= + last_login: 2020-07-21 22:49:00.100211+00:00 + is_superuser: true + zeus_id: 0 + is_staff: true + username: admin + student_number: '' + real_name: '' + date_joined: 2020-07-21 22:48:51.055553+00:00 + groups: [] + user_permissions: [] +- model: users.customuser + pk: 2 + fields: + password: pbkdf2_sha256$180000$ELhNJnyUYwd2$ovCak9NZgTBERj7L9wyAhw+IjSHGSCjeJoePQRLwIdc= + last_login: null + is_superuser: false + zeus_id: null + is_staff: false + username: test + student_number: '' + real_name: '' + date_joined: 2020-07-21 22:50:11.587910+00:00 + groups: [] + user_permissions: [] +- model: users.customuser + pk: 3 + fields: + password: pbkdf2_sha256$180000$gSwTHSqwniBC$SsAEEGlVkHPq2njxNPXKqc9bT9zBecSxdT0MPGkVzD8= + last_login: null + is_superuser: false + zeus_id: null + is_staff: true + username: test staff + student_number: '' + real_name: '' + date_joined: 2020-07-21 22:50:28.026085+00:00 + groups: [] + user_permissions: [] +- model: admin.logentry + pk: 1 + fields: + action_time: 2020-07-21 22:50:11.727868+00:00 + user: 1 + content_type: 8 + object_id: '2' + object_repr: test + action_flag: 1 + change_message: '[{"added": {}}]' +- model: admin.logentry + pk: 2 + fields: + action_time: 2020-07-21 22:50:28.149398+00:00 + user: 1 + content_type: 8 + object_id: '3' + object_repr: test staff + action_flag: 1 + change_message: '[{"added": {}}]' +- model: admin.logentry + pk: 3 + fields: + action_time: 2020-07-22 00:28:33.300409+00:00 + user: 1 + content_type: 9 + object_id: '2' + object_repr: 0 0 * * * (m/h/d/dM/MY) UTC + action_flag: 1 + change_message: '[{"added": {}}]' +- model: admin.logentry + pk: 4 + fields: + action_time: 2020-07-22 00:28:54.879321+00:00 + user: 1 + content_type: 9 + object_id: '2' + object_repr: 0 0 * * * (m/h/d/dM/MY) UTC + action_flag: 3 + change_message: '' +- model: admin.logentry + pk: 5 + fields: + action_time: 2020-07-22 00:29:19.340267+00:00 + user: 1 + content_type: 9 + object_id: '3' + object_repr: '* * * * * (m/h/d/dM/MY) UTC' + action_flag: 1 + change_message: '[{"added": {}}]' +- model: admin.logentry + pk: 6 + fields: + action_time: 2020-07-22 00:30:05.071835+00:00 + user: 1 + content_type: 11 + object_id: '2' + object_repr: 'Every minute yeeet: * * * * * (m/h/d/dM/MY) UTC' + action_flag: 1 + change_message: '[{"added": {}}]' diff --git a/identifier.sqlite b/identifier.sqlite new file mode 100644 index 0000000..e69de29 diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..8729b5e --- /dev/null +++ b/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MSRS.settings") + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/oauth/__init__.py b/oauth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/oauth/templates/oauth/failed.html b/oauth/templates/oauth/failed.html new file mode 100644 index 0000000..aee4cd6 --- /dev/null +++ b/oauth/templates/oauth/failed.html @@ -0,0 +1,11 @@ +{% extends "base.html" %} + +{% block title %}Login Failed{% endblock %} + +{% block content %} +

Login Failed

+ + {% if error %} +

{{ error }}

+ {% endif %} +{% endblock %} diff --git a/oauth/urls.py b/oauth/urls.py new file mode 100644 index 0000000..11afb10 --- /dev/null +++ b/oauth/urls.py @@ -0,0 +1,10 @@ +from django.contrib.auth import logout +from django.urls import path + +from . import views + +app_name = "oauth" +urlpatterns = [ + path('register', views.register, name='login'), + path('authorized', views.register_callback), +] diff --git a/oauth/views.py b/oauth/views.py new file mode 100644 index 0000000..6cca9c1 --- /dev/null +++ b/oauth/views.py @@ -0,0 +1,86 @@ +import logging + +import requests +from django.conf import settings +from django.contrib.auth import login +from django.http.request import HttpRequest +from django.shortcuts import redirect, render + +import users +from users.models import CustomUser + +logger = logging.getLogger(__file__) + + +class OAuthException(Exception): + pass + + +def register(_): + RESPONSE_TYPE = 'code' + return redirect(f'{settings.OAUTH["AUTHORIZE_URI"]}?' + f'response_type={RESPONSE_TYPE}&' + f'client_id={settings.OAUTH["CLIENT_ID"]}&' + f'redirect_uri={settings.OAUTH["REDIRECT_URI"]}') + + +def register_callback(req: HttpRequest): + if 'code' not in req.GET or 'error' in req.GET: + error = req.GET['error'] if 'error' in req.GET else None + return login_fail(req, error) + + try: + access_token = get_access_token(req.GET['code']) + user_info = get_user_info(access_token) + + logger.debug(f'Succesfully authenticated user: {user_info["username"]} with id: {user_info["id"]}') + + validated_user = validate_user(user_info['id'], user_info['username']) + login(req, validated_user) + return redirect('/') + except OAuthException as e: + logger.error(e) + return login_fail(req, str(e)) + + +def login_fail(request, error: str = None): + return render(request, "oauth/failed.html", {'error': error}) + + +def validate_user(zeus_id, username) -> CustomUser: + try: + user = CustomUser.objects.get(zeus_id=zeus_id) + user.username = username + user.save() + return user + except users.models.CustomUser.DoesNotExist: + return CustomUser.objects.create_user(zeus_id, username) + + +def get_access_token(code): + response = requests.post( + settings.OAUTH["ACCESS_TOKEN_URI"], + data={'code': code, + 'grant_type': 'authorization_code', + 'client_id': settings.OAUTH["CLIENT_ID"], + 'client_secret': settings.OAUTH["CLIENT_SECRET"], + 'redirect_uri': settings.OAUTH["REDIRECT_URI"]}) + if response.status_code != 200: + raise OAuthException( + f'Status code {response.status_code} when requesting access token.\nresponse: {response.text}') + if 'access_token' not in response.json(): + raise OAuthException('Got status code 200 but no access_token') + return response.json()['access_token'] + + +def get_user_info(access_token): + response = requests.get( + settings.OAUTH["USER_API_URI"], + headers={'Authorization': f'Bearer {access_token}'}, + ) + if response.status_code != 200: + raise OAuthException( + f'Status code {response.status_code} when requesting user info.\nresponse: {response.text}') + if 'username' not in response.json() or 'id' not in response.json(): + raise OAuthException(f'username and id are expected values: {response.json()}') + return response.json() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..12b3348 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ +amqp==2.6.0 +asgiref==3.2.10 +billiard==3.6.3.0 +certifi==2020.6.20 +chardet==3.0.4 +Django==3.0.8 +django-celery-beat==2.0.0 +django_model_utils==4.1.1 +django-timezone-field==4.0 +future==0.18.2 +idna==2.10 +markdown==3.2.2 +mysqlclient==2.0.1 +Pygments>=2.3.1 +python-crontab==2.5.1 +python-dateutil==2.8.1 +pytz==2020.1 +PyYAML==5.3.1 +requests==2.24.0 +six==1.15.0 +sqlparse==0.3.1 +urllib3==1.25.9 +vine==1.3.0 diff --git a/scripts/wait_for_service b/scripts/wait_for_service new file mode 100755 index 0000000..1ee8a77 --- /dev/null +++ b/scripts/wait_for_service @@ -0,0 +1,12 @@ +#!/bin/sh + +if [ $# -ne 2 ]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +while ! nc -z "$1" "$2"; do + echo "$1:$2 not yet available, waiting" + sleep 1 +done +echo "Done" diff --git a/static/dracula.css b/static/dracula.css new file mode 100644 index 0000000..1b12a63 --- /dev/null +++ b/static/dracula.css @@ -0,0 +1,91 @@ +/* Dracula Theme v1.2.5 + * + * https://github.com/zenorocha/dracula-theme + * + * Copyright 2016, All rights reserved + * + * Code licensed under the MIT license + * http://zenorocha.mit-license.org + * + * @author Rob G + * @author Chris Bracco + * @author Zeno Rocha + */ + + .codehilite .hll { background-color: #f1fa8c } + .codehilite { background: #282a36; color: #f8f8f2 } + .codehilite .c { color: #6272a4 } /* Comment */ + .codehilite .err { color: #f8f8f2 } /* Error */ + .codehilite .g { color: #f8f8f2 } /* Generic */ + .codehilite .k { color: #ff79c6 } /* Keyword */ + .codehilite .l { color: #f8f8f2 } /* Literal */ + .codehilite .n { color: #f8f8f2 } /* Name */ + .codehilite .o { color: #ff79c6 } /* Operator */ + .codehilite .x { color: #f8f8f2 } /* Other */ + .codehilite .p { color: #f8f8f2 } /* Punctuation */ + .codehilite .ch { color: #6272a4 } /* Comment.Hashbang */ + .codehilite .cm { color: #6272a4 } /* Comment.Multiline */ + .codehilite .cp { color: #ff79c6 } /* Comment.Preproc */ + .codehilite .cpf { color: #6272a4 } /* Comment.PreprocFile */ + .codehilite .c1 { color: #6272a4 } /* Comment.Single */ + .codehilite .cs { color: #6272a4 } /* Comment.Special */ + .codehilite .gd { color: #8b080b } /* Generic.Deleted */ + .codehilite .ge { color: #f8f8f2; text-decoration: underline } /* Generic.Emph */ + .codehilite .gr { color: #f8f8f2 } /* Generic.Error */ + .codehilite .gh { color: #f8f8f2; font-weight: bold } /* Generic.Heading */ + .codehilite .gi { color: #f8f8f2; font-weight: bold } /* Generic.Inserted */ + .codehilite .go { color: #44475a } /* Generic.Output */ + .codehilite .gp { color: #f8f8f2 } /* Generic.Prompt */ + .codehilite .gs { color: #f8f8f2 } /* Generic.Strong */ + .codehilite .gu { color: #f8f8f2; font-weight: bold } /* Generic.Subheading */ + .codehilite .gt { color: #f8f8f2 } /* Generic.Traceback */ + .codehilite .kc { color: #ff79c6 } /* Keyword.Constant */ + .codehilite .kd { color: #8be9fd; font-style: italic } /* Keyword.Declaration */ + .codehilite .kn { color: #ff79c6 } /* Keyword.Namespace */ + .codehilite .kp { color: #ff79c6 } /* Keyword.Pseudo */ + .codehilite .kr { color: #ff79c6 } /* Keyword.Reserved */ + .codehilite .kt { color: #8be9fd } /* Keyword.Type */ + .codehilite .ld { color: #f8f8f2 } /* Literal.Date */ + .codehilite .m { color: #bd93f9 } /* Literal.Number */ + .codehilite .s { color: #f1fa8c } /* Literal.String */ + .codehilite .na { color: #50fa7b } /* Name.Attribute */ + .codehilite .nb { color: #8be9fd; font-style: italic } /* Name.Builtin */ + .codehilite .nc { color: #50fa7b } /* Name.Class */ + .codehilite .no { color: #f8f8f2 } /* Name.Constant */ + .codehilite .nd { color: #f8f8f2 } /* Name.Decorator */ + .codehilite .ni { color: #f8f8f2 } /* Name.Entity */ + .codehilite .ne { color: #f8f8f2 } /* Name.Exception */ + .codehilite .nf { color: #50fa7b } /* Name.Function */ + .codehilite .nl { color: #8be9fd; font-style: italic } /* Name.Label */ + .codehilite .nn { color: #f8f8f2 } /* Name.Namespace */ + .codehilite .nx { color: #f8f8f2 } /* Name.Other */ + .codehilite .py { color: #f8f8f2 } /* Name.Property */ + .codehilite .nt { color: #ff79c6 } /* Name.Tag */ + .codehilite .nv { color: #8be9fd; font-style: italic } /* Name.Variable */ + .codehilite .ow { color: #ff79c6 } /* Operator.Word */ + .codehilite .w { color: #f8f8f2 } /* Text.Whitespace */ + .codehilite .mb { color: #bd93f9 } /* Literal.Number.Bin */ + .codehilite .mf { color: #bd93f9 } /* Literal.Number.Float */ + .codehilite .mh { color: #bd93f9 } /* Literal.Number.Hex */ + .codehilite .mi { color: #bd93f9 } /* Literal.Number.Integer */ + .codehilite .mo { color: #bd93f9 } /* Literal.Number.Oct */ + .codehilite .sa { color: #f1fa8c } /* Literal.String.Affix */ + .codehilite .sb { color: #f1fa8c } /* Literal.String.Backtick */ + .codehilite .sc { color: #f1fa8c } /* Literal.String.Char */ + .codehilite .dl { color: #f1fa8c } /* Literal.String.Delimiter */ + .codehilite .sd { color: #f1fa8c } /* Literal.String.Doc */ + .codehilite .s2 { color: #f1fa8c } /* Literal.String.Double */ + .codehilite .se { color: #f1fa8c } /* Literal.String.Escape */ + .codehilite .sh { color: #f1fa8c } /* Literal.String.Heredoc */ + .codehilite .si { color: #f1fa8c } /* Literal.String.Interpol */ + .codehilite .sx { color: #f1fa8c } /* Literal.String.Other */ + .codehilite .sr { color: #f1fa8c } /* Literal.String.Regex */ + .codehilite .s1 { color: #f1fa8c } /* Literal.String.Single */ + .codehilite .ss { color: #f1fa8c } /* Literal.String.Symbol */ + .codehilite .bp { color: #f8f8f2; font-style: italic } /* Name.Builtin.Pseudo */ + .codehilite .fm { color: #50fa7b } /* Name.Function.Magic */ + .codehilite .vc { color: #8be9fd; font-style: italic } /* Name.Variable.Class */ + .codehilite .vg { color: #8be9fd; font-style: italic } /* Name.Variable.Global */ + .codehilite .vi { color: #8be9fd; font-style: italic } /* Name.Variable.Instance */ + .codehilite .vm { color: #8be9fd; font-style: italic } /* Name.Variable.Magic */ + .codehilite .il { color: #bd93f9 } /* Literal.Number.Integer.Long */ diff --git a/static/main.css b/static/main.css new file mode 100644 index 0000000..b9229b0 --- /dev/null +++ b/static/main.css @@ -0,0 +1,228 @@ +:root { + --primary: #0f506f; + --background: #211f1f; + --button-ok: hsl(0, 0%, 14%); + --button-cancel: #80342d; +} + +body { + background: var(--background); + color: #999; + margin: 0; + font-family: monospace; +} + +input, textarea, button { + font-family: inherit; + font-size: inherit; +} + +a { + color: #afafaf; +} + +h3 { + font-weight: normal; +} + + +header { + color: var(--background); + background-color: var(--primary); +} + +header h1 { + margin: 0; + font-size: 120%; +} + +h1 a { + color: inherit; + text-decoration: none; + display: block; + padding: 10px; +} + +nav { + background-color: rgba(0, 0, 0, 0.1); +} + +nav ul { + margin: 0; + padding: 0; +} + +nav li { + list-style-type: none; + display: inline-block; + margin: 0 10px; +} + +nav li:first-child { + margin-left: 0; +} + +nav li:last-child { + margin-right: 0; +} + +nav span, nav a { + display: inline-block; + padding: 10px 1vw; +} + +nav a { + text-decoration: none; + color: black; +} + +header a { + transition: background-color 0.1s; + background-color: rgba(255, 255, 255, 0); +} + +header a:hover, header a:focus, header a:active { + background-color: rgba(255, 255, 255, 0.3); +} + +h1 a:hover, h1 a:focus, h1 a:active { + background-color: rgba(255, 255, 255, 0.1); +} + +.text--important { + color: #e74c3c; +} + +button.cancel { + background-color: var(--button-cancel); + color: white; +} + +button:focus.cancel { + background-color: #c0392b; +} + +/*change the layout of the navigation bar for all the screens +that have a width less or equal than 500px*/ + +@media only screen and (max-width: 750px) { + nav li { + margin: 0; + } + + nav span, nav a { + padding: 10px; + } +} + +@media only screen and (min-width: 750px) { + body { + font-size: 18px; + } + + .align { + display: block; + margin-left: auto; + margin-right: auto; + width: 50%; + min-width: 750px; + } +} + +.alignLeft { + float: left; + text-align: left; +} + +.alignRight { + float: right; + text-align: right; +} + +main { + padding: 10px; +} + +input { + width: 100%; +} + +input[type=text] { + width: 100%; + padding: 12px 20px; + margin: 8px 0; + box-sizing: border-box; +} + +.deemphasized { + color: #421b08; +} + +main ul { + padding: 0; +} + +main li { + list-style-type: none; + margin: 3em 0; +} + +main li:first-child { + margin-top: 2em; +} + +main li:last-child { + margin-bottom: 2em; +} + +select, +input, +textarea, +button { + width: 100%; + line-height: 1.5; + padding: 15px 10px; + border: 1px solid hsl(0, 0%, 10%); + color: #afafaf; + background: var(--button-ok); + transition: background-color 0.1s cubic-bezier(.22, .61, .36, 1), + transform 0.2s cubic-bezier(.22, .61, .36, 1); +} + +textarea { + height: 170px; +} + +::placeholder { + color: #808080; + opacity: 0.8; +} + +/* On focus styling */ +select:focus, +input:focus, +textarea:focus, +button:active { + background: hsl(0, 0%, 20%); +} + +select:focus, +input:focus, +textarea:focus +button:active { + transform: scale(1.02); +} + +/* Hover styling */ +button:hover:not([disabled]) { + cursor: pointer; +} + +footer { + color: #777777; + padding: 10px; +} + +footer a { + color: #888888; +} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..a508174 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,58 @@ +{% load static %} + + + + + + {% block title %}{% endblock %} – MSRS + + + {% block styles %}{% endblock %} + + + +
+

Zeus WPI Membership registration system

+ +
+
+ {% block content %}{% endblock %} +
+ + + diff --git a/users/__init__.py b/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/users/admin.py b/users/admin.py new file mode 100644 index 0000000..29fc6e7 --- /dev/null +++ b/users/admin.py @@ -0,0 +1,28 @@ +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin + +from .forms import CustomUserCreationForm, CustomUserChangeForm +from .models import CustomUser + + +class CustomUserAdmin(UserAdmin): + add_form = CustomUserCreationForm + form = CustomUserChangeForm + model = CustomUser + list_display = ('username', 'is_staff', 'is_superuser') + list_filter = ('username', 'is_staff') + fieldsets = ( + (None, {'fields': ('username', 'password',)}), + ('Permissions', {'fields': ('is_staff', 'is_superuser')}), + ) + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('username', 'password1', 'password2', 'is_staff')} + ), + ) + search_fields = ('username',) + ordering = ('username',) + + +admin.site.register(CustomUser, CustomUserAdmin) diff --git a/users/forms.py b/users/forms.py new file mode 100644 index 0000000..60f32ac --- /dev/null +++ b/users/forms.py @@ -0,0 +1,77 @@ +from django.contrib import admin +from django.contrib.auth.forms import UserCreationForm, UserChangeForm +from django.forms import ModelForm, TextInput + +from .models import CustomUser + + +class CustomUserCreationForm(UserCreationForm): + class Meta(UserCreationForm): + model = CustomUser + fields = ('username',) + + +class CustomUserChangeForm(UserChangeForm): + class Meta: + model = CustomUser + fields = ('username',) + + +# Add user to groups in django admin + +from django import forms +from django.contrib.auth import get_user_model +from django.contrib.admin.widgets import FilteredSelectMultiple +from django.contrib.auth.models import Group + +User = get_user_model() + + +# Create ModelForm based on the Group model. +class GroupAdminForm(forms.ModelForm): + class Meta: + model = Group + exclude = [] + + # Add the users field. + users = forms.ModelMultipleChoiceField( + queryset=User.objects.all(), + required=False, + # Use the pretty 'filter_horizontal widget'. + widget=FilteredSelectMultiple('users', False) + ) + + def __init__(self, *args, **kwargs): + # Do the normal form initialisation. + super(GroupAdminForm, self).__init__(*args, **kwargs) + # If it is an existing group (saved objects have a pk). + if self.instance.pk: + # Populate the users field with the current Group users. + self.fields['users'].initial = self.instance.user_set.all() + + def save_m2m(self): + # Add the users to the Group. + self.instance.user_set.set(self.cleaned_data['users']) + + def save(self, *args, **kwargs): + # Default save + instance = super(GroupAdminForm, self).save() + # Save many-to-many data + self.save_m2m() + return instance + + +# Unregister the original Group admin. +admin.site.unregister(Group) + + +# Create a new Group admin. +class GroupAdmin(admin.ModelAdmin): + # Use our custom form. + form = GroupAdminForm + # Filter permissions horizontal as well. + filter_horizontal = ['permissions'] + + +# Register the new Group ModelAdmin. +admin.site.register(Group, GroupAdmin) diff --git a/users/managers.py b/users/managers.py new file mode 100644 index 0000000..bdf2ec7 --- /dev/null +++ b/users/managers.py @@ -0,0 +1,33 @@ +from django.contrib.auth.base_user import BaseUserManager +from django.utils.translation import ugettext_lazy as _ + + +class CustomUserManager(BaseUserManager): + """ + Custom user model manager where email is the unique identifiers + for authentication instead of usernames. + """ + + def create_user(self, zeus_id, username, password=None, **extra_fields): + """ + Create and save a User with the given email and password. + """ + if zeus_id is None or username is None: + raise ValueError(_('The zeus_id and username must be set')) + user = self.model(zeus_id=zeus_id, username=username, password=password, **extra_fields) + user.set_password(password) + user.save() + return user + + def create_superuser(self, zeus_id, username, password, **extra_fields): + """ + Create and save a SuperUser with the given email and password. + """ + extra_fields.setdefault('is_staff', True) + extra_fields.setdefault('is_superuser', True) + + if extra_fields.get('is_staff') is not True: + raise ValueError(_('Superuser must have is_staff=True.')) + if extra_fields.get('is_superuser') is not True: + raise ValueError(_('Superuser must have is_superuser=True.')) + return self.create_user(zeus_id, username, password, **extra_fields) diff --git a/users/migrations/0001_initial.py b/users/migrations/0001_initial.py new file mode 100644 index 0000000..cde0241 --- /dev/null +++ b/users/migrations/0001_initial.py @@ -0,0 +1,34 @@ +# Generated by Django 3.0.8 on 2021-04-18 18:26 + +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0011_update_proxy_permissions'), + ] + + operations = [ + migrations.CreateModel( + name='CustomUser', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('zeus_id', models.IntegerField(null=True, unique=True)), + ('is_staff', models.BooleanField(default=False)), + ('username', models.CharField(max_length=50, unique=True)), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now)), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/users/migrations/0002_seed_admin_and_zeus_board.py b/users/migrations/0002_seed_admin_and_zeus_board.py new file mode 100644 index 0000000..c9dc01b --- /dev/null +++ b/users/migrations/0002_seed_admin_and_zeus_board.py @@ -0,0 +1,72 @@ +# Created manually + +import logging +import os + +from django.conf import settings +from django.contrib.auth import get_user_model +from django.core.management.sql import emit_post_migrate_signal +from django.db import migrations +from django.utils import timezone + +logger = logging.getLogger(__name__) + +ENV_USERNAME = 'KERS_ADMIN_USERNAME' +ENV_PASSWORD = 'KERS_ADMIN_PASSWORD' + + +def create_superuser(apps, schema_editor): + superuser = get_user_model()( + is_superuser=True, + is_staff=True, + username=os.environ.get(ENV_USERNAME, 'admin'), + last_login=timezone.now(), + ) + + dev_password = 'admin' + password = os.environ.get(ENV_PASSWORD, dev_password) + if password == dev_password: + log = logger.warning if settings.DEBUG else logger.error + log( + f"Admin password is '{password}'. This is not for use in production. Set environment variable {ENV_PASSWORD} to choose a different password.") + if not settings.DEBUG: + raise Exception("Development admin password used in production") + + superuser.set_password(password) + superuser.save() + + +kers_group_permissions = { + "Bestuur": [ + "add_event", + "delete_event", + "change_event", + ] +} + + +def add_group_permissions(apps, schema_editor): + db_alias = schema_editor.connection.alias + emit_post_migrate_signal(2, False, db_alias) + + Group = apps.get_model('auth', 'Group') + Permission = apps.get_model('auth', 'Permission') + + for group in kers_group_permissions: + role, created = Group.objects.get_or_create(name=group) + logger.info(f'{group} Group {"created" if created else "exists"}') + for perm in kers_group_permissions[group]: + role.permissions.add(Permission.objects.get(codename=perm)) + logger.info(f'Permitting {group} to {perm}') + role.save() + + +class Migration(migrations.Migration): + dependencies = [ + ('users', '0001_initial'), + ] + + operations = [ + migrations.RunPython(create_superuser), + migrations.RunPython(add_group_permissions), + ] diff --git a/users/migrations/__init__.py b/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/users/models.py b/users/models.py new file mode 100644 index 0000000..3038c00 --- /dev/null +++ b/users/models.py @@ -0,0 +1,25 @@ +from django.contrib.auth.base_user import AbstractBaseUser +from django.db import models +from django.contrib.auth.models import User, PermissionsMixin +from django.utils import timezone + +from users.managers import CustomUserManager + + +class CustomUser(AbstractBaseUser, PermissionsMixin): + zeus_id = models.IntegerField(unique=True, null=True) + is_staff = models.BooleanField(default=False) + username = models.CharField(max_length=50, unique=True) # zeus username + + date_joined = models.DateTimeField(default=timezone.now) + + USERNAME_FIELD = 'username' + REQUIRED_FIELDS = ['zeus_id'] + + objects = CustomUserManager() + + def __str__(self): + return self.username + + def __repr__(self): + return "".format(self.username) diff --git a/users/templates/users/profile.html b/users/templates/users/profile.html new file mode 100644 index 0000000..fced0b7 --- /dev/null +++ b/users/templates/users/profile.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} + +{% block title %}Profiel{% endblock %} + +{% block content %} +

Profiel

+ {% if user.is_authenticated %} +

Gebruikersnaam: {{ user.username }}

+ +
+ {% csrf_token %} + {{ form }} + +
+ {% else %} +

Niet ingelogd

+ {% endif %} +{% endblock %} + diff --git a/users/urls.py b/users/urls.py new file mode 100644 index 0000000..ab041b1 --- /dev/null +++ b/users/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views + +app_name = "users" + +urlpatterns = [ + path('logout', views.logout_view, name="logout") +] diff --git a/users/views.py b/users/views.py new file mode 100644 index 0000000..9786e19 --- /dev/null +++ b/users/views.py @@ -0,0 +1,9 @@ +from django.contrib.auth import logout +from django.shortcuts import redirect +from django.urls import reverse + + +def logout_view(request): + logout(request) + + return redirect(reverse("events:index")) diff --git a/web.env b/web.env new file mode 100644 index 0000000..13b0e8c --- /dev/null +++ b/web.env @@ -0,0 +1,10 @@ +DATABASE_HOST=database +SECRET_KEY=REPLACEME +DEBUG=1 +BASE_URL=http://localhost:8000 +OAUTH_CLIENT_ID=REPLACEME +OAUTH_CLIENT_SECRET=REPLACEME +KERS_ADMIN_USERNAME=replaceme +KERS_ADMIN_PASSWORD=replaceme +ALLOWED_HOSTS=localhost +STATIC_ROOT=/static