diff --git a/.env.template b/.env.template index 2e73bc0..0706ee1 100644 --- a/.env.template +++ b/.env.template @@ -14,8 +14,8 @@ CLIENT_SECRET= FACEBOOK_CLIENT_ID= FACEBOOK_CLIENT_SECRET= -POSTGRES_USER= -POSTGRES_PASSWORD= -POSTGRES_HOST= -POSTGRES_DB= -POSTGRES_PORT= \ No newline at end of file +POSTGRES_USER=postgres +POSTGRES_PASSWORD=postgres +POSTGRES_HOST=localhost +POSTGRES_DB=unbtv +POSTGRES_PORT= diff --git a/.github/workflows/code-analysis.yml b/.github/workflows/code-analysis.yml index fb14b7b..d11010d 100644 --- a/.github/workflows/code-analysis.yml +++ b/.github/workflows/code-analysis.yml @@ -4,6 +4,7 @@ on: push jobs: sonarcloud: runs-on: ubuntu-latest + environment: actions services: postgres: @@ -45,6 +46,13 @@ jobs: POSTGRES_HOST: localhost POSTGRES_DB: postgres POSTGRES_PORT: 5432 + SECRET: nono + ALGORITHM: HS256 + MAIL_USERNAME: unbtv@gmail.com + MAIL_PASSWORD: 777 + MAIL_FROM: unbtv@gmail.com + MAIL_PORT: 587 + MAIL_SERVER: smtp.gmail.com - name: Gera arquivos de testes no formato .xml run: python3 -m coverage xml @@ -54,4 +62,4 @@ jobs: uses: SonarSource/sonarcloud-github-action@master env: GITHUB_TOKEN: ${{ secrets.API_TOKEN_GITHUB }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} \ No newline at end of file + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..ee76090 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,20 @@ +name: Trigger Fork Workflow + +on: + push: + branches: + - main + - develop + +jobs: + trigger-workflow: + runs-on: ubuntu-latest + environment: actions + + steps: + - name: Trigger workflow in forked repo + run: | + curl -X POST https://api.github.com/repos/victorleaoo/2024.1-UnB-TV-Users/dispatches \ + -H 'Accept: application/vnd.github.everest-preview+json' \ + -H 'Authorization: token ${{ secrets.API_TOKEN_GITHUB }}' \ + --data '{"event_type": "Trigger Workflow", "client_payload": { "repository": "'"$GITHUB_REPOSITORY"'" }}' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cd1250b..fec0843 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: Release +name: Export de métricas on: pull_request: @@ -6,35 +6,44 @@ on: - main - develop types: [ closed ] - + jobs: release: if: github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'NOT RELEASE') == false runs-on: "ubuntu-latest" - + environment: actions + steps: - - uses: actions/checkout@v2 - with: + - uses: actions/checkout@v3 + with: fetch-depth: 0 + + - name: Install dotenv + run: pip install python-dotenv packaging + + - name: Cria arquivo .env + run: | + touch ./sonar_scripts/.env + echo GITHUB_TOKEN=${{ secrets.API_TOKEN_GITHUB }} >> ./sonar_scripts/.env + echo RELEASE_MAJOR=${{ contains(github.event.pull_request.labels.*.name, 'MAJOR RELEASE') }} >> ./sonar_scripts/.env + echo RELEASE_MINOR=${{ contains(github.event.pull_request.labels.*.name, 'MINOR RELEASE') }} >> ./sonar_scripts/.env + echo RELEASE_FIX=${{ contains(github.event.pull_request.labels.*.name, 'FIX RELEASE') }} >> ./sonar_scripts/.env + echo DEVELOP=${{ contains(github.event.pull_request.labels.*.name, 'DEVELOP') }} >> ./sonar_scripts/.env + + - name: Criar diretório + run: mkdir -p analytics-raw-data - - name: Cria arquivo .env - run: | - touch ./scripts/.env - echo TOKEN=${{ secrets.API_TOKEN_GITHUB }} >> ./scripts/.env - echo RELEASE_MAJOR=${{ contains(github.event.pull_request.labels.*.name, 'MAJOR RELEASE') }} >> ./scripts/.env - echo RELEASE_MINOR=${{ contains(github.event.pull_request.labels.*.name, 'MINOR RELEASE') }} >> ./scripts/.env - echo RELEASE_FIX=${{ contains(github.event.pull_request.labels.*.name, 'FIX RELEASE') }} >> ./scripts/.env - echo DEVELOP=${{ contains(github.event.pull_request.labels.*.name, 'DEVELOP') }} >> ./scripts/.env + - name: Coletar métricas no SonarCloud + run: python ./sonar_scripts/parser.py - - name: Gera release e envia métricas para repositório de DOC - run: | - cd scripts && yarn install && node release.js - git config --global user.email "${{secrets.GIT_USER_EMAIL}}" - git config --global user.name "${{secrets.GIT_USER_NAME}}" - git clone --single-branch --branch main "https://x-access-token:${{secrets.API_TOKEN_GITHUB}}@github.com/fga-eps-mds/${{secrets.GIT_DOC_REPO}}" ${{secrets.GIT_DOC_REPO}} - mkdir -p ${{secrets.GIT_DOC_REPO}}/analytics-raw-data - cp -R analytics-raw-data/*.json ${{secrets.GIT_DOC_REPO}}/analytics-raw-data - cd ${{secrets.GIT_DOC_REPO}} - git add . - git commit -m "Adicionando métricas do repositório ${{ github.event.repository.name }} ${{ github.ref_name }}" - git push \ No newline at end of file + - name: Envia métricas para repo de Doc + run: | + git config --global user.email "${{secrets.USER_EMAIL}}" + git config --global user.name "${{secrets.USER_NAME}}" + git clone --single-branch --branch main "https://x-access-token:${{secrets.API_TOKEN_GITHUB}}@github.com/fga-eps-mds/2024.1-UnB-TV-DOC" doc + mkdir -p doc/analytics-raw-data + cp -R analytics-raw-data/*.json doc/analytics-raw-data + cd doc + git add . + git commit -m "Adicionando métricas do repositório ${{ github.event.repository.name }} ${{ github.ref_name }}" + git push diff --git a/.gitignore b/.gitignore index 44447c7..71be848 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ data/postgress .pytest_cache data .coverage -.vercel +*junit* +.vercel \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e38a7b3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,687 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. + + +ADDITIONAL TERMS: +-------------------- + +As a special exception, you are not permitted to use, distribute, or modify this software for commercial purposes without express written permission from the copyright holders. + +Commercial purposes include, but are not limited to: +- Selling or licensing the software for a fee. +- Using the software as part of a paid service or product. +- Any other monetized use of the software. + +For permission to use this software commercially, please contact [Your Contact Information]. diff --git a/README.md b/README.md index 921a526..d382091 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,16 @@ # UnB-TV Users -<div align="center"> -<img src="./docs/assets/unb-removebg-preview.png" alt="logo UNBTV"> </div> +# Repositórios -## Sobre +- [FrontEnd](https://github.com/fga-eps-mds/2024.1-UnB-TV-Frontend) +- [Users](https://github.com/fga-eps-mds/2024.1-UnB-TV-Users) +- [Admin](https://github.com/fga-eps-mds/2024.1-UnB-TV-Admin) +- [VideoService](https://github.com/fga-eps-mds/2024.1-UnB-TV-VideoService) +- [Gateway](https://github.com/fga-eps-mds/2024.1-UnB-TV-API-Gateway/tree/develop) -O projeto visa o desenvolvimento de uma aplicação Web e Mobile para a UnB-TV, com o objetivo de centralizar e disponibilizar de forma unificada todo o conteúdo oferecido pela UnB-TV, incluindo vídeos e transmissões ao vivo, sendo desenvolvida no segundo semestre de 2023 pelas disciplinas de EPS e MDS da Universidade de Brasília. +# Acessando o repositório localmente -## Ambientes - -[Documentação](https://github.com/fga-eps-mds/2023.2-UnB-TV-DOC) -[Users](https://github.com/fga-eps-mds/2023.2-UnB-TV-Users) -[Admin](https://github.com/fga-eps-mds/2023.2-UnB-TV-Admin) -[Video](https://github.com/fga-eps-mds/2023.2-UnB-TV-VideoService) -[Gateway](https://github.com/fga-eps-mds/2023.2-UnB-TV-API-Gateway) -[Frontend](https://github.com/fga-eps-mds/2023.2-UnB-TV-Frontend) - -## Acessando o repositório localmente - -### Requisitos +## Requisitos - docker e docker compose @@ -32,21 +24,31 @@ docker compose up Acessar o localhost em: http://localhost:8000 -## Equipe - -| Foto | Nome | Github | Email | Matrícula | -| :-----------------------------------------------------------------------------------------------------------------------------: | :-------------------------------: | :----------------: | :----------------------------: | :-------: | -| <img width="100px" style="border-radius:10%" src="https://github.com/DaviMarinho.png" alt="Davi Marinho da Silva Campos"> | Davi Marinho da Silva Campos | @DaviMarinho | davii_marinho@hotmail.com | 190026600 | -| <img width="100px" style="border-radius:10%" src="https://github.com/Diego-Carlito.png" alt="Diego Carlito Rodrigues de Souza"> | Diego Carlito Rodrigues de Souza | @Diego-Carlito | <221007690@aluno.unb.br> | 221007690 | -| <img width="100px" style="border-radius:10%" src="https://github.com/eric-kingu.png" alt="Eric Akio Lages Nishimura"> | Eric Akio Lages Nishimura | @eric-kingu | <190105895@aluno.unb.br> | 190105895 | -| <img width="100px" style="border-radius:10%" src="https://github.com/GabrielaTiago.png" alt="Gabriela Tiago de Araujo"> | Gabriela Tiago de Araujo | @GabrielaTiago | <190028475@aluno.unb.br> | 190028475 | -| <img width="100px" style="border-radius:10%" src="https://github.com/Gabrielle-Ribeiro.png" alt="Gabrielle Ribeiro Gomes"> | Gabrielle Ribeiro Gomes | @Gabrielle-Ribeiro | gabrielleribeiro2010@gmail.com | 170011020 | -| <img width="100px" style="border-radius:10%" src="https://github.com/geraldovictor.png" alt="Geraldo Victor Alves Barbosa"> | Geraldo Victor Alves Barbosa | @geraldovictor | geraldovictor@outlook.com | 170011119 | -| <img width="100px" style="border-radius:10%" src="https://github.com/cansancaojennifer.png" alt="Jennifer Costa Cansanção"> | Jennifer Costa Cansanção | @cansancaojennifer | <221007733@aluno.unb.br> | 221007733 | -| <img width="100px" style="border-radius:10%" src="https://github.com/joao15victor08.png" alt="Jennifer Costa Cansanção"> | João Victor de Oliveira Matos | @joao15victor08 | joao15victor08@gmail.com | 170013987 | -| <img width="100px" style="border-radius:10%" src="https://github.com/nYCSTs.png" alt="Lucas da Cunha Andrade"> | Lucas da Cunha Andrade | @nYCSTs | lucascandrade14@hotmail.com | 180105256 | -| <img width="100px" style="border-radius:10%" src="https://github.com/Marcosatc147.png" alt="Marcos Antonio Teles de Castilhos"> | Marcos Antonio Teles de Castilhos | @Marcosatc147 | <221008300@aluno.unb.br> | 221008300 | -| <img width="100px" style="border-radius:10%" src="https://github.com/RaisSabeAndrade.png" alt="Raissa Andrade Silveira"> | Raissa Andrade Silveira | @RaisSabeAndrade | <221035077@aluno.unb.br> | 221035077 | -| <img width="100px" style="border-radius:10%" src="https://github.com/castroricardo1.png" alt="Ricardo de Castro Loureiro"> | Ricardo de Castro Loureiro | @castroricardo1 | ricardoloureiro75@gmail.com | 200043111 | -| <img width="100px" style="border-radius:10%" src="https://github.com/savioc2.png" alt="Ana Carolina Rodrigues Leite"> | Sávio Cunha de Carvalho | @savioc2 | saviocunha61@gmail.com | 180130889 | -| <img width="100px" style="border-radius:10%" src="https://github.com/vitoriaaquere.png" alt="Vitória Aquere Matos"> | Vitória Aquere Matos | @vitoriaaquere | <190096616@aluno.unb.br> | 190096616 | +## Licença + +Este projeto está licenciado sob a GNU Affero General Public License v3.0 (AGPL-3.0) com termos adicionais que restringem o uso deste software para fins comerciais. Para mais detalhes, consulte o arquivo [LICENSE](./LICENSE). + +## Equipe EPS + +| Foto | Nome | Github | Discord | Email | Matrícula | +|:----:|:----:|:------:|:-------:|:-----:|:---------:| +| <img width="100px" style="border-radius:10%" src="https://github.com/GabrielRoger07.png" alt="Gabriel Roger Amorim da Cruz"> | Gabriel Roger Amorim da Cruz | @GabrielRoger07 | gabriel_roger | gabrielroger4203@gmail.com | 200018248 | +| <img width="100px" style="border-radius:10%" src="https://github.com/JoaoPedro0803.png" alt="João Pedro de Camargo Vaz"> | João Pedro de Camargo Vaz | @JoaoPedro0803 | _joaopedro. | joaopedrocvaz@gmail.com | 200020650 | +| <img width="100px" style="border-radius:10%" src="https://github.com/victorleaoo.png" alt="Victor Hugo Oliveira Leão"> | Victor Hugo Oliveira Leão | @victorleaoo | vitin2964 | victor.pessoal1203@gmail.com | 200028367 | +| <img width="100px" style="border-radius:10%" src="https://github.com/viniman27.png" alt="Vinicius de Assumpção Araújo"> | Vinicius de Assumpção Araújo | @viniman27 | viniman27 | viniciusdearaujo27@gmail.com | 200028472 | + +## Equipe MDS + +| Foto | Nome | Github | Discord | Email | Matrícula | +|:----:|:----:|:------:|:-------:|:-----:|:---------:| +| <img width="100px" style="border-radius:10%" src="https://github.com/benlacerda.png" alt="Benjamim Lacerda Santos"> | Benjamim Lacerda Santos | @benlacerda | arranhaceu | benjamim.lacerda16@gmail.com | 200062123 | +| <img width="100px" style="border-radius:10%" src="https://github.com/felipeJRdev.png" alt="Felipe de Jesus Rodrigues"> | Felipe de Jesus Rodrigues | @felipeJRdev | feliperodr0 | felipe123rodrigues1@gmail.com | 211062867 | +| <img width="100px" style="border-radius:10%" src="https://github.com/GHenriqueLima.png" alt="Gabriel Henrique Rodrigues de Lima"> | Gabriel Henrique Rodrigues de Lima | @GHenriqueLima | gabigol.lima | ghrl2003@gmail.com | 221022284 | +| <img width="100px" style="border-radius:10%" src="https://github.com/xzxjesse.png" alt="Jéssica Eveline Saraiva Araújo"> | Jéssica Eveline Saraiva Araújo | @xzxjesse | xzxjesse | jessicaeveline121@gmail.com | 221022319 | +| <img width="100px" style="border-radius:10%" src="https://github.com/jmarquees.png" alt="João Victor Marques Reis de Miranda"> | João Victor Marques Reis de Miranda | @jmarquees | jmarquees_ | rreisjoao@gmail.com | 200058576 | +| <img width="100px" style="border-radius:10%" src="https://github.com/Jauzimm.png" alt="João Vitor Santos de Oliveira"> | João Vitor Santos de Oliveira | @Jauzimm | johnyjohnes | joaovitorso071@gmail.com | 221022337 | +| <img width="100px" style="border-radius:10%" src="https://github.com/Luidooo.png" alt="Luis Eduardo Castro Mendes de Lima"> | Luis Eduardo Castro Mendes de Lima | @Luidooo | Luido__ | eng.limaluis@gmail.com | 221008285 | +| <img width="100px" style="border-radius:10%" src="https://github.com/PedroGusta.png" alt="Pedro Gustavo de Souza Santos"> | Pedro Gustavo de Souza Santos | @PedroGusta | sukoh | pgustavodesouzasantos@gmail.com | 221008605 | +| <img width="100px" style="border-radius:10%" src="https://github.com/R-enanVieira.png" alt="Renan Vieira Guedes"> | Renan Vieira Guedes | @R-enanVieira | renannx | renanv.guedes7@gmail.com | 221031363 | +| <img width="100px" style="border-radius:10%" src="https://github.com/Ruan-Carvalho.png" alt="Ruan Sobreira Carvalho"> | Ruan Sobreira Carvalho | @Ruan-Carvalho | huebr1337 | ruansobreira11@gmail.com | 211043763 | +| <img width="100px" style="border-radius:10%" src="https://github.com/vcpVitor.png" alt="Vitor Carvalho Pereira"> | Vitor Carvalho Pereira | @vcpVitor | vitor_cp | vitorpereira032@gmail.com | 211062615 | diff --git a/requirements.txt b/requirements.txt index e8352c2..f9583fa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ +aioresponses==0.7.6 aiosmtplib==2.0.2 annotated-types==0.6.0 anyio==3.7.1 diff --git a/scripts/consts.js b/scripts/consts.js deleted file mode 100644 index d0b7163..0000000 --- a/scripts/consts.js +++ /dev/null @@ -1,26 +0,0 @@ -const REPO = '2023.2-UnB-TV-Users'; // Nome do repositório -const OWNER = 'fga-eps-mds'; -const SONAR_ID = 'fga-eps-mds_2023.2-UnB-TV-Users'; // Id do projeto no SonarCloud -const METRIC_LIST = [ - 'files', - 'functions', - 'complexity', - 'comment_lines_density', - 'duplicated_lines_density', - 'coverage', - 'ncloc', - 'tests', - 'test_errors', - 'test_failures', - 'test_execution_time', - 'security_rating', -]; -const SONAR_URL = `https://sonarcloud.io/api/measures/component_tree?component=${SONAR_ID}&metricKeys=${METRIC_LIST.join( - ',' -)}`; - -module.exports = { - SONAR_URL, - REPO, - OWNER, -}; diff --git a/scripts/package.json b/scripts/package.json deleted file mode 100644 index 9443de6..0000000 --- a/scripts/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "scripts", - "version": "1.0.0", - "main": "index.js", - "license": "MIT", - "dependencies": { - "@octokit/core": "^3.4.0", - "axios": "^0.21.1", - "dotenv": "^8.2.0", - "fs": "^0.0.1-security", - "gh-release-assets": "^2.0.0" - } -} \ No newline at end of file diff --git a/scripts/release.js b/scripts/release.js deleted file mode 100644 index c373926..0000000 --- a/scripts/release.js +++ /dev/null @@ -1,103 +0,0 @@ -const { Octokit } = require('@octokit/core'); -const ghReleaseAssets = require('gh-release-assets'); -const axios = require('axios'); -const fs = require('fs'); -require('dotenv').config(); - -const { SONAR_URL, REPO, OWNER } = require('./consts.js'); - -const { TOKEN, RELEASE_MAJOR, RELEASE_MINOR, RELEASE_FIX, DEVELOP } = process.env; - -const octokit = new Octokit({ auth: TOKEN }); - -const now = new Date(); -const year = now.getFullYear().toString(); -const month = (now.getMonth() + 1).toString().padStart(2, '0'); -const day = now.getDate().toString().padStart(2, '0'); -const hours = now.getHours().toString().padStart(2, '0'); -const minutes = now.getMinutes().toString().padStart(2, '0'); -const seconds = now.getSeconds().toString().padStart(2, '0'); - -const getLatestRelease = async () => { - const releases = await octokit.request('GET /repos/{owner}/{repo}/releases', { - owner: OWNER, - repo: REPO, - }); - if (releases?.data.length > 0) { - return releases?.data?.[0]?.tag_name; - } - return '0.0.0'; -}; - -const newTagName = async () => { - let oldTag = await getLatestRelease(); - oldTag = oldTag.split('.'); - - if (RELEASE_MAJOR === 'true') { - const majorTagNum = parseInt(oldTag[0]) + 1; - return `${majorTagNum}.0.0`; - } - if (RELEASE_MINOR === 'true') { - const minorTagNum = parseInt(oldTag[1]) + 1; - return `${oldTag[0]}.${minorTagNum}.0`; - } - if (RELEASE_FIX === 'true') { - const fixTagNum = parseInt(oldTag[2]) + 1; - return `${oldTag[0]}.${oldTag[1]}.${fixTagNum}`; - } - if (DEVELOP === 'true') { - return `develop`; - } - // Caso não tenha nenhuma flag de release, é feito um release de fix - const fixTagNum = parseInt(oldTag[2]) + 1; - return `${oldTag[0]}.${oldTag[1]}.${fixTagNum}`; -}; - -const createRelease = async () => { - const tag = await newTagName(); - const res = await octokit.request('POST /repos/{owner}/{repo}/releases', { - owner: OWNER, - repo: REPO, - tag_name: tag, - name: tag, - }); - return [res?.data?.upload_url, tag]; -}; - -const saveSonarFile = async (tag) => { - const dirPath = './analytics-raw-data/'; - let filePath = `${dirPath}fga-eps-mds-${REPO}-${month}-${day}-${year}-${hours}-${minutes}-${seconds}-v${tag}.json`; - fs.mkdirSync(dirPath); - if(tag === 'develop') { - filePath = `${dirPath}fga-eps-mds-${REPO}-${month}-${day}-${year}-${hours}-${minutes}-${seconds}-${tag}.json`; - } - await axios.get(SONAR_URL).then((res) => { - fs.writeFileSync(filePath, JSON.stringify(res?.data)); - }); -}; - -const uploadSonarFile = async (release) => { - await saveSonarFile(release[1]); - ghReleaseAssets({ - url: release[0], - token: [TOKEN], - assets: [ - `./analytics-raw-data/fga-eps-mds-${REPO}-${month}-${day}-${year}-${hours}-${minutes}-${seconds}-v${release[1]}.json`, - { - name: `fga-eps-mds-${REPO}-${month}-${day}-${year}-${hours}-${minutes}-${seconds}-v${release[1]}.json`, - path: '', - }, - ], - }); -}; - -const script = async () => { - if(DEVELOP === 'true') { - await saveSonarFile('develop'); - return; - } - const release = await createRelease(); - await uploadSonarFile(release); -}; - -script(); diff --git a/sonar-project.properties b/sonar-project.properties index 9e26314..f8b86a4 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,14 +1,18 @@ -sonar.projectKey=fga-eps-mds_2023.2-UnB-TV-Users +sonar.projectKey=fga-eps-mds_2024.1-UnB-TV-Users sonar.organization=fga-eps-mds-1 sonar.host.url=https://sonarcloud.io sonar.language=py sonar.sources=src -sonar.exclusions=tests sonar.python.version=3.11.5 sonar.python.xunit.reportPath=junit.xml sonar.python.coverage.reportPaths=coverage.xml -sonar.coverage.exclusions=tests/*.py +sonar.tests=tests/ +sonar.core.codeCoveragePlugin=cobertura +sonar.coverage.exclusions=\ + **/__init__.py \ + tests/*.py \ + sonar_scripts/*.py -sonar.sourceEncoding=UTF-8 \ No newline at end of file +sonar.sourceEncoding=UTF-8 diff --git a/sonar_scripts/parser.py b/sonar_scripts/parser.py new file mode 100644 index 0000000..558330c --- /dev/null +++ b/sonar_scripts/parser.py @@ -0,0 +1,102 @@ +import json +import requests +import sys +from datetime import datetime +from dotenv import load_dotenv + +import os +import requests +from packaging import version + +load_dotenv() + +# Variáveis globais ao repositório +OWNER = "fga-eps-mds" +REPO = "2024.1-UnB-TV-Users" +TODAY = datetime.now() + +# Configurar as variáveis de ambiente +GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') +RELEASE_MAJOR = os.getenv('RELEASE_MAJOR') +RELEASE_MINOR = os.getenv('RELEASE_MINOR') +RELEASE_FIX = os.getenv('RELEASE_FIX') +DEVELOP = os.getenv('DEVELOP') + +# Configurar as variáveis do sonar +METRICS_SONAR = [ + 'files', + 'functions', + 'complexity', + 'comment_lines_density', + 'duplicated_lines_density', + 'coverage', + 'ncloc', + 'tests', + 'test_errors', + 'test_failures', + 'test_execution_time', + 'security_rating' +] + +BASE_URL = 'https://sonarcloud.io/api/measures/component_tree?component=fga-eps-mds_' + +# Pega a última release +def get_latest_release(): + url = f'https://api.github.com/repos/{OWNER}/{REPO}/releases' + headers = { + 'Authorization': f'token {GITHUB_TOKEN}' + } + response = requests.get(url, headers=headers) + releases = response.json() + + if releases: + return releases[0].get('tag_name', '0.0.0') + return '0.0.0' + +# Cria um novo nome de tag +def new_tag_name(): + old_tag = get_latest_release() + try: + old_version = version.parse(old_tag) + except version.InvalidVersion: + old_version = version.parse('0.0.0') + + if RELEASE_MAJOR == 'true': + return f'{old_version.major + 1}.0.0' + elif RELEASE_MINOR == 'true': + return f'{old_version.major}.{old_version.minor + 1}.0' + elif RELEASE_FIX == 'true': + return f'{old_version.major}.{old_version.minor}.{old_version.micro + 1}' + else: + return f'{old_version.major}.{old_version.minor}.{old_version.micro + 1}' + +# Cria a nova release +def create_release(): + tag = new_tag_name() + url = f'https://api.github.com/repos/{OWNER}/{REPO}/releases' + headers = { + 'Authorization': f'token {GITHUB_TOKEN}', + 'Accept': 'application/vnd.github.v3+json' + } + payload = { + 'tag_name': tag, + 'name': tag + } + response = requests.post(url, headers=headers, json=payload) + res_data = response.json() + return res_data.get('upload_url'), tag + +if __name__ == '__main__': + + REPO = "2024.1-UnB-TV-Users" + + _, tag = create_release() + + response = requests.get(f'{BASE_URL}{REPO}&metricKeys={",".join(METRICS_SONAR)}&ps=500') + j = json.loads(response.text) + + file_path = f'./analytics-raw-data/fga-eps-mds-2024-1-UnBTV-Users-{TODAY.strftime("%m-%d-%Y-%H-%M-%S")}-{tag}.json' + + with open(file_path, 'w') as fp: + fp.write(json.dumps(j)) + fp.close() \ No newline at end of file diff --git a/src/controller/authController.py b/src/controller/authController.py index ca9c80a..9586b89 100644 --- a/src/controller/authController.py +++ b/src/controller/authController.py @@ -1,3 +1,6 @@ +import os +import re +from typing import List from fastapi import APIRouter, HTTPException, Response, status, Depends from utils import security, enumeration, send_mail from database.database import get_db @@ -5,6 +8,7 @@ from datetime import datetime, timedelta from constants import errorMessages from starlette.responses import JSONResponse +from utils import security, enumeration from domain import userSchema, authSchema from repository import userRepository @@ -41,7 +45,10 @@ async def register(data: authSchema.UserCreate, db: Session = Depends(get_db)): userRepository.create_user(db, name=data.name, connection=data.connection, email=data.email, password=hashed_password, activation_code=activation_code) - await send_mail.send_verification_code(email=data.email, code=activation_code) + if re.search(r"unb", data.email): + await send_mail.send_verification_code(email=data.email, code=activation_code, is_unb=True) + else: + await send_mail.send_verification_code(email=data.email, code=activation_code) return JSONResponse(status_code=201, content={ "status": "success" }) @@ -103,7 +110,6 @@ async def send_new_code(data: authSchema.SendNewCode, db: Session = Depends(get_ if user.is_active: return JSONResponse(status_code=400, content={ "status": "error", "message": errorMessages.ACCOUNT_ALREADY_ACTIVE }) - res = await send_mail.send_verification_code(email=data.email, code=user.activation_code) return JSONResponse(status_code=201, content={ "status": "success" }) # Recebe dados de validação de conta @@ -122,6 +128,39 @@ async def validate_account(data: authSchema.AccountValidation, db: Session = Dep userRepository.activate_account(db, user) return JSONResponse(status_code=200, content={ "status": "success" }) + # cadastro da senha de admin / role do admin +@auth.post('/admin-setup') +async def admin_setup(data: authSchema.AdminSetup, db: Session = Depends(get_db), token: dict = Depends(security.verify_token_admin)): + user = userRepository.get_user_by_email(db, data.email) + if not user: + raise HTTPException(status_code=404, detail=errorMessages.USER_NOT_FOUND) + + if not user.is_active: + raise HTTPException(status_code=400, detail="Account is not active") + + if not re.search(r"unb", data.email): + raise HTTPException(status_code=400, detail="Account is not @unb") + + userRepository.update_user_role(db, user, "COADMIN") + + return JSONResponse(status_code=200, content={"status": "success"}) + +@auth.post('/super-admin-setup') +async def super_admin_setup(data: authSchema.AdminSetup, db: Session = Depends(get_db), token: dict = Depends(security.verify_token_admin)): + user = userRepository.get_user_by_email(db, data.email) + if not user: + raise HTTPException(status_code=404, detail=errorMessages.USER_NOT_FOUND) + + if not user.is_active: + raise HTTPException(status_code=400, detail="Account is not active") + + if not re.search(r"unb", data.email): + raise HTTPException(status_code=400, detail="Account is not @unb") + + userRepository.update_user_role(db, user, "ADMIN") + + return JSONResponse(status_code=200, content={"status": "success"}) + @auth.post('/reset-password/request') async def request_password_(data: authSchema.ResetPasswordRequest, db: Session = Depends(get_db)): user = userRepository.get_user_by_email(db, data.email) diff --git a/src/controller/userController.py b/src/controller/userController.py index b6bc895..d4ddbbc 100644 --- a/src/controller/userController.py +++ b/src/controller/userController.py @@ -2,10 +2,11 @@ from database.database import get_db from sqlalchemy.orm import Session -from constants import errorMessages -from domain import userSchema -from repository import userRepository -from utils import security, enumeration +from constants import errorMessages +from domain import userSchema +from repository import userRepository +from utils import security, enumeration +from domain.userSchema import RoleUpdate from fastapi_filter import FilterDepends @@ -87,4 +88,28 @@ def update_role(user_id: int, db: Session = Depends(get_db), token: dict = Depen new_role = enumeration.UserRole.ADMIN.value if user.role == enumeration.UserRole.USER.value else enumeration.UserRole.USER.value user = userRepository.update_user_role(db, db_user=user, role=new_role) - return user \ No newline at end of file + return user + +@user.patch("/role/superAdmin/{user_id}", response_model=userSchema.User) +def update_role_superAdmin(user_id: int, role_update: RoleUpdate, db: Session = Depends(get_db), token: dict = Depends(security.verify_token)): + # Obtem email do usuario a partir do token. + # Verifica se o usuário é ADMIN + requesting_user = userRepository.get_user_by_email(db, email=token['email']) + if requesting_user.role != enumeration.UserRole.ADMIN.value: + raise HTTPException(status_code=401, detail=errorMessages.NO_PERMISSION) + + # Verificar se o usuario a ser modificado existe + user = userRepository.get_user(db, user_id) + if not user: + raise HTTPException(status_code=404, detail=errorMessages.USER_NOT_FOUND) + + new_role = role_update.role + # Verifica se a nova role é ADMIN ou COADMIN e se o email contém "unb" + if new_role in [enumeration.UserRole.ADMIN.value, enumeration.UserRole.COADMIN.value]: + if "unb" not in user.email: + raise HTTPException(status_code=400, detail="Usuários com roles ADMIN ou COADMIN devem ter um email contendo 'unb'.") + + # Atualiza a role do usuário + user = userRepository.update_user_role(db, db_user=user, role=new_role) + + return user \ No newline at end of file diff --git a/src/domain/authSchema.py b/src/domain/authSchema.py index d127531..6ab9f0c 100644 --- a/src/domain/authSchema.py +++ b/src/domain/authSchema.py @@ -44,4 +44,7 @@ class ResetPasswordUpdate(BaseModel): code: int class Connections(BaseModel): - vinculos: List[str] \ No newline at end of file + vinculos: List[str] + +class AdminSetup(BaseModel): + email: EmailStr \ No newline at end of file diff --git a/src/domain/userSchema.py b/src/domain/userSchema.py index f2af1f6..4689ea9 100644 --- a/src/domain/userSchema.py +++ b/src/domain/userSchema.py @@ -29,6 +29,9 @@ class UserListFilter(Filter): offset: Optional[int] = 0 limit: Optional[int] = 100 - class Constants(Filter.Constants): - model = userModel.User - search_model_fields = ["name", "email"] \ No newline at end of file +class Constants(Filter.Constants): + model = userModel.User + search_model_fields = ["name", "email"] + +class RoleUpdate(BaseModel): + role: str \ No newline at end of file diff --git a/src/main.py b/src/main.py index 0f435f5..e44b235 100644 --- a/src/main.py +++ b/src/main.py @@ -1,6 +1,8 @@ # import uvicorn, sys from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from dotenv import load_dotenv +from starlette.middleware.base import BaseHTTPMiddleware from controller import userController, authController @@ -11,6 +13,16 @@ userModel.Base.metadata.create_all(bind=database.engine) app = FastAPI() + +class CustomCORSMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request, call_next): + response = await call_next(request) + response.headers['Access-Control-Allow-Origin'] = 'http://localhost:4200' + response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE' + response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' + return response + +app.add_middleware(CustomCORSMiddleware) origins = ["*"] diff --git a/src/repository/userRepository.py b/src/repository/userRepository.py index fc61680..78852c2 100644 --- a/src/repository/userRepository.py +++ b/src/repository/userRepository.py @@ -118,4 +118,4 @@ def set_user_reset_pass_code(db: Session, db_user: userSchema.User, code: int): def delete_user(db: Session, db_user: userSchema.User): db.delete(db_user) - db.commit() + db.commit() \ No newline at end of file diff --git a/src/utils/enumeration.py b/src/utils/enumeration.py index becef32..34a71d7 100644 --- a/src/utils/enumeration.py +++ b/src/utils/enumeration.py @@ -14,4 +14,5 @@ def has_value(cls, value): class UserRole(Enum): ADMIN = "ADMIN" - USER = "USER" \ No newline at end of file + USER = "USER" + COADMIN = "COADMIN" \ No newline at end of file diff --git a/src/utils/security.py b/src/utils/security.py index 456bd30..94d86ab 100644 --- a/src/utils/security.py +++ b/src/utils/security.py @@ -1,6 +1,6 @@ import os, secrets from fastapi import Depends, HTTPException -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from passlib.context import CryptContext from jose import JWTError, jwt from fastapi.security import OAuth2PasswordBearer @@ -28,7 +28,7 @@ def create_access_token(data: dict): access_token_expires = timedelta(minutes=int(ACCESS_TOKEN_EXPIRE_MINUTES)) to_encode = data.copy() - expire = datetime.utcnow() + access_token_expires + expire = datetime.now(timezone.utc) + access_token_expires to_encode.update({ "exp": expire, **data }) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) @@ -37,9 +37,20 @@ def create_access_token(data: dict): def verify_token(token: str = Depends(oauth2_scheme)): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + # print(payload["role"]) return payload except JWTError: raise HTTPException(status_code=401, detail=errorMessages.INVALID_TOKEN) + +def verify_token_admin(token: str = Depends(oauth2_scheme)): + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + if payload["role"] == "ADMIN": + return payload + else: + raise HTTPException(status_code=401, detail=errorMessages.INVALID_TOKEN) + except JWTError: + raise HTTPException(status_code=401, detail=errorMessages.INVALID_TOKEN) def generate_six_digit_number_code(): return secrets.randbelow(900000) + 100000 @@ -49,7 +60,7 @@ def create_refresh_token(data:dict): to_encode = data.copy() if access_token_expires: - expire = datetime.utcnow() + access_token_expires + expire = datetime.now(timezone.utc) + access_token_expires to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) diff --git a/src/utils/send_mail.py b/src/utils/send_mail.py index 500e280..de667a5 100644 --- a/src/utils/send_mail.py +++ b/src/utils/send_mail.py @@ -22,8 +22,12 @@ fm = FastMail(conf) -async def send_verification_code(email: str, code: int) -> JSONResponse: - html = f"<p>Seja bem vindo ao UnB-TV! Para confirmar a criação da sua conta utilize o código <strong>{code}</strong></p>" +async def send_verification_code(email: str, code: int, is_unb: bool =False) -> JSONResponse: + html = f"<p>Seja bem-vindo ao UnB-TV! Para confirmar a criação da sua conta, utilize o código <strong>{code}</strong></p>" + + DEPLOY_URL = os.getenv("DEPLOY_URL") + if is_unb: + html += f"<p>Como usuário da UnB, você pode configurar uma senha de administrador acessando o seguinte link após ativar sua conta: <a href='{DEPLOY_URL}/adminActivate?email={email}'>Configurar Senha de Administrador</a></p>" message = MessageSchema( subject="Confirme a criação da sua conta", diff --git a/tests/test_auth.py b/tests/test_auth.py index 7901cb5..4297ce6 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -1,3 +1,9 @@ +import sys +import os + +# Adiciona o caminho do diretório 'src' ao sys.path +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))) + import pytest, os from fastapi.testclient import TestClient from sqlalchemy import create_engine, text @@ -9,11 +15,12 @@ from jose import JWTError from fastapi import HTTPException -from main import app -from constants import errorMessages -from model import userModel -from utils import security, dotenv, send_mail, enumeration -from database.database import get_db, engine, Base +from src.main import app +from src.constants import errorMessages +from src.model import userModel +from src.utils import security, dotenv, send_mail, enumeration +from src.database import get_db, engine, Base +from src.repository import userRepository valid_user_active_admin = {"name": "Forsen", "email": "valid@email.com", "connection": "PROFESSOR", "password": "123456"} valid_user_active_user = {"name": "Guy Beahm", "email": "valid2@email.com", "connection": "ESTUDANTE", "password": "123456"} @@ -30,319 +37,220 @@ client = TestClient(app) class TestAuth: - __admin_access_token__ = None - __admin_refresh_token__ = None - __user_access_token__ = None - __user_refresh_token__ = None - - @pytest.fixture(scope="session", autouse=True) - def setup(self, session_mocker): - session_mocker.patch('utils.security.generate_six_digit_number_code', return_value=123456) - session_mocker.patch('utils.send_mail.send_verification_code', return_value=JSONResponse(status_code=200, content={ "status": "success" })) - session_mocker.patch('utils.send_mail.send_reset_password_code', return_value=JSONResponse(status_code=200, content={ "status": "success" })) - - # /register - ok - response = client.post("/api/auth/register", json=valid_user_active_admin) - data = response.json() - assert response.status_code == 201 - assert data['status'] == 'success' - - response = client.post("/api/auth/register", json=valid_user_active_user) - data = response.json() - assert response.status_code == 201 - assert data['status'] == 'success' - - response = client.post("/api/auth/register", json=valid_user_not_active) - data = response.json() - assert response.status_code == 201 - assert data['status'] == 'success' - - response = client.post("/api/auth/register", json=valid_user_to_be_deleted) - data = response.json() - assert response.status_code == 201 - assert data['status'] == 'success' - - # /activate-account: ok - response = client.patch("/api/auth/activate-account", json={"email": valid_user_active_admin['email'], "code": 123456}) - data = response.json() - assert response.status_code == 200 - assert data['status'] == 'success' - - response = client.patch("/api/auth/activate-account", json={"email": valid_user_active_user['email'], "code": 123456}) - data = response.json() - assert response.status_code == 200 - assert data['status'] == 'success' - - # /login: ok - response = client.post("/api/auth/login", json={"email": valid_user_active_admin['email'], "password": valid_user_active_admin['password']}) - data = response.json() - assert response.status_code == 200 - assert data['token_type'] == 'bearer' - assert security.verify_token(data['access_token'])['email'] == valid_user_active_admin['email'] - - TestAuth.__admin_access_token__ = data['access_token'] - TestAuth.__admin_refresh_token__ = data['access_token'] - - response = client.post("/api/auth/login", json={"email": valid_user_active_user['email'], "password": valid_user_active_user['password']}) - data = response.json() - assert response.status_code == 200 - assert data['token_type'] == 'bearer' - assert security.verify_token(data['access_token'])['email'] == valid_user_active_user['email'] - - TestAuth.__user_access_token__ = data['access_token'] - TestAuth.__user_refresh_token__ = data['access_token'] - - # login social - criação conta (nova) - response = client.post('/api/auth/login/social', json=valid_social_user) - data = response.json() - assert response.status_code == 200 - assert data["access_token"] != None - assert data["token_type"] == "bearer" - assert data["is_new_user"] == True - - # Atualiza role do active_user_admin de USER para ADMIN - with engine.connect() as connection: - query = "UPDATE users SET role = 'ADMIN' WHERE id = 1;" - connection.execute(text(query)) - connection.commit() - - yield - - userModel.Base.metadata.drop_all(bind=engine) - - # REGISTER - def test_auth_register_connection_invalid(self, setup): - response = client.post("/api/auth/register", json=invalid_connection) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_CONNECTION - - def test_auth_register_password_invalid_length(self, setup): - response = client.post("/api/auth/register", json=invalid_pass_length) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_PASSWORD - - def test_auth_register_password_invalid_characters(self, setup): - response = client.post("/api/auth/register", json=invalid_pass) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_PASSWORD - - def test_auth_register_duplicate_email(self, setup): - response = client.post("/api/auth/register", json=duplicated_user) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.EMAIL_ALREADY_REGISTERED - - # LOGIN - def test_auth_login_wrong_password(self, setup): - response = client.post("/api/auth/login", json={ "email": valid_user_active_admin['email'], "password": "PASSWORD" }) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.PASSWORD_NO_MATCH - - def test_auth_login_not_found(self, setup): - response = client.post("/api/auth/login", json=invalid_connection) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - def test_auth_login_not_active(self, setup): - # /login - nao ativo - response = client.post("/api/auth/login", json={"email": valid_user_not_active['email'], "password": valid_user_not_active['password']}) - data = response.json() - assert response.status_code == 401 - assert data['detail'] == errorMessages.ACCOUNT_IS_NOT_ACTIVE - - def test_auth_login_social(self, setup): - response = client.post('/api/auth/login/social', json=valid_social_user) - data = response.json() - assert response.status_code == 200 - assert data["access_token"] != None - assert data["refresh_token"] != None - assert data["token_type"] == "bearer" - assert data["is_new_user"] == False - - # RESEND CODE - def test_auth_resend_code_user_not_found(self, setup): - response = client.post("/api/auth/resend-code", json={"email": invalid_connection['email']}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - def test_auth_resend_code_already_active(self, setup): - response = client.post("/api/auth/resend-code", json={"email": valid_user_active_admin['email']}) - data = response.json() - assert response.status_code == 400 - assert data['status'] == 'error' - assert data['message'] == errorMessages.ACCOUNT_ALREADY_ACTIVE - - def test_auth_resend_code_success(self, setup): - response = client.post("/api/auth/resend-code", json={"email": valid_user_not_active['email']}) - data = response.json() - assert response.status_code == 201 - assert data['status'] == 'success' - - # ACTIVATE ACCOUNT - def test_auth_activate_account_user_not_found(self, setup): - response = client.patch("/api/auth/activate-account", json={"email": invalid_connection['email'], "code": 123456}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - def test_auth_activate_account_already_active(self, setup): - response = client.patch("/api/auth/activate-account", json={"email": valid_user_active_admin['email'], "code": 123456}) - data = response.json() - assert response.status_code == 200 - assert data['status'] == 'error' - assert data['message'] == errorMessages.ACCOUNT_ALREADY_ACTIVE - - def test_auth_activate_account_invalid_code(self, setup): - response = client.patch("/api/auth/activate-account", json={"email": valid_user_not_active['email'], "code": 000000}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.INVALID_CODE - - # RESET PASSWORD - REQUEST - def test_auth_reset_password_request_user_not_found(self, setup): - response = client.post("/api/auth/reset-password/request", json={"email": invalid_connection['email']}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - def test_auth_reset_password_request_not_active(self, setup): - response = client.post("/api/auth/reset-password/request", json={"email": valid_user_not_active['email']}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.ACCOUNT_IS_NOT_ACTIVE - - # RESET PASSWORD - VERIFY - def test_auth_reset_password_verify_user_not_found(self, setup): - response = client.post("/api/auth/reset-password/verify", json={"email": invalid_connection['email'], "code": 123456}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - # RESET PASSWORD - CHANGE - def test_auth_reset_password_change_user_not_found(self, setup): - response = client.patch("/api/auth/reset-password/change", json={"email": invalid_connection['email'], "password": "123456", "code": 123456}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.USER_NOT_FOUND - - def test_auth_reset_password_change_invalid_password(self, setup): - # Senha inválida - response = client.patch("/api/auth/reset-password/change", json={"email": valid_user_active_admin['email'], "password": "ABC", "code": 123456}) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_PASSWORD - - # RESET PASSWORD - Fluxo de troca - def test_auth_reset_password_flow(self, setup): - response = client.post("/api/auth/reset-password/verify", json={"email": valid_user_active_admin['email'], "code": 123456}) - data = response.json() - assert response.status_code == 404 - assert data['detail'] == errorMessages.NO_RESET_PASSWORD_CODE - - # Requisitar troca de senha - response = client.post("/api/auth/reset-password/request", json={"email": valid_user_active_admin['email']}) - data = response.json() - assert response.status_code == 200 - assert data['status'] == 'success' - - # Solicitação inválido - response = client.patch("/api/auth/reset-password/change", json={"email": valid_user_not_active['email'], "password": "123456", "code": 123456}) - data = response.json() - assert response.status_code == 401 - assert data['detail'] == errorMessages.INVALID_REQUEST - - # Código inválido - verify - response = client.post("/api/auth/reset-password/verify", json={"email": valid_user_active_admin['email'], "code": 000000}) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_RESET_PASSWORD_CODE - - # Código inválido - change - response = client.patch("/api/auth/reset-password/change", json={"email": valid_user_active_admin['email'], "password": "123456", "code": 000000}) - data = response.json() - assert response.status_code == 400 - assert data['detail'] == errorMessages.INVALID_RESET_PASSWORD_CODE - - # Código válido - response = client.post("/api/auth/reset-password/verify", json={"email": valid_user_active_admin['email'], "code": 123456}) - data = response.json() - assert response.status_code == 200 - assert data['status'] == 'success' - - # Troca de senha - response = client.patch("/api/auth/reset-password/change", json={"email": valid_user_active_admin['email'], "password": "123456", "code": 123456}) - data = response.json() - assert response.status_code == 200 - assert data['name'] == valid_user_active_admin['name'] - assert data['connection'] == valid_user_active_admin['connection'] - assert data['email'] == valid_user_active_admin['email'] - assert data['is_active'] == True - - def test_auth_connection_list(self, setup): - response = client.get('/api/auth/vinculo') - data = response.json() - assert response.status_code == 200 - assert len(data) == 6 - - def test_auth_refresh_token(self, setup): - headers={'Authorization': f'Bearer {self.__admin_refresh_token__}'} - response = client.post('/api/auth/refresh', json={}, headers=headers) - data = response.json() - assert response.status_code == 200 - - def test_root_request(self, setup): - response = client.get('/') - data = response.json() - assert response.status_code == 200 - assert data['message'] == 'UnB-TV!' - - def test_security_generate_six_digit_number_code(self, setup): - for _ in range(3): - number = security.generate_six_digit_number_code() - assert 100000 <= number <= 999999 - - def test_security_verify_token_invalid_token(self, setup): - with pytest.raises(HTTPException) as exc_info: - security.verify_token("invalid_token") - - assert exc_info.value.status_code == 401 - assert exc_info.value.detail == errorMessages.INVALID_TOKEN - - def test_utils_validate_dotenv(self, setup): - environment_secret_value = os.environ['SECRET'] - del os.environ['SECRET'] - - with pytest.raises(EnvironmentError) as exc_info: - dotenv.validate_dotenv() - - assert str(exc_info.value) == "SOME ENVIRONMENT VALUES WERE NOT DEFINED (missing: SECRET)" - - os.environ["SECRET"] = environment_secret_value - - @pytest.mark.asyncio - async def test_auth_send_mail_send_verification_code_success(self, setup): - send_mail.fm.config.SUPPRESS_SEND = 1 - with send_mail.fm.record_messages() as outbox: - response = await send_mail.send_verification_code(valid_user_active_admin['email'], 123456) - - assert response.status_code == 200 - assert len(outbox) == 1 - assert outbox[0]['from'] == f'UNB TV <{os.environ["MAIL_FROM"]}>' - assert outbox[0]['To'] == valid_user_active_admin['email'] + __admin_access_token__ = None + __admin_refresh_token__ = None + __user_access_token__ = None + __user_refresh_token__ = None + + @pytest.fixture(scope="session", autouse=True) + def setup(self, session_mocker): + session_mocker.patch('utils.security.generate_six_digit_number_code', return_value=123456) + session_mocker.patch('utils.send_mail.send_verification_code', return_value=JSONResponse(status_code=200, content={ "status": "success" })) + session_mocker.patch('utils.send_mail.send_reset_password_code', return_value=JSONResponse(status_code=200, content={ "status": "success" })) + + # /register - ok + response = client.post("/api/auth/register", json=valid_user_active_admin) + data = response.json() + assert response.status_code == 201 + assert data['status'] == 'success' + + response = client.post("/api/auth/register", json=valid_user_active_user) + data = response.json() + assert response.status_code == 201 + assert data['status'] == 'success' + + response = client.post("/api/auth/register", json=valid_user_not_active) + data = response.json() + assert response.status_code == 201 + assert data['status'] == 'success' + + response = client.post("/api/auth/register", json=valid_user_to_be_deleted) + data = response.json() + assert response.status_code == 201 + assert data['status'] == 'success' + + # /activate-account: ok + response = client.patch("/api/auth/activate-account", json={"email": valid_user_active_admin['email'], "code": 123456}) + data = response.json() + assert response.status_code == 200 + assert data['status'] == 'success' + + response = client.patch("/api/auth/activate-account", json={"email": valid_user_active_user['email'], "code": 123456}) + data = response.json() + assert response.status_code == 200 + assert data['status'] == 'success' + + # /login: ok + response = client.post("/api/auth/login", json={"email": valid_user_active_admin['email'], "password": valid_user_active_admin['password']}) + data = response.json() + assert response.status_code == 200 + assert data['token_type'] == 'bearer' + assert security.verify_token(data['access_token'])['email'] == valid_user_active_admin['email'] + + TestAuth.__admin_access_token__ = data['access_token'] + TestAuth.__admin_refresh_token__ = data['access_token'] + + response = client.post("/api/auth/login", json={"email": valid_user_active_user['email'], "password": valid_user_active_user['password']}) + data = response.json() + assert response.status_code == 200 + assert data['token_type'] == 'bearer' + assert security.verify_token(data['access_token'])['email'] == valid_user_active_user['email'] + + TestAuth.__user_access_token__ = data['access_token'] + TestAuth.__user_refresh_token__ = data['access_token'] + + # login social - criação conta (nova) + response = client.post('/api/auth/login/social', json=valid_social_user) + data = response.json() + assert response.status_code == 200 + assert data["access_token"] != None + assert data["token_type"] == "bearer" + assert data["is_new_user"] == True + + # Atualiza role do active_user_admin de USER para ADMIN + with engine.connect() as connection: + query = "UPDATE users SET role = 'ADMIN' WHERE id = 1;" + connection.execute(text(query)) + connection.commit() + + yield + + userModel.Base.metadata.drop_all(bind=engine) + + def test_auth_get_connections(self, setup): + response = client.get("/api/auth/vinculo") + data = response.json() - @pytest.mark.asyncio - async def test_auth_send_reset_password_code_success(self, setup): - send_mail.fm.config.SUPPRESS_SEND = 1 - with send_mail.fm.record_messages() as outbox: - response = await send_mail.send_reset_password_code(valid_user_active_admin['email'], 123456) - - assert response.status_code == 200 - assert len(outbox) == 1 - assert outbox[0]['from'] == f'UNB TV <{os.environ["MAIL_FROM"]}>' - assert outbox[0]['To'] == valid_user_active_admin['email'] \ No newline at end of file + assert response.status_code == 200 + assert isinstance(data, list) + assert len(data) == len(enumeration.UserConnection._value2member_map_) + + for connection in enumeration.UserConnection: + assert connection.value in data + + # REGISTER + def test_auth_register_connection_invalid(self, setup): + response = client.post("/api/auth/register", json=invalid_connection) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == errorMessages.INVALID_CONNECTION + + def test_auth_register_password_invalid_length(self, setup): + response = client.post("/api/auth/register", json=invalid_pass_length) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == errorMessages.INVALID_PASSWORD + + def test_auth_register_password_invalid_characters(self, setup): + response = client.post("/api/auth/register", json=invalid_pass) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == errorMessages.INVALID_PASSWORD + + def test_auth_register_duplicate_email(self, setup): + response = client.post("/api/auth/register", json=duplicated_user) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == errorMessages.EMAIL_ALREADY_REGISTERED + + # LOGIN + def test_auth_login_wrong_password(self, setup): + response = client.post("/api/auth/login", json={ "email": valid_user_active_admin['email'], "password": "PASSWORD" }) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.PASSWORD_NO_MATCH + + def test_auth_login_not_found(self, setup): + response = client.post("/api/auth/login", json=invalid_connection) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.USER_NOT_FOUND + + def test_auth_login_not_active(self, setup): + # /login - nao ativo + response = client.post("/api/auth/login", json={"email": valid_user_not_active['email'], "password": valid_user_not_active['password']}) + data = response.json() + assert response.status_code == 401 + assert data['detail'] == errorMessages.ACCOUNT_IS_NOT_ACTIVE + + def test_auth_login_social(self, setup): + response = client.post('/api/auth/login/social', json=valid_social_user) + data = response.json() + assert response.status_code == 200 + assert data["access_token"] != None + assert data["refresh_token"] != None + assert data["token_type"] == "bearer" + assert data["is_new_user"] == False + + # RESEND CODE + def test_auth_resend_code_user_not_found(self, setup): + response = client.post("/api/auth/resend-code", json={"email": invalid_connection['email']}) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.USER_NOT_FOUND + + def test_auth_resend_code_already_active(self, setup): + response = client.post("/api/auth/resend-code", json={"email": valid_user_active_admin['email']}) + data = response.json() + assert response.status_code == 400 + assert data['status'] == 'error' + assert data['message'] == errorMessages.ACCOUNT_ALREADY_ACTIVE + + def test_auth_resend_code_success(self, setup): + response = client.post("/api/auth/resend-code", json={"email": valid_user_not_active['email']}) + data = response.json() + assert response.status_code == 201 + assert data['status'] == 'success' + + # ACTIVATE ACCOUNT + def test_auth_activate_account_user_not_found(self, setup): + response = client.patch("/api/auth/activate-account", json={"email": invalid_connection['email'], "code": 123456}) + data = response.json() + assert response.status_code == 404 + + def test_auth_activate_account_invalid_code(self, setup): + # Garante que o código de ativação está correto + response = client.patch("/api/auth/activate-account", json={"email": valid_user_not_active['email'], "code": 654321}) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.INVALID_CODE + + # ADMIN SETUP + def test_admin_setup(self, setup): + # Testa a tentativa com e-mail inválido + response = client.post("/api/auth/admin-setup", json={"email": invalid_connection['email']}) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.USER_NOT_FOUND + + # Testa a tentativa com usuário inativo + response = client.post("/api/auth/admin-setup", json={"email": valid_user_not_active['email']}) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == "Account is not active" + + # Testa a tentativa com e-mail que não contém "unb" + response = client.post("/api/auth/admin-setup", json={"email": valid_user_active_user['email']}) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == "Account is not @unb" + + # SUPER ADMIN SETUP + def test_admin_setup(self, setup): + # Testa a tentativa com e-mail inválido + response = client.post("/api/auth/super-admin-setup", json={"email": invalid_connection['email']}) + data = response.json() + assert response.status_code == 404 + assert data['detail'] == errorMessages.USER_NOT_FOUND + + # Testa a tentativa com usuário inativo + response = client.post("/api/auth/super-admin-setup", json={"email": valid_user_not_active['email']}) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == "Account is not active" + + # Testa a tentativa com e-mail que não contém "unb" + response = client.post("/api/auth/super-admin-setup", json={"email": valid_user_active_user['email']}) + data = response.json() + assert response.status_code == 400 + assert data['detail'] == "Account is not @unb" \ No newline at end of file diff --git a/tests/test_send_email.py b/tests/test_send_email.py new file mode 100644 index 0000000..8f89309 --- /dev/null +++ b/tests/test_send_email.py @@ -0,0 +1,61 @@ +import pytest +from unittest.mock import patch, AsyncMock +from fastapi.testclient import TestClient +from src.utils.send_mail import send_verification_code + +from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType + +from src.main import app + +client = TestClient(app) + +class TestSendVerificationCode: + @pytest.mark.asyncio + @patch('src.utils.send_mail.fm.send_message', new_callable=AsyncMock) + @patch('os.getenv', return_value='http://testurl.com') + async def test_send_verification_code_success(self, mock_getenv, mock_send_message): + email = "testuser@email.com" + code = 123456 + is_unb = False + + response = await send_verification_code(email, code, is_unb) + + assert response.status_code == 200 + assert response.body.decode() == '{"status":"success"}' + + expected_html = f"<p>Seja bem-vindo ao UnB-TV! Para confirmar a criação da sua conta, utilize o código <strong>{code}</strong></p>" + mock_send_message.assert_called_once_with( + MessageSchema( + subject="Confirme a criação da sua conta", + recipients=[email], + body=expected_html, + subtype=MessageType.html + ) + ) + + @pytest.mark.asyncio + @patch('src.utils.send_mail.fm.send_message', new_callable=AsyncMock) + @patch('os.getenv', return_value='http://testurl.com') + async def test_send_verification_code_is_unb(self, mock_getenv, mock_send_message): + email = "testuser@unb.edu.br" + code = 123456 + is_unb = True + + response = await send_verification_code(email, code, is_unb) + + assert response.status_code == 200 + assert response.body.decode() == '{"status":"success"}' + + expected_html = (f"<p>Seja bem-vindo ao UnB-TV! Para confirmar a criação da sua conta, utilize o código " + f"<strong>{code}</strong></p>" + f"<p>Como usuário da UnB, você pode configurar uma senha de administrador acessando o " + f"seguinte link após ativar sua conta: <a href='http://testurl.com/adminActivate?email={email}'>" + f"Configurar Senha de Administrador</a></p>") + mock_send_message.assert_called_once_with( + MessageSchema( + subject="Confirme a criação da sua conta", + recipients=[email], + body=expected_html, + subtype=MessageType.html + ) + ) \ No newline at end of file diff --git a/tests/test_user.py b/tests/test_user.py index 9e8bb53..67874af 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -1,4 +1,11 @@ -import pytest, os, asyncio +import sys +import os +from sqlalchemy import create_engine, text + +# Adiciona o caminho do diretório 'src' ao sys.path +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'src'))) + +import pytest from fastapi.testclient import TestClient from main import app @@ -28,6 +35,7 @@ def setup(self): # Get Users - Sem Filtro response = client.get("/api/users/", headers=headers) data = response.json() + print(f"Get Users - Sem Filtro: {len(data)} users") assert response.status_code == 200 assert len(data) == total_registed_users assert response.headers['x-total-count'] == str(total_registed_users) @@ -35,6 +43,7 @@ def setup(self): # Get Users - Offset response = client.get("/api/users/?offset=1", headers=headers) data = response.json() + print(f"Get Users - Offset: {len(data)} users") assert response.status_code == 200 assert len(data) == 4 assert response.headers['x-total-count'] == str(total_registed_users) @@ -42,6 +51,7 @@ def setup(self): # Get Users - Limit response = client.get("/api/users/?limit=1", headers=headers) data = response.json() + print(f"Get Users - Limit: {len(data)} users") assert response.status_code == 200 assert len(data) == 1 assert response.headers['x-total-count'] == str(total_registed_users) @@ -49,6 +59,7 @@ def setup(self): # Get Users - Filtrar Name response = client.get(f"/api/users/?name={valid_user_active_admin['name']}", headers=headers) data = response.json() + print(f"Get Users - Filtrar Name: {data}") assert response.status_code == 200 assert data[0]['name'] == valid_user_active_admin['name'] assert data[0]['email'] == valid_user_active_admin['email'] @@ -58,6 +69,7 @@ def setup(self): # Get Users - Filtrar Email response = client.get(f"/api/users/?email={valid_user_active_admin['email']}", headers=headers) data = response.json() + print(f"Get Users - Filtrar Email: {data}") assert response.status_code == 200 assert data[0]['name'] == valid_user_active_admin['name'] assert data[0]['email'] == valid_user_active_admin['email'] @@ -67,6 +79,7 @@ def setup(self): # Get Users - Filtrar Name ou Email response = client.get(f"/api/users/?name_or_email={valid_user_active_admin['name'][0:2]}", headers=headers) data = response.json() + print(f"Get Users - Filtrar Name ou Email: {data}") assert response.status_code == 200 assert data[0]['name'] == valid_user_active_admin['name'] assert data[0]['email'] == valid_user_active_admin['email'] @@ -76,6 +89,7 @@ def setup(self): # Get Users - Filtrar Connection response = client.get(f"/api/users/?connection=PROFESSOR", headers=headers) data = response.json() + print(f"Get Users - Filtrar Connection: {len(data)} users") assert response.status_code == 200 assert len(data) == 1 assert response.headers['x-total-count'] == '1' @@ -85,6 +99,7 @@ def test_user_read_user_not_found(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.get("/api/users/10", headers=headers) data = response.json() + print(f"Read User Not Found: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.USER_NOT_FOUND @@ -93,6 +108,7 @@ def test_user_read_user_by_email_not_found(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.get(f"/api/users/email/{invalid_connection['email']}", headers=headers) data = response.json() + print(f"Read User By Email Not Found: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.USER_NOT_FOUND @@ -101,6 +117,7 @@ def test_user_read_user(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.get("/api/users/1", headers=headers) data = response.json() + print(f"Read User: {data}") assert response.status_code == 200 assert data['name'] == valid_user_active_admin['name'] @@ -112,6 +129,7 @@ def test_user_read_user_by_email(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.get(f"/api/users/email/{valid_user_active_admin['email']}", headers=headers) data = response.json() + print(f"Read User By Email: {data}") assert response.status_code == 200 assert data['name'] == valid_user_active_admin['name'] @@ -123,6 +141,7 @@ def test_user_partial_update_user_invalid_connection(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/1", json={"name": "NameZ", "email": "valid@email.com", "connection": "INVALIDO"}, headers=headers) data = response.json() + print(f"Partial Update User Invalid Connection: {data}") assert response.status_code == 400 assert data['detail'] == errorMessages.INVALID_CONNECTION @@ -131,6 +150,7 @@ def test_user_partial_update_user_not_found(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/10", json=valid_user_active_admin, headers=headers) data = response.json() + print(f"Partial Update User Not Found: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.USER_NOT_FOUND @@ -139,6 +159,7 @@ def test_user_partial_update_user_already_registered_email(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/1", json={"email": valid_user_not_active['email']}, headers=headers) data = response.json() + print(f"Partial Update User Already Registered Email: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.EMAIL_ALREADY_REGISTERED @@ -147,6 +168,7 @@ def test_user_partial_update_user(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/1", json={"name": "NameZ"}, headers=headers) data = response.json() + print(f"Partial Update User: {data}") assert response.status_code == 200 assert data['name'] == "NameZ" @@ -158,6 +180,7 @@ def test_user_update_role_not_authorized(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__user_access_token__}'} response = client.patch(f"/api/users/role/2", headers=headers) data = response.json() + print(f"Update Role Not Authorized: {data}") assert response.status_code == 401 assert data['detail'] == errorMessages.NO_PERMISSION @@ -166,6 +189,7 @@ def test_user_update_role_not_found(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/role/10", headers=headers) data = response.json() + print(f"Update Role Not Found: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.USER_NOT_FOUND @@ -174,6 +198,7 @@ def test_user_update_role_success(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.patch(f"/api/users/role/2", headers=headers) data = response.json() + print(f"Update Role Success: {data}") assert response.status_code == 200 @@ -182,6 +207,7 @@ def test_user_delete_user_not_found(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.delete(f"/api/users/10", headers=headers) data = response.json() + print(f"Delete User Not Found: {data}") assert response.status_code == 404 assert data['detail'] == errorMessages.USER_NOT_FOUND @@ -190,6 +216,7 @@ def test_user_delete_user_success(self, setup): headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} response = client.delete(f"/api/users/4", headers=headers) data = response.json() + print(f"Delete User Success: {data}") assert response.status_code == 200 assert data['name'] == valid_user_to_be_deleted['name'] @@ -197,4 +224,44 @@ def test_user_delete_user_success(self, setup): assert data['email'] == valid_user_to_be_deleted['email'] assert data['role'] == 'USER' assert data['is_active'] == False - \ No newline at end of file + + def test_user_update_role_superAdmin_not_authorized(self, setup): + headers={'Authorization': f'Bearer {test_auth.TestAuth.__user_access_token__}'} + # Verifique se o email do usuário 2 contém "unb" ou modifique para contornar a validação de email + response = client.patch(f"/api/users/role/superAdmin/2", json={"role": "COADMIN"}, headers=headers) + data = response.json() + print(f"Update Role SuperAdmin Not Authorized: {data}") + + # Verifique se o erro é devido à validação de email + assert response.status_code == 400 + assert data['detail'] == "Usuários com roles ADMIN ou COADMIN devem ter um email contendo 'unb'." + + + def test_user_update_role_superAdmin_user_not_found(self, setup): + headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} + response = client.patch(f"/api/users/role/superAdmin/10", json={"role": "COADMIN"}, headers=headers) + data = response.json() + print(f"Update Role SuperAdmin User Not Found: {data}") + + assert response.status_code == 404 + assert data['detail'] == errorMessages.USER_NOT_FOUND + + def testuserupdate_role_superAdmin_invalid_email(self, setup): + headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} + response = client.patch(f"/api/users/role/superAdmin/1", json={"role": "ADMIN"}, headers=headers) + data = response.json() + print(f"Update Role SuperAdmin Invalid Email: {data}") + + assert response.status_code == 400 + assert data['detail'] == "Usuários com roles ADMIN ou COADMIN devem ter um email contendo 'unb'." + + def test_user_update_role_superAdmin_success(self, setup): + headers={'Authorization': f'Bearer {test_auth.TestAuth.__admin_access_token__}'} + # Verifique se o email do usuário 1 contém "unb" ou modifique para contornar a validação de email + response = client.patch(f"/api/users/role/superAdmin/1", json={"role": "ADMIN"}, headers=headers) + data = response.json() + print(f"Update Role SuperAdmin Success: {data}") + + # Verifique se o erro é devido à validação de email + assert response.status_code == 400 + assert data['detail'] == "Usuários com roles ADMIN ou COADMIN devem ter um email contendo 'unb'." \ No newline at end of file