63 Commits

Author SHA1 Message Date
19a3d168a1 Changes in text 2024-06-03 16:30:24 +02:00
81ce9eb546 Merge pull request 'Fixes: error handling on login page #13' (#39) from fr/error-handling-login into main
Reviewed-on: #39
2024-06-03 16:21:31 +02:00
d40af87c46 Fixes: error handling on login page #13
Some checks failed
Build DeguApp backend / build (pull_request) Failing after 2m11s
2024-06-03 16:19:32 +02:00
7eb548e138 Added: gitea action for backend 2024-06-03 13:22:25 +02:00
6c2ebe7d7a Added: dist/ to biome ignore 2024-06-02 23:06:58 +02:00
1dd7952976 Code formatted 2024-06-02 23:06:32 +02:00
922a11b23b Added: package.json format script 2024-06-02 23:05:57 +02:00
5a2a2db5e2 Fixes: error handling on signup page #13 2024-06-02 23:04:42 +02:00
61449caef1 Updated README.md 2024-06-02 22:34:07 +02:00
c9b8246218 Fix: route for frontend 2024-05-16 15:41:24 +02:00
c89dfa6786 Added: script for building website version 2024-05-15 03:04:16 +02:00
8f3e442077 Added: beer image and other info about beer into reviews 2024-05-15 02:52:01 +02:00
0430710522 Fixed: reviews data now contains info about beer 2024-05-15 02:33:38 +02:00
c1805643c8 Added: print results from API on /reviews page 2024-05-15 02:29:42 +02:00
f1c296c0d3 Added: array with variables on reviews page 2024-05-15 02:08:11 +02:00
2041c8998a Fixed: fetching review data, typos 2024-05-15 02:04:16 +02:00
cff010f2b4 Fix: review add overlapping dropdown 2024-05-15 01:46:08 +02:00
986aca3931 Fixed: review add - send add request to api 2024-05-15 01:35:52 +02:00
a57a059c2a Added: review add form 2024-05-15 01:05:25 +02:00
b7dc6af2e4 Added: images and review button on beer/get
Fixes: #12
2024-05-15 00:44:47 +02:00
4fc58aedd7 Added: folder with routes to review and add review page, added package RangeSlider; in _layout.js added add review as invisible 2024-05-14 22:49:11 +02:00
bf08eefe57 Fix: beer get page responsibility 2024-05-14 22:44:32 +02:00
6d6afc6274 Fixes: #25 again 2024-05-14 22:39:37 +02:00
82c90c1ceb Added: upload image in beer add form 2024-05-14 22:27:10 +02:00
4fe4808b3c Fix: image was rendering inside buttons view 2024-05-14 22:25:23 +02:00
b6b9b989c7 Edited: restyled beer get; Added: flashlist package 2024-05-14 22:25:23 +02:00
13b223ed5f Fixes: #25 2024-05-14 22:25:21 +02:00
04833277e1 Edited: .gitignore - added test-report.html 2024-05-14 19:41:35 +02:00
31179d7292 Fixes: #15 2024-05-12 23:38:17 +02:00
1c97262ee3 Added: tests for reviews, Reviews GET API endpoint; Fixed: tests for beers 2024-05-12 22:19:04 +02:00
bf791db47f Backend: code formatted 2024-05-12 22:19:04 +02:00
fa25015472 Added: package jest-html-reporter 2024-05-12 22:19:04 +02:00
4d02572d0c Added: API review 2024-05-12 22:19:04 +02:00
d418a53144 Fix: image was rendering inside buttons view 2024-05-12 21:58:18 +02:00
9b850ba88f Merge pull request 'kevin/add-form' (#14) from kevin/add-form into main
Beer add form
Reviewed-on: #14
2024-05-12 21:44:08 +02:00
41f52e67d3 Fix: responsivity 2024-05-12 21:43:05 +02:00
2d06e0fb12 Added: custom style for DropDownPicker, added icons for DropDownPicker, in style.js added new color for placeholder; Edited: Component for button, where you can now define background, border, ... by class 2024-05-12 21:26:44 +02:00
114ab257b2 Fix: changed dropdown menu to another package 2024-05-12 19:43:29 +02:00
f382150da3 Edited: Pick and take an image 2024-05-12 19:12:11 +02:00
630da41536 Fix: check that beer was added 2024-05-12 17:47:06 +02:00
674ee65c29 Added: check if beer was added, if not, show alert; Added packages picker,expo-camera 2024-05-12 12:10:32 +02:00
e8a0449ad2 Fix: gradient background on signup page; Added: color for text in button, on index page added new button and greeting 2024-05-09 20:06:20 +02:00
a25ce29154 Edited: README.md - how to build android package 2024-05-09 20:02:51 +02:00
6cf744bbc5 Added expo-linear-gradient and expo-system-ui package via npx expo install 2024-05-09 19:42:40 +02:00
7c25158c85 Edited: Styles on login page, styles on sign up page 2024-05-09 18:05:15 +02:00
05d0ff7134 Added: beer add page; all beers page 2024-05-09 15:32:26 +02:00
6497a05e3c Fix: add missing dependency 2024-05-08 23:41:29 +02:00
b388736ee8 Edited: Styles on login page 2024-05-08 23:22:05 +02:00
652a3b56d7 Added .env file 2024-05-08 21:30:30 +02:00
b17cf25970 Added: Link and Text component, Named links for components..., Tab layout 2024-05-08 21:18:47 +02:00
e62ef8695b Added biome for formatting, code formatted 2024-05-08 16:50:25 +02:00
dc446fe8dc Clean up 2024-05-08 16:37:48 +02:00
8e25ca5dd7 Moved from axios to Fetch API, Added user object to the AuthState 2024-05-08 16:31:21 +02:00
89075eb6ae Added: fully working signin/signup system with routing 2024-05-06 22:18:22 +02:00
bd5f7388b8 Login screen design done 2024-05-05 18:47:51 +02:00
8bff13f98f Added: deguapp logo 2024-05-05 17:54:58 +02:00
c2c3821ce2 Working on login screen 2024-05-05 17:44:42 +02:00
77e5082680 Added: web support 2024-05-04 00:16:27 +02:00
3a7b83b990 Added: base expo installation 2024-05-04 00:13:58 +02:00
44dbf74f1c Added: Beer API, Docs API and tests for both, fixed build 2024-05-03 01:46:23 +02:00
ef4cabff78 Update README.md 2024-05-02 02:01:44 +02:00
66e2cb82e5 Added: README.md and LICENSE 2024-05-02 02:01:07 +02:00
f12cae20ae Fixed: api auth status -> get response 2024-05-02 01:45:30 +02:00
78 changed files with 19203 additions and 230 deletions

View File

@@ -0,0 +1,32 @@
name: Build DeguApp backend
on: pull_request
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Set up Node.js and TypeScript
uses: actions/setup-node@v1
with:
node-version: "20.14.0"
- name: npm install
working-directory: api/
run: |
npm install
- name: npm run build
working-directory: api/
run: |
npm run build --if-present
- name: npm run test
working-directory: api/
run: |
npm run test

233
LICENSE Normal file
View File

@@ -0,0 +1,233 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 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.
tim
Copyright (C) 2023 fr
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:
tim Copyright (C) 2023 fr
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/philosophy/why-not-lgpl.html>.

98
README.md Normal file
View File

@@ -0,0 +1,98 @@
# DeguApp
DeguApp is an application designed for beer tasting enthusiasts to rate beers during tastings.
## Features
- **Adding Beers**: Users can add new beers to the app's database.
- **Beer Rating**: Users can rate beers based on their taste and experience.
- **Creating Sessions**: Users can create shared tasting sessions with friends.
- **Review Overview**: Users can view reviews from all users.
- **User Average Rating**: Users can see the average rating of each beer.
## Technologies Used
- **Backend API**:
- Node.js
- Express.js
- Nork
- TypeScript
- MongoDB (for database storage)
- **Android and Web App**:
- Expo
## Getting Started
To get started with DeguApp, follow these steps:
1. Clone the repository:
```bash
git clone https://git.filiprojek.cz/fr/deguapp.git
```
2. Install dependencies:
```bash
# frontend
cd deguapp/frontend
npm install
# backend
cd deguapp/api
npm install
```
3. Will be added in the future:)
5. Open the app in your browser or Android emulator and start exploring!
## Local builds
### Android
```bash
cd frontend/
npm i
export ANDROID_HOME=$HOME/.Android/Sdk/
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/platform-tools
echo "EXPO_PUBLIC_API_URL=https://degu.filiprojek.cz/api/v1" > .env
npx expo prebuild
# edit gradle.properties and add info about signing key
# copy signing key to android/app/[keyname].keystore
# edit android/app/build.gradle
npx react-native build-android --mode=release
bundletool build-apks --bundle=./frontend/android/app/build/outputs/bundle/release/app-release.aab --output ./deguapp.apks --ks <upload-key.keystore> --ks-key-alias <upload-key-alias>
bundletool install-apks --apks=./deguapp.apks
```
#### Resources:
- https://github.com/expo/eas-cli/issues/1300
- https://reactnative.dev/docs/signed-apk-android#generating-the-release-aab
### Server
```bash
cd api/
npm i
npm run build
```
## Contributing
Contributions are welcome! If you'd like to contribute to DeguApp, please fork the repository and submit a pull request with your changes.
Use the upstream of the project, which can be found at https:/git.filiprojek.cz/fr/deguapp. **GitHub repository is just a mirror!**
## License
This project is licensed under the GNU GPLv3 License - see the [LICENSE](LICENSE) file for details.

2
api/.gitignore vendored
View File

@@ -2,3 +2,5 @@ node_modules/
dist/ dist/
package-lock.json package-lock.json
.env .env
test-report.html
uploads/

36
api/biome.json Normal file
View File

@@ -0,0 +1,36 @@
{
"$schema": "https://biomejs.dev/schemas/1.7.3/schema.json",
"files": {
"ignore": [".expo/", ".vscode/", "node_modules/", "dist/", "*.json"]
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": false,
"rules": {
"recommended": true
}
},
"formatter": {
"enabled": true,
"formatWithErrors": false,
"ignore": [],
"attributePosition": "auto",
"indentStyle": "tab",
"indentWidth": 2,
"lineEnding": "lf",
"lineWidth": 120
},
"javascript": {
"formatter": {
"arrowParentheses": "always",
"bracketSameLine": true,
"bracketSpacing": true,
"jsxQuoteStyle": "double",
"quoteProperties": "asNeeded",
"semicolons": "always",
"trailingComma": "all"
}
}
}

View File

@@ -11,7 +11,7 @@ services:
image: mongo-express image: mongo-express
restart: always restart: always
ports: ports:
- 8081:8081 - 8091:8081
environment: environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: root ME_CONFIG_MONGODB_ADMINPASSWORD: root

View File

@@ -10,6 +10,7 @@
"start:dev": "tsx watch src/server.ts", "start:dev": "tsx watch src/server.ts",
"start:prod": "node dist/server.js", "start:prod": "node dist/server.js",
"tsc": "tsc -p .", "tsc": "tsc -p .",
"docs": "DOCS_GEN=true npx ts-node ./src/server.ts",
"clean": "rimraf dist", "clean": "rimraf dist",
"copy-assets": "ts-node src/utils/copy_assets", "copy-assets": "ts-node src/utils/copy_assets",
"build": "npm-run-all clean tsc copy-assets", "build": "npm-run-all clean tsc copy-assets",
@@ -22,6 +23,7 @@
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"colors": "1.4.0", "colors": "1.4.0",
"cookie-parser": "^1.4.6", "cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
@@ -29,6 +31,7 @@
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.3", "mongoose": "^8.3.3",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"pad": "^3.2.0", "pad": "^3.2.0",
"path": "^0.12.7", "path": "^0.12.7",
"yup": "^1.4.0", "yup": "^1.4.0",
@@ -39,6 +42,7 @@
"@types/bcrypt": "^5.0.2", "@types/bcrypt": "^5.0.2",
"@types/chai": "^4.2.22", "@types/chai": "^4.2.22",
"@types/cookie-parser": "^1.4.7", "@types/cookie-parser": "^1.4.7",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/inquirer": "^8.1.3", "@types/inquirer": "^8.1.3",
@@ -46,6 +50,7 @@
"@types/jsonwebtoken": "^9.0.6", "@types/jsonwebtoken": "^9.0.6",
"@types/mocha": "^9.0.0", "@types/mocha": "^9.0.0",
"@types/morgan": "^1.9.9", "@types/morgan": "^1.9.9",
"@types/multer": "^1.4.11",
"@types/shelljs": "^0.8.11", "@types/shelljs": "^0.8.11",
"@types/supertest": "^6.0.2", "@types/supertest": "^6.0.2",
"@typescript-eslint/eslint-plugin": "^5.5.0", "@typescript-eslint/eslint-plugin": "^5.5.0",
@@ -54,6 +59,7 @@
"eslint": "^8.3.0", "eslint": "^8.3.0",
"http": "^0.0.1-security", "http": "^0.0.1-security",
"jest": "^29.7.0", "jest": "^29.7.0",
"jest-html-reporter": "^3.10.2",
"mocha": "^9.1.3", "mocha": "^9.1.3",
"mongodb-memory-server": "^9.2.0", "mongodb-memory-server": "^9.2.0",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
@@ -71,6 +77,12 @@
"testEnvironment": "node", "testEnvironment": "node",
"setupFilesAfterEnv": [ "setupFilesAfterEnv": [
"./tests/_setupFile.ts" "./tests/_setupFile.ts"
],
"reporters": [
"default",
["./node_modules/jest-html-reporter", {
"pageTitle": "Test Report"
}]
] ]
} }
} }

View File

@@ -1,29 +1,29 @@
import express from "express"; import express from "express";
import morgan from "morgan"; import morgan from "morgan";
import path from 'path' import path from "path";
//import cors from 'cors' import cors from "cors";
import cookieParser from 'cookie-parser' import cookieParser from "cookie-parser";
import { router as routes } from "./routes"; import { router as routes } from "./routes";
//import { router as middlewares } from './middlewares' //import { router as middlewares } from './middlewares'
//import env from './config/environment' import env from "./config/environment";
//export let corsWhitelist: Array<string> export let corsWhitelist: Array<string>;
//if (env.CORS_WHITELIST != 'undefined') { if (env.CORS_WHITELIST != "undefined") {
// corsWhitelist = [...['http://localhost:8080', 'http://localhost:6040'], ...env.CORS_WHITELIST.split(';')] corsWhitelist = [...["http://localhost:8080", "http://localhost:6040"], ...env.CORS_WHITELIST.split(";")];
//} else { } else {
// corsWhitelist = ['http://localhost:8080', 'http://localhost:6040'] corsWhitelist = ["http://localhost:8080", "http://localhost:6040"];
//} }
//const corsOptions = { const corsOptions = {
// origin: function (origin: any, callback: any) { origin: function (origin: any, callback: any) {
// if (!origin || corsWhitelist.indexOf(origin) !== -1) { if (!origin || corsWhitelist.indexOf(origin) !== -1) {
// callback(null, true) callback(null, true);
// } else { } else {
// callback(new Error('Not allowed by CORS')) callback(new Error("Not allowed by CORS"));
// } }
// }, },
// optionsSuccessStatus: 200, optionsSuccessStatus: 200,
// credentials: true credentials: true,
//} };
export const app = express(); export const app = express();
@@ -31,12 +31,13 @@ export const app = express();
//app.use(middlewares) //app.use(middlewares)
//app.set('view engine', 'ejs') //app.set('view engine', 'ejs')
//app.set('views', path.join(__dirname, 'views')) //app.set('views', path.join(__dirname, 'views'))
//app.use(cors(corsOptions)) app.use(cors(corsOptions));
app.use(morgan("dev")); app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
app.use(express.json()); app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser()) app.use('/public/uploads', express.static(path.join(__dirname, '../uploads')));
app.use(cookieParser());
// Routes // Routes
app.use(routes); app.use(routes);

View File

@@ -1,13 +1,13 @@
import { Request, Response } from 'express'; import { Request, Response } from "express";
import bcrypt from 'bcrypt'; import bcrypt from "bcrypt";
import jwt from 'jsonwebtoken'; import jwt from "jsonwebtoken";
import env from '../config/environment'; import env from "../config/environment";
import Docs from '../services/docsService'; import Docs from "../services/docsService";
import User from '../models/User'; import User from "../models/User";
import {Log} from 'nork' import { Log } from "nork";
import { IUser, signupExam, ISignin, signinExam } from '../validators/authValidator'; import { IUser, signupExam, ISignin, signinExam } from "../validators/authValidator";
new Docs('user', 'signup', '/api/v1/auth/signup', 'POST', 'user signup api', undefined, signupExam, 'status object'); new Docs("user", "signup", "/api/v1/auth/signup", "POST", "user signup api", undefined, signupExam, "status object");
export async function signup_post(req: Request, res: Response) { export async function signup_post(req: Request, res: Response) {
try { try {
const payload: IUser = req.body; const payload: IUser = req.body;
@@ -16,27 +16,27 @@ export async function signup_post(req: Request, res: Response) {
const user = new User(payload); const user = new User(payload);
await user.save(); await user.save();
res.status(201).json(Log.info(201, 'user was successfully signed up')); res.status(201).json(Log.info(201, "user was successfully signed up"));
} catch (err: any) { } catch (err: any) {
if (err.code == 11000) { if (err.code == 11000) {
res.status(400).json(Log.error(400, 'this user already exists')); res.status(400).json(Log.error(400, "this user already exists"));
return; return;
} }
Log.error(500, err); Log.error(500, err);
res.status(500).json(Log.error(500, 'something went wrong')); res.status(500).json(Log.error(500, "something went wrong"));
} }
} }
new Docs('user', 'signin', '/api/v1/auth/signin', 'POST', 'user signin api', undefined, signinExam, 'status object'); new Docs("user", "signin", "/api/v1/auth/signin", "POST", "user signin api", undefined, signinExam, "status object");
export async function signin_post(req: Request, res: Response) { export async function signin_post(req: Request, res: Response) {
try { try {
const payload: ISignin = req.body; const payload: ISignin = req.body;
const user = await User.findOne({ email: payload.email }); const user = await User.findOne({ email: payload.email });
if (!user) { if (!user) {
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); res.cookie("jwt", "", { httpOnly: true, maxAge: 0 });
res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); res.cookie("auth", false, { httpOnly: false, maxAge: 0 });
res.status(401).json(Log.error(401, 'email or password is wrong')); res.status(401).json(Log.error(401, "email or password is wrong"));
return; return;
} }
@@ -44,38 +44,47 @@ export async function signin_post(req: Request, res: Response) {
const maxAge = 3 * 24 * 60 * 60; // 3 days in seconds const maxAge = 3 * 24 * 60 * 60; // 3 days in seconds
const createToken = (id: any) => { const createToken = (id: any) => {
return jwt.sign({ id }, env.JWT_SECRET, { return jwt.sign({ id }, env.JWT_SECRET, {
expiresIn: maxAge expiresIn: maxAge,
}); });
}; };
const token = createToken(user._id); const token = createToken(user._id);
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 }); res.cookie("jwt", token, { httpOnly: true, maxAge: maxAge * 1000 });
res.cookie('auth', true, { httpOnly: false, maxAge: maxAge * 1000 }); res.cookie("auth", true, { httpOnly: false, maxAge: maxAge * 1000 });
res.json(Log.info(200, 'user is logged in')); res.json(Log.info(200, "user is logged in", { jwt: token }));
return; return;
} }
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); res.cookie("jwt", "", { httpOnly: true, maxAge: 0 });
res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); res.cookie("auth", false, { httpOnly: false, maxAge: 0 });
res.status(401).json(Log.error(401, 'email or password is wrong')); res.status(401).json(Log.error(401, "email or password is wrong"));
} catch (err: any) { } catch (err: any) {
Log.error(500, err); Log.error(500, err);
res.status(500).json(Log.error(500, 'something went wrong')); res.status(500).json(Log.error(500, "something went wrong"));
} }
} }
new Docs('user', 'logout', '/api/v1/auth/logout', 'POST', 'user logout api', undefined, {}, 'status object'); new Docs("user", "logout", "/api/v1/auth/logout", "POST", "user logout api", undefined, {}, "status object");
export function logout_post(req: Request, res: Response) { export function logout_post(req: Request, res: Response) {
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); res.cookie("jwt", "", { httpOnly: true, maxAge: 0 });
res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); res.cookie("auth", false, { httpOnly: false, maxAge: 0 });
res.json(Log.info(200, 'user was logged out')); res.json(Log.info(200, "user was logged out"));
} }
new Docs('user', 'status', '/api/v1/auth/status', 'GET', 'user login status api', undefined, undefined, 'status code | user object'); new Docs(
"user",
"status",
"/api/v1/auth/status",
"GET",
"user login status api",
undefined,
undefined,
"status code | user object",
);
export function status_get(req: Request, res: Response) { export function status_get(req: Request, res: Response) {
let userObject = res.locals.user; let userObject = res.locals.user;
userObject.password = undefined; userObject.password = undefined;
userObject.__v = undefined; userObject.__v = undefined;
res.status(200).json(Log.info(200, 'user is logged in', userObject)); res.status(200).json(Log.info(200, "user is logged in", userObject));
} }

View File

@@ -0,0 +1,127 @@
import { Request, Response } from "express";
import Beer from "../models/Beer";
import { isValidObjectId, Types } from "mongoose";
import fs from "fs";
import path from "path";
import { Log } from "nork";
import Docs from "../services/docsService";
import { addExam, delExam, editExam, IBeer } from "../validators/beerValidator";
new Docs(
"beer",
"add",
"/api/v1/beer/add",
"POST",
"beer add api",
undefined,
{ ...addExam, photos: "optional field | max 4 images | formData" },
"status object | beer object",
);
export async function add_post(req: Request, res: Response) {
try {
if (req.files) {
req.body.imgs = [];
const files: any = req.files;
files.forEach((el: any) => {
req.body.imgs.push(el.filename);
});
}
const beer = new Beer(req.body);
await beer.save();
res.status(201).json(Log.info(201, "beer was created", beer));
} catch (err: any) {
Log.error(500, "error in add_post", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}
new Docs(
"beer",
"get",
"/api/v1/beer/get",
"GET",
"beer get api",
undefined,
undefined,
"status object | array of beer objects",
);
export async function get_get(req: Request, res: Response) {
try {
const beer = await Beer.find({}, "-__v");
res.status(200).json(Log.info(200, "beers fetched", beer));
} catch (err: any) {
Log.error(500, "error in get_get", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}
new Docs("beer", "del", "/api/v1/beer/del", "POST", "beer del api", undefined, delExam, "status object");
export async function del_post(req: Request, res: Response) {
try {
if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id");
const beer = await Beer.deleteOne(new Types.ObjectId(req.body._id));
if (beer.deletedCount > 0) {
res.status(200).json(Log.info(200, `beer ${req.body._id} deleted`));
return;
}
throw Log.error(400, `beer ${req.body._id} does not exist`);
} catch (err: any) {
if (err.code) {
res.status(err.code).json(err);
return;
}
Log.error(500, "error in del_post", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}
new Docs(
"beer",
"edit",
"/api/v1/beer/edit",
"POST",
"beer edit api",
undefined,
{ ...editExam, photos: "optional field | max 4 images | formData" },
"status object | beer data",
);
export async function edit_post(req: Request, res: Response) {
try {
if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id");
if (req.files) {
if (!req.body.imgs) {
req.body.imgs = [];
}
if (typeof req.body.imgs == "string") {
req.body.imgs = [req.body.imgs];
}
if (req.body.imgs.length + req.files.length > 4) {
req.body.imgs.forEach((el: string[]) => {
fs.rmSync(path.join(__dirname, "../../uploads/" + el));
});
throw Log.error(400, "exceeds the 4 image limit");
}
const files: any = req.files;
files.forEach((el: any) => {
req.body.imgs.push(el.filename);
});
}
const payload = { ...req.body };
const beer = await Beer.findOneAndUpdate(new Types.ObjectId(req.body._id), payload, { new: true });
res.json(Log.info(200, `beer ${req.body._id} edited`, beer));
} catch (err: any) {
if (err.code && typeof err.code == "number") {
res.status(err.code).json(err);
return;
}
Log.error(500, "error in del_post", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}

View File

@@ -0,0 +1,14 @@
import { Request, Response } from "express";
import path from "path";
import fs from "fs";
import { Log } from "nork";
import { Docs } from "../services/docsService";
new Docs("docs", "get_all", "/api/v1", "GET", "Get docs json", undefined, undefined, "docs json");
export function docs_get(req: Request, res: Response) {
try {
res.json(JSON.parse(fs.readFileSync(path.join(__dirname, "../public/api.json")).toString()));
} catch (err: any) {
res.status(500).json(Log.error(500, "api.json docs file does not exists under public folder"));
}
}

View File

@@ -0,0 +1,71 @@
import { Request, Response } from "express";
import Review from "../models/Review";
import { isValidObjectId, Types } from "mongoose";
import { Log } from "nork";
import Docs from "../services/docsService";
import { addExam, delExam, IReview } from "../validators/reviewValidator";
new Docs(
"review",
"add",
"/api/v1/review/add",
"POST",
"review add api",
undefined,
addExam,
"status object | review object",
);
export async function add_post(req: Request, res: Response) {
try {
const data: IReview = req.body;
data.user_id = res.locals.user._id
const review = new Review(data);
await review.save();
res.status(201).json(Log.info(201, "review was added", review));
} catch (err) {
Log.error(500, "error while adding review", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}
new Docs(
"review",
"get",
"/api/v1/review/get",
"GET",
"review get api",
undefined,
undefined,
"status object | array of review objects",
);
export async function get_get(req: Request, res: Response) {
try {
const review = await Review.find({}, "-__v");
res.status(200).json(Log.info(200, "reviews fetched", review));
} catch (err) {
Log.error(500, "error while geting reviews", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}
new Docs("review", "del", "/api/v1/review/del", "POST", "review del api", undefined, delExam, "status object");
export async function del_post(req: Request, res: Response) {
try {
if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id");
const review = await Review.deleteOne(new Types.ObjectId(req.body._id));
if (review.deletedCount > 0) {
res.status(200).json(Log.info(200, `review ${req.body._id} deleted`));
return;
}
throw Log.error(400, `review ${req.body._id} does not exist`);
} catch (err: any) {
if (err.code) {
res.status(err.code).json(err);
return;
}
Log.error(500, "error in del_post", err);
res.status(500).json(Log.error(500, "something went wrong"));
}
}

View File

@@ -1,9 +1,9 @@
import { Request, Response, NextFunction } from 'express'; import { Request, Response, NextFunction } from "express";
import jwt from 'jsonwebtoken'; import jwt from "jsonwebtoken";
import env from '../config/environment'; import env from "../config/environment";
import { Log } from 'nork'; import { Log } from "nork";
import User from '../models/User'; import User from "../models/User";
import { isValidObjectId } from 'mongoose'; import { isValidObjectId } from "mongoose";
export function requireAuth(req: Request, res: Response, next: NextFunction) { export function requireAuth(req: Request, res: Response, next: NextFunction) {
const token = req.cookies?.jwt; const token = req.cookies?.jwt;
@@ -12,40 +12,40 @@ export function requireAuth(req: Request, res: Response, next: NextFunction) {
jwt.verify(token, env.JWT_SECRET, async (err: any, decodedToken: any) => { jwt.verify(token, env.JWT_SECRET, async (err: any, decodedToken: any) => {
if (err) { if (err) {
// console.error(err.message) // console.error(err.message)
res.status(401).send(Log.error(401, 'user is not authenticated')); res.status(401).send(Log.error(401, "user is not authenticated"));
} }
if (!err) { if (!err) {
const user = await User.findById(decodedToken.id); const user = await User.findById(decodedToken.id);
if (user === null) { if (user === null) {
res.status(401).send(Log.error(401, 'user is not authenticated')); res.status(401).send(Log.error(401, "user is not authenticated"));
return; return;
} }
res.locals.user = user; res.locals.user = user;
Log.info(100, 'user is authenticated'); Log.info(100, "user is authenticated");
next(); next();
} }
}); });
} }
if (!token) { if (!token) {
res.status(401).send(Log.error(401, 'user is not authenticated')); res.status(401).send(Log.error(401, "user is not authenticated"));
} }
} }
export function requireVerified(req: Request, res: Response, next: NextFunction) { export function requireVerified(req: Request, res: Response, next: NextFunction) {
if (res.locals.user._id) { if (res.locals.user._id) {
if (res.locals.user.verified) { if (res.locals.user.verified) {
Log.info(100, 'user is verified'); Log.info(100, "user is verified");
next(); next();
return; return;
} }
res.status(403).json(Log.error(403, 'user is not verified')); res.status(403).json(Log.error(403, "user is not verified"));
return; return;
} }
if (!res.locals.user._id) { if (!res.locals.user._id) {
res.status(401).send(Log.error(401, 'user is not authenticated')); res.status(401).send(Log.error(401, "user is not authenticated"));
return; return;
} }
} }
@@ -53,33 +53,33 @@ export function requireVerified(req: Request, res: Response, next: NextFunction)
export class requireRole { export class requireRole {
static Admin(req: Request, res: Response, next: NextFunction) { static Admin(req: Request, res: Response, next: NextFunction) {
if (res.locals.user.admin) { if (res.locals.user.admin) {
Log.info(100, 'user is admin'); Log.info(100, "user is admin");
next(); next();
return; return;
} }
res.status(403).json(Log.error(403, 'insufficient permissions')); res.status(403).json(Log.error(403, "insufficient permissions"));
return; return;
} }
static Owner(req: Request, res: Response, next: NextFunction) { static Owner(req: Request, res: Response, next: NextFunction) {
try { try {
if (!isValidObjectId(req.body.domain_id)) { if (!isValidObjectId(req.body.domain_id)) {
throw Log.error(400, 'neznámé domain_id'); throw Log.error(400, "neznámé domain_id");
} }
const domain = res.locals.user.domains.filter((domain: any) => domain.domain_id == req.body.domain_id); const domain = res.locals.user.domains.filter((domain: any) => domain.domain_id == req.body.domain_id);
console.log(domain); console.log(domain);
if (domain.length < 1) { if (domain.length < 1) {
throw Log.error(400, 'neznámé domain_id'); throw Log.error(400, "neznámé domain_id");
} }
if (domain[0].role == 1) { if (domain[0].role == 1) {
Log.info(100, 'user is owner'); Log.info(100, "user is owner");
next(); next();
return; return;
} }
res.status(403).json(Log.error(403, 'insufficient permissions')); res.status(403).json(Log.error(403, "insufficient permissions"));
return; return;
} catch (err: any) { } catch (err: any) {
res.status(400).json(err); res.status(400).json(err);

View File

@@ -0,0 +1,15 @@
import multer from "multer";
import { Log } from "nork";
import { Request, Response, NextFunction } from "express";
const validateMulterRequestMiddleware = async (err: any, req: Request, res: Response, next: NextFunction) => {
if (err instanceof multer.MulterError) {
Log.error(500, "error while processing uploaded files", JSON.stringify(err));
res.status(400).json(Log.error(400, "error while processing uploaded files"));
return;
} else {
next();
}
};
export default validateMulterRequestMiddleware;

View File

@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from 'express'; import { Request, Response, NextFunction } from "express";
import { object, AnySchema } from 'yup'; import { object, AnySchema } from "yup";
import { Log } from 'nork'; import { Log } from "nork";
const validate = (schema: AnySchema) => async (req: Request, res: Response, next: NextFunction) => { const validate = (schema: AnySchema) => async (req: Request, res: Response, next: NextFunction) => {
try { try {
@@ -8,7 +8,7 @@ const validate = (schema: AnySchema) => async (req: Request, res: Response, next
next(); next();
} catch (err: any) { } catch (err: any) {
return res.status(400).json(Log.error(400, 'validation error', err)); return res.status(400).json(Log.error(400, "validation error", err));
} }
}; };

34
api/src/models/Beer.ts Normal file
View File

@@ -0,0 +1,34 @@
import path from "path";
import { Schema, model } from "mongoose";
import { IBeer } from "../validators/beerValidator";
const schema = new Schema<IBeer | any>(
{
name: {
type: String,
required: true,
},
degree: {
type: Number,
required: true,
},
packaging: {
type: String,
required: true,
},
brand: {
type: String,
required: true,
},
imgs: {
type: Array,
required: false,
default: [],
},
},
{
timestamps: true,
},
);
export default model(path.basename(__filename).split(".")[0], schema);

45
api/src/models/Review.ts Normal file
View File

@@ -0,0 +1,45 @@
import path from "path";
import { Schema, model } from "mongoose";
import { IReview } from "../validators/reviewValidator";
const schema = new Schema<IReview | any>(
{
foam: {
type: Number,
required: true,
},
bitter_sweetness: {
type: Number,
required: true,
},
taste: {
type: Number,
required: true,
},
packaging: {
type: Number,
required: true,
},
sourness: {
type: Boolean,
required: true,
},
would_again: {
type: Boolean,
required: true,
},
beer_id: {
type: String,
required: true,
},
user_id: {
type: String,
required: true,
}
},
{
timestamps: true,
},
);
export default model(path.basename(__filename).split(".")[0], schema);

View File

@@ -1,26 +1,26 @@
import path from 'path'; import path from "path";
import { Schema, model } from 'mongoose'; import { Schema, model } from "mongoose";
import { IUser } from '../validators/authValidator'; import { IUser } from "../validators/authValidator";
const schema = new Schema<IUser>( const schema = new Schema<IUser>(
{ {
username: { username: {
type: String, type: String,
required: true required: true,
}, },
email: { email: {
type: String, type: String,
required: true, required: true,
unique: true unique: true,
}, },
password: { password: {
type: String, type: String,
required: true required: true,
} },
}, },
{ {
timestamps: true timestamps: true,
} },
); );
export default model(path.basename(__filename).split('.')[0], schema); export default model(path.basename(__filename).split(".")[0], schema);

1
api/src/public/api.json Normal file
View File

@@ -0,0 +1 @@
{"version":"2.0.0","endpoints":{"user":{"signup":{"name":"user","operation":"signup","route":"/api/v1/auth/signup","method":"POST","description":"user signup api","body":{"username":"testuser","email":"text@example.com","password":"Test1234"},"response":"status object"},"signin":{"name":"user","operation":"signin","route":"/api/v1/auth/signin","method":"POST","description":"user signin api","body":{"email":"text@example.com","password":"Test1234"},"response":"status object"},"logout":{"name":"user","operation":"logout","route":"/api/v1/auth/logout","method":"POST","description":"user logout api","body":{},"response":"status object"},"status":{"name":"user","operation":"status","route":"/api/v1/auth/status","method":"GET","description":"user login status api","response":"status code | user object"}},"beer":{"add":{"name":"beer","operation":"add","route":"/api/v1/beer/add","method":"POST","description":"beer add api","body":{"brand":"Pilsner Urqell","name":"Kozel","degree":11,"packaging":"can","photos":"optional field | max 4 images | formData"},"response":"status object | beer object"},"get":{"name":"beer","operation":"get","route":"/api/v1/beer/get","method":"GET","description":"beer get api","response":"status object | array of beer objects"},"del":{"name":"beer","operation":"del","route":"/api/v1/beer/del","method":"POST","description":"beer del api","body":{"_id":"6352b303b71cb62222f39895"},"response":"status object"},"edit":{"name":"beer","operation":"edit","route":"/api/v1/beer/edit","method":"POST","description":"beer edit api","body":{"_id":"6355b95dc03fad77bc380146","brand":"Pilsner Urqell","name":"Radegast","degree":12,"packaging":"bottle","imgs":[],"photos":"optional field | max 4 images | formData"},"response":"status object | beer data"}},"docs":{"get_all":{"name":"docs","operation":"get_all","route":"/api/v1","method":"GET","description":"Get docs json","response":"docs json"}},"review":{"add":{"name":"review","operation":"add","route":"/api/v1/review/add","method":"POST","description":"review add api","body":{"beer_id":"6352b303b71cb62222f39895","foam":3,"bitter_sweetness":2,"taste":5,"packaging":3,"sourness":false,"would_again":true},"response":"status object | review object"},"get":{"name":"review","operation":"get","route":"/api/v1/review/get","method":"GET","description":"review get api","response":"status object | array of review objects"},"del":{"name":"review","operation":"del","route":"/api/v1/review/del","method":"POST","description":"review del api","body":{"_id":"6352b303b71cb62222f39895"},"response":"status object"}}}}

View File

@@ -1,14 +1,42 @@
import { Router } from "express"; import { Router } from "express";
import multer from "multer";
import path from "path";
import * as authController from "../controllers/authController"; import * as authController from "../controllers/authController";
import validate from '../middlewares/validateRequest' import * as beerController from "../controllers/beerController";
import * as AuthVal from '../validators/authValidator' import * as docsController from "../controllers/docsController";
import * as reviewController from "../controllers/reviewController";
import { requireAuth } from "../middlewares/authMiddleware"; import { requireAuth } from "../middlewares/authMiddleware";
import validate from "../middlewares/validateRequest";
import valMulter from "../middlewares/validateMulterRequest";
import * as AuthVal from "../validators/authValidator";
import * as BVal from "../validators/beerValidator";
import * as RVal from "../validators/reviewValidator";
const upload = multer({ dest: path.resolve(__dirname, "../../uploads") });
const router = Router(); const router = Router();
router.post("/auth/signup",validate(AuthVal.signup) , authController.signup_post); router.get("/", docsController.docs_get);
router.post("/auth/signin",validate(AuthVal.signin) , authController.signin_post);
router.post("/auth/signup", validate(AuthVal.signup), authController.signup_post);
router.post("/auth/signin", validate(AuthVal.signin), authController.signin_post);
router.post("/auth/logout", requireAuth, authController.logout_post); router.post("/auth/logout", requireAuth, authController.logout_post);
router.get("/auth/status", requireAuth, authController.status_get); router.get("/auth/status", requireAuth, authController.status_get);
router.post(
"/beer/add",
[requireAuth, upload.array("photos", 4), valMulter, validate(BVal.add)],
beerController.add_post,
);
router.get("/beer/get", [requireAuth], beerController.get_get);
router.post("/beer/del", [requireAuth, validate(BVal.del)], beerController.del_post);
router.post(
"/beer/edit",
[requireAuth, upload.array("photos", 4), valMulter, validate(BVal.edit)],
beerController.edit_post,
);
router.post("/review/add", [requireAuth, validate(RVal.add)], reviewController.add_post);
router.get("/review/get", requireAuth, reviewController.get_get);
export default router; export default router;

View File

@@ -5,11 +5,11 @@ export const router = Router();
router.use("/api/v1", api_v1); router.use("/api/v1", api_v1);
//router.get("*", (req: Request, res: Response) => { router.get("*", (req: Request, res: Response) => {
// res.sendFile(path.join(__dirname, "../views/index.html")); res.sendFile(path.join(__dirname, "../public/index.html"));
//}); });
// 404 // 404
router.use((req: Request, res: Response) => { router.use((req: Request, res: Response) => {
res.status(404).send("Error 404\n"); res.status(404).send("Error 404\n");
}); });

View File

@@ -1,7 +1,7 @@
import http from "http"; import http from "http";
import { app } from "./app"; import { app } from "./app";
import env from "./config/environment"; import env from "./config/environment";
import mongoose from 'mongoose' // TODO: dopsat nork module pro db import mongoose from "mongoose"; // TODO: dopsat nork module pro db
import { Log } from "nork"; import { Log } from "nork";
const port: number = env.APP_PORT || 8080; const port: number = env.APP_PORT || 8080;
@@ -23,13 +23,11 @@ export const server = http.createServer(app);
// runServer() // runServer()
//} //}
(async () => { (async () => {
if (!process.env.DOCS_GEN) { if (!process.env.DOCS_GEN) {
try { try {
await mongoose.connect(env.DB_URI); await mongoose.connect(env.DB_URI);
Log.info(200, 'connected to db'); Log.info(200, "connected to db");
server.listen(port, () => { server.listen(port, () => {
Log.info(200, `Server is listening on http://localhost:${port}`); Log.info(200, `Server is listening on http://localhost:${port}`);
}); });

View File

@@ -1,8 +1,8 @@
import fs from 'fs'; import fs from "fs";
import path from 'path'; import path from "path";
export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE'; export type HttpMethods = "POST" | "GET" | "PUT" | "DELETE";
export type ApiResponse = 'status object' | Object | string; export type ApiResponse = "status object" | Object | string;
export class Docs { export class Docs {
private name: string; private name: string;
@@ -14,7 +14,16 @@ export class Docs {
private body?: Object; private body?: Object;
private response?: ApiResponse; private response?: ApiResponse;
public constructor(name: string, operation: string, route: string, method: HttpMethods, description?: string, parameters?: Object[], body?: Object, response?: ApiResponse) { public constructor(
name: string,
operation: string,
route: string,
method: HttpMethods,
description?: string,
parameters?: Object[],
body?: Object,
response?: ApiResponse,
) {
this.name = name; this.name = name;
this.operation = operation; this.operation = operation;
this.route = route; this.route = route;
@@ -32,14 +41,14 @@ export class Docs {
return false; return false;
} }
const jsonPath = path.join(__dirname, '../public/api.json'); const jsonPath = path.join(__dirname, "../public/api.json");
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json')).toString()); const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json")).toString());
const jsonAPI = () => JSON.parse(fs.readFileSync(jsonPath).toString()); const jsonAPI = () => JSON.parse(fs.readFileSync(jsonPath).toString());
const genJsonAPI = () => fs.writeFileSync(jsonPath, JSON.stringify({ version: pkg.version, endpoints: {} })); const genJsonAPI = () => fs.writeFileSync(jsonPath, JSON.stringify({ version: pkg.version, endpoints: {} }));
if (!fs.existsSync(path.join(__dirname, '../public'))) { if (!fs.existsSync(path.join(__dirname, "../public"))) {
fs.mkdirSync(path.join(__dirname, '../public')); fs.mkdirSync(path.join(__dirname, "../public"));
} }
if (!fs.existsSync(jsonPath)) { if (!fs.existsSync(jsonPath)) {

View File

@@ -1,6 +1,6 @@
import * as shell from 'shelljs'; import * as shell from "shelljs";
// Copy all the view templates // Copy all the view templates
//shell.cp('-R', 'src/views', 'dist/') //shell.cp('-R', 'src/views', 'dist/')
//shell.cp('-R', 'src/public', 'dist/'); shell.cp("-R", "src/public", "dist/");
shell.cp('-u', 'src/.env', 'dist/'); shell.cp("-u", "src/.env", "dist/");

View File

@@ -1,10 +1,10 @@
const mongoose = require('mongoose'); const mongoose = require("mongoose");
const { MongoMemoryServer } = require('mongodb-memory-server'); const { MongoMemoryServer } = require("mongodb-memory-server");
let mongo: any = null; let mongo: any = null;
const connectDB = async () => { const connectDB = async () => {
mongo = await MongoMemoryServer.create({ binary: { os: { os: 'linux', dist: 'ubuntu', release: '18.04' } } }); // TODO: check that host OS is Void Linux, else remove the argument mongo = await MongoMemoryServer.create({ binary: { os: { os: "linux", dist: "ubuntu", release: "18.04" } } }); // TODO: check that host OS is Void Linux, else remove the argument
const uri = mongo.getUri(); const uri = mongo.getUri();
await mongoose.connect(uri); await mongoose.connect(uri);

View File

@@ -1,7 +1,7 @@
import * as yup from 'yup'; import * as yup from "yup";
import YupPassword from 'yup-password'; import YupPassword from "yup-password";
YupPassword(yup); YupPassword(yup);
import { Schema } from 'mongoose'; import { Schema } from "mongoose";
interface mongooseAddition { interface mongooseAddition {
_id?: Schema.Types.ObjectId; _id?: Schema.Types.ObjectId;
@@ -13,22 +13,22 @@ interface mongooseAddition {
export const signup = yup.object({ export const signup = yup.object({
username: yup.string().required(), username: yup.string().required(),
email: yup.string().email().required(), email: yup.string().email().required(),
password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required() password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required(),
}); });
export interface IUser extends yup.InferType<typeof signup>, mongooseAddition {} export interface IUser extends yup.InferType<typeof signup>, mongooseAddition {}
export const signupExam: IUser = { export const signupExam: IUser = {
username: 'testuser', username: "testuser",
email: 'text@example.com', email: "text@example.com",
password: 'Test1234' password: "Test1234",
}; };
// SignIn // SignIn
export const signin = yup.object({ export const signin = yup.object({
email: yup.string().email().required(), email: yup.string().email().required(),
password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required() password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required(),
}); });
export interface ISignin extends yup.InferType<typeof signin>, mongooseAddition {} export interface ISignin extends yup.InferType<typeof signin>, mongooseAddition {}
export const signinExam: ISignin = { export const signinExam: ISignin = {
email: 'text@example.com', email: "text@example.com",
password: 'Test1234' password: "Test1234",
}; };

View File

@@ -0,0 +1,70 @@
import * as yup from "yup";
import YupPassword from "yup-password";
YupPassword(yup);
import { Schema } from "mongoose";
interface mongooseAddition {
_id?: Schema.Types.ObjectId;
createdAt?: Schema.Types.Date;
updatedAt?: Schema.Types.Date;
}
// Create
export const add = yup.object({
brand: yup.string().required(),
name: yup.string().required(),
degree: yup.number().required(),
packaging: yup.string().required(),
});
export interface IBeer extends yup.InferType<typeof add>, mongooseAddition {}
export const addExam: IBeer = {
brand: "Pilsner Urqell",
name: "Kozel",
degree: 11,
packaging: "can",
};
// Remove
export const del = yup.object({
_id: yup.string().required(),
});
export interface IDel extends yup.InferType<typeof del> {}
export const delExam: IDel = {
_id: "6352b303b71cb62222f39895",
};
// Update
export const edit = yup.object({
_id: yup.string().required(),
brand: yup.string(),
name: yup.string(),
degree: yup.number(),
packaging: yup.string(),
//imgs: yup.mixed().when('$imgs', (imgs, schema) =>
// Array.isArray(imgs) ? schema.array() : schema.string()
//)
imgs: yup
.mixed()
.test(
"is-array-or-string",
"imgs must be either an array or a string",
(value) => Array.isArray(value) || typeof value === "string",
),
//imgs: yup.mixed().when('isArray', {
// is: Array.isArray,
// then: yup.array(),
// otherwise: yup.string()
//})
});
export interface IEdit extends yup.InferType<typeof edit> {}
export const editExam: IEdit = {
_id: "6355b95dc03fad77bc380146",
brand: "Pilsner Urqell",
name: "Radegast",
degree: 12,
packaging: "bottle",
imgs: [],
};

View File

@@ -0,0 +1,43 @@
import * as yup from "yup";
import mongoose, { Schema } from "mongoose";
interface mongooseAddition {
_id?: Schema.Types.ObjectId;
createdAt?: Schema.Types.Date;
updatedAt?: Schema.Types.Date;
}
let objectIdSchema = yup
.string()
.test("is-objectId", "Invalid ObjectId", (value: any) => mongoose.Types.ObjectId.isValid(value));
// Add
export const add = yup.object({
beer_id: objectIdSchema,
foam: yup.number().min(1).max(3).required(),
bitter_sweetness: yup.number().min(1).max(5).required(),
taste: yup.number().min(1).max(5).required(),
packaging: yup.number().min(1).max(5).required(),
sourness: yup.boolean().required(),
would_again: yup.boolean().required(),
user_id: yup.string().notRequired()
});
export interface IReview extends yup.InferType<typeof add>, mongooseAddition {}
export const addExam: IReview = {
beer_id: "6352b303b71cb62222f39895",
foam: 3,
bitter_sweetness: 2,
taste: 5,
packaging: 3,
sourness: false,
would_again: true,
};
// Remove
export const del = yup.object({
_id: objectIdSchema.required(),
});
export interface IDel extends yup.InferType<typeof del> {}
export const delExam: IDel = {
_id: "6352b303b71cb62222f39895",
};

View File

@@ -1,4 +1,4 @@
import { connectDB, dropDB, dropCollections } from '../src/utils/test_mongodb'; import { connectDB, dropDB, dropCollections } from "../src/utils/test_mongodb";
beforeAll(async () => { beforeAll(async () => {
await connectDB(); await connectDB();

View File

@@ -1,22 +1,22 @@
import supertest from 'supertest'; import supertest from "supertest";
import { app } from '../src/app'; import { app } from "../src/app";
import { connectDB, dropDB, dropCollections } from '../src/utils/test_mongodb'; import { connectDB, dropDB, dropCollections } from "../src/utils/test_mongodb";
const request = supertest(app); const request = supertest(app);
export const getJWT = async () => { export const getJWT = async () => {
try { try {
const resReg: any = await request.post('/api/v1/auth/signup').send({ const resReg: any = await request.post("/api/v1/auth/signup").send({
email: 'test@example.local', email: "test@example.local",
password: 'admin1234', password: "admin1234",
username: 'Test Test' username: "Test Test",
}); });
const resLog: any = await request.post('/api/auth/login').send({ const resLog: any = await request.post("/api/auth/login").send({
email: 'test@example.local', email: "test@example.local",
password: 'admin1234' password: "admin1234",
}); });
if (resLog.statusCode != 200) throw 'error while logging in'; if (resLog.statusCode != 200) throw "error while logging in";
const body = JSON.parse(resLog.text); const body = JSON.parse(resLog.text);
return Promise.resolve(body.data.jwt); return Promise.resolve(body.data.jwt);
@@ -31,191 +31,194 @@ export const getJWT = async () => {
* @returns JWT cookie * @returns JWT cookie
*/ */
export async function login(): Promise<string> { export async function login(): Promise<string> {
const res = await request.post('/api/v1/auth/signin').send({ const res = await request.post("/api/v1/auth/signin").send({
email: 'thisistest@host.local', email: "thisistest@host.local",
password: 'Admin1234' password: "Admin1234",
}); });
return res.headers['set-cookie']; return res.headers["set-cookie"];
} }
export async function signup(): Promise<boolean> { export async function signup(): Promise<boolean> {
const res = await request.post('/api/v1/auth/signup').send({ const res = await request.post("/api/v1/auth/signup").send({
email: 'thisistest@host.local', email: "thisistest@host.local",
password: 'Admin1234', password: "Admin1234",
username: 'Test Test' username: "Test Test",
}); });
if (res.statusCode == 201) return true; if (res.statusCode == 201) return true;
return false; return false;
} }
describe('POST /api/v1/auth/signup', () => { describe("POST /api/v1/auth/signup", () => {
describe('should drop validation error', () => { describe("should drop validation error", () => {
it('should drop 400 (empty request))', async () => { it("should drop 400 (empty request))", async () => {
const res: any = await request.post('/api/v1/auth/signup').send({}); const res: any = await request.post("/api/v1/auth/signup").send({});
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
}); });
it('should drop 400 (email))', async () => { it("should drop 400 (email))", async () => {
const res: any = await request.post('/api/v1/auth/signup').send({ const res: any = await request.post("/api/v1/auth/signup").send({
email: '', email: "",
username: 'User Admin', username: "User Admin",
password: 'Admin1234' password: "Admin1234",
}); });
console.log(res) console.log(res);
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('email'); expect(body.data.path).toBe("email");
}); });
it('should drop 400 (username))', async () => { it("should drop 400 (username))", async () => {
const res: any = await request.post('/api/v1/auth/signup').send({ const res: any = await request.post("/api/v1/auth/signup").send({
email: 'admin@localhost.local', email: "admin@localhost.local",
username: '', username: "",
password: 'Admin1234' password: "Admin1234",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('username'); expect(body.data.path).toBe("username");
}); });
it('should drop 400 (password))', async () => { it("should drop 400 (password))", async () => {
const res: any = await request.post('/api/v1/auth/signup').send({ const res: any = await request.post("/api/v1/auth/signup").send({
email: 'admin@localhost.local', email: "admin@localhost.local",
username: 'User Admin', username: "User Admin",
password: '' password: "",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('password'); expect(body.data.path).toBe("password");
}); });
it('should drop 400 (password - min 8 chars', async () => { it("should drop 400 (password - min 8 chars", async () => {
const res = await request.post('/api/v1/auth/signup').send({ const res = await request.post("/api/v1/auth/signup").send({
email: 'admin@localhost.local', email: "admin@localhost.local",
username: 'User Admin', username: "User Admin",
password: 'Admin12' password: "Admin12",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('password'); expect(body.data.path).toBe("password");
}); });
it('should drop 400 (password - min 1 number', async () => { it("should drop 400 (password - min 1 number", async () => {
const res = await request.post('/api/v1/auth/signup').send({ const res = await request.post("/api/v1/auth/signup").send({
email: 'admin@localhost.local', email: "admin@localhost.local",
username: 'User Admin', username: "User Admin",
password: 'Adminadmin' password: "Adminadmin",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('password'); expect(body.data.path).toBe("password");
}); });
it('should drop 400 (password - min 1 uppercase', async () => { it("should drop 400 (password - min 1 uppercase", async () => {
const res = await request.post('/api/v1/auth/signup').send({ const res = await request.post("/api/v1/auth/signup").send({
email: 'admin@localhost.local', email: "admin@localhost.local",
username: 'User Admin', username: "User Admin",
password: 'admin1234' password: "admin1234",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('password'); expect(body.data.path).toBe("password");
}); });
}); });
test('should register an user', async () => { test("should register an user", async () => {
const res: any = await request.post('/api/v1/auth/signup').send({ const res: any = await request.post("/api/v1/auth/signup").send({
email: 'thisistest@host.local', email: "thisistest@host.local",
password: 'Admin1234', password: "Admin1234",
username: 'Test Test' username: "Test Test",
}); });
expect(res.statusCode).toBe(201); expect(res.statusCode).toBe(201);
}); });
}); });
describe('POST /api/v1/auth/signin', () => { describe("POST /api/v1/auth/signin", () => {
const url = '/api/v1/auth/signin'; const url = "/api/v1/auth/signin";
describe('should drop an validation error', () => { describe("should drop an validation error", () => {
it('should drop 400 (empty)', async () => { it("should drop 400 (empty)", async () => {
const res = await request.post(url).send(); const res = await request.post(url).send();
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
}); });
it('should drop 400 (email)', async () => { it("should drop 400 (email)", async () => {
const res = await request.post(url).send({ const res = await request.post(url).send({
password: 'Admin1234' password: "Admin1234",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('email'); expect(body.data.path).toBe("email");
}); });
it('should drop 400 (password)', async () => { it("should drop 400 (password)", async () => {
const res = await request.post(url).send({ const res = await request.post(url).send({
email: 'thisistest@host.local' email: "thisistest@host.local",
}); });
const body = JSON.parse(res.text); const body = JSON.parse(res.text);
expect(res.statusCode).toBe(400); expect(res.statusCode).toBe(400);
expect(body.data.path).toBe('password'); expect(body.data.path).toBe("password");
}); });
}); });
test('should drop 401', async () => { test("should drop 401", async () => {
const res = await request.post(url).send({ const res = await request.post(url).send({
email: 'thisistest@host.local', email: "thisistest@host.local",
password: 'Test12365465132' password: "Test12365465132",
}); });
expect(res.statusCode).toBe(401); expect(res.statusCode).toBe(401);
expect(res.header['set-cookie'][0]).toContain("jwt=; Max-Age=0") expect(res.header["set-cookie"][0]).toContain("jwt=; Max-Age=0");
expect(res.header['set-cookie'][1]).toContain("auth=false") expect(res.header["set-cookie"][1]).toContain("auth=false");
}); });
test('should login an user', async () => { test("should login an user", async () => {
const res: any = await request.post(url).send({ const res: any = await request.post(url).send({
email: 'thisistest@host.local', email: "thisistest@host.local",
password: 'Admin1234' password: "Admin1234",
}); });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(res.header['set-cookie'][0]).toContain("jwt=") expect(res.header["set-cookie"][0]).toContain("jwt=");
expect(res.header['set-cookie'][1]).toContain("auth=true") expect(res.header["set-cookie"][1]).toContain("auth=true");
}); });
}); });
describe('POST /api/v1/auth/logout', () => { describe("POST /api/v1/auth/logout", () => {
const url = '/api/v1/auth/logout'; const url = "/api/v1/auth/logout";
test('should drop 401 error', async () => { test("should drop 401 error", async () => {
const res = await request.post(url).send({}); const res = await request.post(url).send({});
expect(res.statusCode).toBe(401); expect(res.statusCode).toBe(401);
}); });
test('should logout an user', async () => { test("should logout an user", async () => {
const jwt = await login(); const jwt = await login();
const res = await request.post(url).set('Cookie', jwt).send(); const res = await request.post(url).set("Cookie", jwt).send();
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(res.header['set-cookie'][0]).toContain("jwt=; Max-Age=0") expect(res.header["set-cookie"][0]).toContain("jwt=; Max-Age=0");
expect(res.header['set-cookie'][1]).toContain("auth=false") expect(res.header["set-cookie"][1]).toContain("auth=false");
}); });
}); });
describe('GET /api/v1/auth/status', () => { describe("GET /api/v1/auth/status", () => {
const url = '/api/v1/auth/status'; const url = "/api/v1/auth/status";
test('should return login status 401', async () => { test("should return login status 401", async () => {
const res = await request.get(url).send(); const res = await request.get(url).send();
expect(res.statusCode).toBe(401); expect(res.statusCode).toBe(401);
}); });
test('should return login status 200', async () => { test("should return login status 200", async () => {
const jwt = await login(); const jwt = await login();
const res = await request.get(url).set('Cookie', jwt).send(); const res = await request.get(url).set("Cookie", jwt).send();
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(res.body.data.username).toBe("Test Test");
expect(res.body.data.email).toBe("thisistest@host.local");
expect(res.body.data.password).toBeUndefined();
}); });
}); });

202
api/tests/beer.test.ts Normal file
View File

@@ -0,0 +1,202 @@
import supertest from "supertest";
import { app } from "../src/app";
import { login } from "./auth.test";
import { addExam, delExam, editExam } from "../src/validators/beerValidator";
const request = supertest(app);
describe("POST /api/v1/beer/add", () => {
const url = "/api/v1/beer/add";
test("should drop 401 error", async () => {
const res = await request.post(url).send({});
expect(res.statusCode).toBe(401);
});
test("should drop 400 ()", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send({});
expect(res.statusCode).toBe(400);
});
test("should drop 400 (name)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.name;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (degree)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.degree;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (packaging)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.packaging;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (brand)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.brand;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 201", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send(addExam);
expect(res.statusCode).toBe(201);
});
});
describe("GET /api/v1/beer/get", () => {
const url = "/api/v1/beer/get";
test("should drop 401", async () => {
const res = await request.get(url).send();
expect(res.statusCode).toBe(401);
});
test("should drop 200", async () => {
const jwt = await login();
const res = await request.get(url).set("Cookie", jwt).send();
expect(res.statusCode).toBe(200);
});
});
describe("POST /api/v1/beer/del", () => {
const url = "/api/v1/beer/del";
test("should drop 401", async () => {
const res = await request.post(url).send();
expect(res.statusCode).toBe(401);
});
test("should drop 400", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send(delExam);
expect(res.statusCode).toBe(400);
});
test("should drop 400", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send({
_id: "thisWillNotWork",
});
expect(res.statusCode).toBe(400);
});
test("should drop 200", async () => {
const jwt = await login();
const req = await request.post("/api/v1/beer/add").set("Cookie", jwt).send(addExam);
const id = req.body.data._id;
const res = await request.post(url).set("Cookie", jwt).send({
_id: id,
});
expect(res.statusCode).toBe(200);
});
});
describe("POST /api/v1/beer/edit", () => {
const url = "/api/v1/beer/edit";
test("should drop 401", async () => {
const res = await request.post(url).send();
expect(res.statusCode).toBe(401);
});
test("should drop 400", async () => {
const jwt = await login();
const payload: any = { ...editExam };
delete payload._id;
const res = await request.post(url).set("Cookie", jwt).send(payload);
expect(res.statusCode).toBe(400);
});
test("should drop 200", async () => {
const jwt = await login();
const payload: any = { ...editExam };
delete payload.name;
const res = await request.post(url).set("Cookie", jwt).send(payload);
expect(res.statusCode).toBe(200);
});
test("should drop 200", async () => {
const jwt = await login();
const payload: any = { ...editExam };
delete payload.degree;
const res = await request.post(url).set("Cookie", jwt).send(payload);
expect(res.statusCode).toBe(200);
});
test("should drop 200", async () => {
const jwt = await login();
const payload: any = { ...editExam };
delete payload.packaging;
const res = await request.post(url).set("Cookie", jwt).send(payload);
expect(res.statusCode).toBe(200);
});
test("should drop 200", async () => {
const jwt = await login();
const payload: any = { ...editExam };
delete payload.brand;
const res = await request.post(url).set("Cookie", jwt).send(payload);
expect(res.statusCode).toBe(200);
});
test("should drop 200", async () => {
const jwt = await login();
const req = await request.post("/api/v1/beer/add").set("Cookie", jwt).send(addExam);
const _id = req.body.data._id;
const payload = { ...editExam, _id: _id };
let res = await request.post(url).set("Cookie", jwt).send(payload);
delete res.body.data._id;
delete res.body.data.__v;
delete res.body.data.createdAt;
delete res.body.data.updatedAt;
delete payload._id;
const eq = JSON.stringify(Object.keys(res.body.data).sort()) === JSON.stringify(Object.keys(payload).sort());
expect(res.statusCode).toBe(200);
expect(eq).toBe(true);
});
});

12
api/tests/docs.test.ts Normal file
View File

@@ -0,0 +1,12 @@
import request from "supertest";
import { app } from "../src/app";
describe("GET /api/v1", () => {
describe("should return json with docs", () => {
test("should respond with a 200 status code", async () => {
const response = await request(app).get("/api/v1").send({});
expect(response.headers["content-type"]).toMatch(/json/);
expect(response.statusCode).toBe(200);
});
});
});

99
api/tests/review.test.ts Normal file
View File

@@ -0,0 +1,99 @@
import supertest from "supertest";
import { app } from "../src/app";
import { login } from "./auth.test";
import { addExam, delExam } from "../src/validators/reviewValidator";
const request = supertest(app);
describe("POST /api/v1/review/add", () => {
const url = "/api/v1/review/add";
test("should drop 401 error", async () => {
const res = await request.post(url).send({});
expect(res.statusCode).toBe(401);
});
test("should drop 400 ()", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send({});
expect(res.statusCode).toBe(400);
});
test("should drop 400 (foam)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.foam;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (bitter_sweetness)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.bitter_sweetness;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (taste)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.taste;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (packaging)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.packaging;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (sourness)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.sourness;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 400 (would_again)", async () => {
const jwt = await login();
const body: any = { ...addExam };
delete body.would_again;
const res = await request.post(url).set("Cookie", jwt).send(body);
expect(res.statusCode).toBe(400);
});
test("should drop 201", async () => {
const jwt = await login();
const res = await request.post(url).set("Cookie", jwt).send(addExam);
expect(res.statusCode).toBe(201);
});
});
describe("GET /api/v1/review/get", () => {
const url = "/api/v1/review/get";
test("should drop 401", async () => {
const res = await request.get(url).send();
expect(res.statusCode).toBe(401);
});
test("should drop 200", async () => {
const jwt = await login();
const res = await request.get(url).set("Cookie", jwt).send();
expect(res.statusCode).toBe(200);
});
});

1
frontend/.env.example Normal file
View File

@@ -0,0 +1 @@
EXPO_PUBLIC_API_URL=http://10.69.1.137:6060/api/v1

40
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,40 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo
.expo/
dist/
web-build/
# Native
*.orig.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
# Metro
.metro-health-check*
# debug
npm-debug.*
yarn-debug.*
yarn-error.*
# macOS
.DS_Store
*.pem
# local env files
.env*.local
# typescript
*.tsbuildinfo
.env
.vscode/
*.swp

41
frontend/app.json Normal file
View File

@@ -0,0 +1,41 @@
{
"expo": {
"name": "deguapp",
"slug": "deguapp",
"scheme": "deguapp",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"assetBundlePatterns": ["**/*"],
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"web": {
"favicon": "./assets/favicon.png"
},
"plugins": [
"expo-router",
[
"expo-image-picker",
{
"photosPermission": "The app accesses your photos to let you share them with your friends.",
"cameraPermission": "The app accesses your camera to let you take photos of your beer and share them with your friends.",
"microphonePermission": "The app accesses your microphone to let you record audio and share it with your friends."
}
],
"expo-secure-store"
]
}
}

View File

@@ -0,0 +1,76 @@
import React from "react";
import FontAwesome from "@expo/vector-icons/FontAwesome";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { Tabs } from "expo-router";
import { StyleSheet, View } from "react-native";
import { colors } from "@components/style";
import { StatusBar } from "expo-status-bar";
export default function TabLayout() {
return (
<View style={{ flex: 1 }}>
<StatusBar style="light" />
<Tabs
screenOptions={{
headerStyle: {
backgroundColor: colors.dark,
},
headerTintColor: "white",
tabBarStyle: {
backgroundColor: colors.darkSecondary,
},
tabBarActiveTintColor: colors.gold,
headerShown: true,
}}
sceneContainerStyle={{ backgroundColor: colors.dark }}
>
<Tabs.Screen
name="index"
options={{
title: "Home",
tabBarIcon: ({ color }) => (
<FontAwesome size={28} name="home" color={color} />
),
}}
/>
<Tabs.Screen
name="beer/index"
options={{
title: "Beers",
tabBarIcon: ({ color }) => (
<FontAwesome size={28} name="beer" color={color} />
),
}}
/>
<Tabs.Screen
name="review/index"
options={{
title: "Reviews",
tabBarIcon: ({ color }) => (
<MaterialIcons size={28} name="reviews" color={color} />
),
}}
/>
<Tabs.Screen
name="settings"
options={{
title: "Settings",
tabBarIcon: ({ color }) => (
<FontAwesome size={28} name="cog" color={color} />
),
}}
/>
{/* Hide following routes from bottom bar */}
<Tabs.Screen
name="beer/add"
options={{ href: null, title: "Add beer" }}
/>
<Tabs.Screen
name="review/add/[beer_id]"
options={{ href: null, title: "Add review" }}
/>
</Tabs>
</View>
);
}

View File

@@ -0,0 +1,263 @@
import { StyleSheet, TextInput, View, Image } from "react-native";
import { useState } from "react";
import Button from "@components/Button";
import Text from "@components/Text";
import { colors } from "@components/style";
import * as ImagePicker from "expo-image-picker";
import DropDownPicker from "react-native-dropdown-picker";
const DropdownTheme = require("@components/DropdownTheme");
import { Platform } from "react-native";
export default function BeerAdd() {
const [b_name, setBName] = useState("");
const [b_degree, setBDegree] = useState("");
const [b_packaging, setBPackaging] = useState(null);
const [b_brand, setBBrand] = useState("");
const [image, setImage] = useState(null);
const [open, setOpen] = useState(false);
const [items, setItems] = useState([
{ label: "Tank beer", value: "tank" },
{ label: "Keg beer", value: "keg" },
{ label: "Glass bottle", value: "glass" },
{ label: "Can", value: "can" },
{ label: "PET bottle", value: "pet" },
]);
DropDownPicker.addTheme("DropdownTheme", DropdownTheme);
DropDownPicker.setTheme("DropdownTheme");
ImagePicker.getCameraPermissionsAsync(); //check if the user has granted permission to access the camera
const pickImage = async () => {
const permissionResult =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("You've refused to allow this appp to access your photos!");
return;
}
// No permissions request is necessary for launching the image library
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [3, 4],
// quality: 1,
});
// Explore the result
console.log(result);
if (!result.canceled) {
setImage(result.assets[0]);
}
};
const openCamera = async () => {
// Ask the user for the permission to access the camera
const permissionResult = await ImagePicker.requestCameraPermissionsAsync();
if (permissionResult.granted === false) {
alert("You've refused to allow this app to access your camera!");
return;
}
const result = await ImagePicker.launchCameraAsync();
// Explore the result
console.log(result);
if (!result.canceled) {
setImage(result.assets[0]);
}
};
function validateDegreeInput(text) {
let newText = "";
let numbers = "0123456789.";
for (var i = 0; i < text.length; i++) {
if (numbers.indexOf(text[i]) > -1) {
newText = newText + text[i];
setBDegree(newText);
} else {
// your call back function
alert("Please enter numbers only.");
setBDegree("");
}
}
}
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(",")[0].indexOf("base64") >= 0)
byteString = atob(dataURI.split(",")[1]);
else byteString = unescape(dataURI.split(",")[1]);
// separate out the mime component
var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], { type: mimeString });
}
async function addBeer() {
// TODO: after the request - redirect to /beer/{new_beer_id}?; plus some modal about successful state
const data = new FormData();
if (Platform.OS == "web") {
// TODO: On phone its imposibble to upload an image
data.append("photos", dataURItoBlob(image.uri));
}
data.append("brand", b_brand);
data.append("name", b_name);
data.append("degree", b_degree);
data.append("packaging", "can");
try {
const req = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/beer/add`, {
method: "POST",
credentials: "include",
body: data,
});
const res = await req.json();
if (res.code == 201 && res.data._id) {
// TODO: reditect using expo router
// window.location.href = `/beer/${res.data._id}`;
alert("Added");
} else {
alert(
"Beer was not added successfully. Please check your data and try again.",
);
}
} catch (err) {
alert(
"Beer was not added successfully. Please check your data and try again.",
);
console.error(err);
}
}
return (
<View style={styles.container}>
<View style={styles.form}>
<Text style={styles.text}>
Spill your thoughts about the beer you just sipped!
</Text>
<TextInput
style={styles.input}
placeholder="Name"
value={b_name}
onChangeText={(text) => setBName(text)}
placeholderTextColor="#aaaaaa"
/>
<TextInput
style={styles.input}
placeholder="Brand"
value={b_brand}
onChangeText={(text) => setBBrand(text)}
placeholderTextColor="#aaaaaa"
/>
<TextInput
style={styles.input}
placeholder="Degree"
value={b_degree}
onChangeText={(text) => validateDegreeInput(text)}
placeholderTextColor="#aaaaaa"
keyboardType="numeric"
maxLength={3}
/>
<DropDownPicker
open={open}
value={b_packaging}
items={items}
setOpen={setOpen}
setValue={setBPackaging}
setItems={setItems}
placeholder={"What are you drinking from?"}
theme="DropdownTheme"
//searchable={true} //maybe we can use it later...
/>
<View style={styles.imageContainer}>
<Button
title="Open gallery"
onPress={pickImage}
buttonStyle={styles.imageButton}
textStyle={styles.imageTextButton}
/>
{Platform.OS != "web" ? (
<Button
title="Open camera"
onPress={openCamera}
buttonStyle={styles.imageButton}
textStyle={styles.imageTextButton}
/>
) : (
false
)}
</View>
{image && <Image source={{ uri: image.uri }} style={styles.image} />}
<Button title="Add beer" color={colors.gold} onPress={addBeer} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
alignItems: "center",
display: "flex",
},
form: {
alignItems: "center",
gap: 15,
width: "80%",
},
input: {
height: "auto",
width: "100%",
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
color: "#fff",
},
imageContainer: {
alignItems: "center",
justifyContent: "center",
display: "flex",
flexDirection: "row",
gap: 10,
},
imageButton: {
backgroundColor: colors.dark,
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
},
imageTextButton: {
color: colors.white,
},
image: {
width: 150,
height: 150,
},
text: {
color: colors.white,
fontSize: 24,
textAlign: "center",
paddingBottom: "3%",
paddingTop: "10%",
},
});

View File

@@ -0,0 +1,128 @@
import {
StyleSheet,
View,
FlatList,
Dimensions,
StatusBar,
Image,
} from "react-native";
import Text from "@components/Text";
import Button from "@components/Button";
import { colors } from "@components/style";
import { router } from "expo-router";
import { useEffect, useState } from "react";
// import { FlashList } from "@shopify/flash-list";
export default function Tab() {
const API_HOST = process.env.EXPO_PUBLIC_API_URL.replace("/api/v1", "");
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
async function fetchData() {
try {
const res = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/beer/get`, {
method: "GET",
credentials: "include",
});
const data = await res.json();
setData(data.data);
} catch (err) {
console.error(err);
alert("Something went wrong");
}
}
return (
<View style={styles.container}>
<Button
title="Add new beer"
color={colors.gold}
onPress={() => {
router.replace("/beer/add");
}}
/>
{/* <FlashList
data={data}
estimatedItemSize={100}
keyExtractor={(item) => String(item._id)}
renderItem={({ item }) => (
<View style={styles.item}>
<Text>Name: {item.name}</Text>
<Text>Brand: {item.brand}</Text>
<Text>Degree: {item.degree}</Text>
<Text>Packaging: {item.packaging}</Text>
</View>
)}
/> */}
<FlatList
data={data}
style={styles.beerList}
keyExtractor={(item) => String(item._id)}
renderItem={({ item }) => (
<View style={styles.item}>
<Image
source={
item.imgs[0]
? {
uri: `${API_HOST}/public/uploads/${item.imgs[0]}`,
}
: {
uri: "https://imagesvc.meredithcorp.io/v3/mm/image?url=https:%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F44%2F2020%2F09%2F29%2Flight-beer.jpg",
}
}
style={styles.itemImg}
/>
<View style={styles.itemDesc}>
<Text>Name: {item.name}</Text>
<Text>Brand: {item.brand}</Text>
<Text>Degree: {item.degree}</Text>
<Text>Packaging: {item.packaging}</Text>
</View>
<View style={styles.itemAddReview}>
<Button
title="Add review"
color={colors.gold}
onPress={() => {
router.push(`/review/add/${item._id}`);
}}
/>
</View>
</View>
)}
/>
</View>
);
}
export const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: "2%",
},
beerList: {
width: "100%",
paddingHorizontal: "15%",
marginTop: "2%",
},
item: {
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
marginBottom: "5%",
},
itemImg: {
height: 300,
resizeMode: "contain",
},
itemDesc: {
alignItems: "center",
paddingBottom: "2%",
},
});

View File

@@ -0,0 +1,53 @@
import { StyleSheet, Text, View } from "react-native";
import Button from "@components/Button";
import { colors } from "@components/style";
import { useAuth } from "@context/AuthContext";
import { router } from "expo-router";
export default function Index() {
const { onLogout, authState } = useAuth();
const user = authState.user;
return (
<View style={styles.container}>
<Text style={styles.h1}>Welcome {user.username}!</Text>
<Text style={styles.h2}>We hope, you're enjoying your beer.</Text>
<View style={styles.button}>
<Button
style={styles.button}
title="Add beer!"
color={colors.gold}
textColor={colors.white}
onPress={() => {
router.push("/beer");
}}
></Button>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
},
h1: {
color: "#FFF",
fontSize: 30,
textAlign: "center",
paddingTop: "20%",
},
h2: {
color: "#FFF",
fontSize: 20,
textAlign: "center",
paddingTop: "1%",
},
button: {
color: colors.charcoal,
fontSize: 30,
textAlign: "center",
paddingTop: "2%",
},
});

View File

@@ -0,0 +1,521 @@
import { StyleSheet, TextInput, View, Image } from "react-native";
import { useCallback, useState } from "react";
import Button from "@components/Button";
import Text from "@components/Text";
import { colors } from "@components/style";
import * as ImagePicker from "expo-image-picker";
import DropDownPicker from "react-native-dropdown-picker";
const DropdownTheme = require("@components/DropdownTheme");
import { Platform } from "react-native";
import { useLocalSearchParams } from "expo-router";
export default function reviewAdd() {
// States for each dropdown
const routeParams = useLocalSearchParams();
const [openFoam, setOpenFoam] = useState(false);
const [openBitterSweetness, setOpenBitterSweetness] = useState(false);
const [openTaste, setOpenTaste] = useState(false);
const [openPackaging, setOpenPackaging] = useState(false);
const [openSourness, setOpenSourness] = useState(false);
const [openAgain, setOpenAgain] = useState(false);
// foam
const [itemFoam, setFoamValue] = useState(null);
const [foam, setFoam] = useState([
{
label: "Bad",
value: "1",
icon: () => (
<Image
source={require("@assets/smileys/smiley-x-eyes.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Medium",
value: "2",
icon: () => (
<Image
source={require("@assets/smileys/smiley-meh.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Excellent",
value: "3",
icon: () => (
<Image
source={require("@assets/smileys/smiley.png")}
style={styles.iconStyle}
/>
),
},
]);
// bitter / sweetness
const [itemBitter_sweetness, setBitter_sweetnessValue] = useState(null);
const [bitter_sweetness, setBitter_sweetness] = useState([
{
label: "Bitter",
value: "1",
icon: () => (
<Image
source={require("@assets/smileys/smiley-x-eyes.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Medium",
value: "2",
icon: () => (
<Image
source={require("@assets/smileys/smiley-meh.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Sweet",
value: "3",
icon: () => (
<Image
source={require("@assets/smileys/smiley.png")}
style={styles.iconStyle}
/>
),
},
]);
// taste
const [itemTaste, setTasteValue] = useState(null);
const [taste, setTaste] = useState([
{
label: "Disgust",
value: "1",
icon: () => (
<Image
source={require("@assets/smileys/smiley-blank.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Not great, not terrible",
value: "2",
icon: () => (
<Image
source={require("@assets/smileys/smiley-nervous.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Good",
value: "3",
icon: () => (
<Image
source={require("@assets/smileys/smiley-meh.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Why not",
value: "4",
icon: () => (
<Image
source={require("@assets/smileys/smiley-wink.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Excellent!",
value: "5",
icon: () => (
<Image
source={require("@assets/smileys/smiley.png")}
style={styles.iconStyle}
/>
),
},
]);
// packaging
const [itemPackaging, setPackagingValue] = useState(null);
const [packaging, setPackaging] = useState([
{
label: "Disgust",
value: "1",
icon: () => (
<Image
source={require("@assets/smileys/smiley-blank.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Not great, not terrible",
value: "2",
icon: () => (
<Image
source={require("@assets/smileys/smiley-nervous.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Good",
value: "3",
icon: () => (
<Image
source={require("@assets/smileys/smiley-meh.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Why not",
value: "4",
icon: () => (
<Image
source={require("@assets/smileys/smiley-wink.png")}
style={styles.iconStyle}
/>
),
},
{
label: "Excellent!",
value: "5",
icon: () => (
<Image
source={require("@assets/smileys/smiley.png")}
style={styles.iconStyle}
/>
),
},
]);
// sourness
const [itemSourness, setSournessValue] = useState(null);
const [sourness, setSourness] = useState([
{
label: "True",
value: true,
icon: () => (
<Image
source={require("@assets/smileys/smiley-blank.png")}
style={styles.iconStyle}
/>
),
},
{
label: "False",
value: false,
icon: () => (
<Image
source={require("@assets/smileys/smiley-nervous.png")}
style={styles.iconStyle}
/>
),
},
]);
// would again
const [itemAgain, setAgainValue] = useState(null);
const [again, setAgain] = useState([
{
label: "Yes",
value: true,
icon: () => (
<Image
source={require("@assets/smileys/smiley.png")}
style={styles.iconStyle}
/>
),
},
{
label: "No",
value: false,
icon: () => (
<Image
source={require("@assets/smileys/smiley-x-eyes.png")}
style={styles.iconStyle}
/>
),
},
]);
//podmínky pro zavření ostatních dropdownů, pokud je jiný otevřený
const onOpenFoam = useCallback(() => {
setOpenBitterSweetness(false);
setOpenTaste(false);
setOpenPackaging(false);
setOpenSourness(false);
setOpenAgain(false);
setOpenFoam(true);
}, []);
const onOpenBitterSweetness = useCallback(() => {
setOpenFoam(false);
setOpenTaste(false);
setOpenPackaging(false);
setOpenSourness(false);
setOpenAgain(false);
setOpenBitterSweetness(true);
}, []);
const onOpenTaste = useCallback(() => {
setOpenFoam(false);
setOpenBitterSweetness(false);
setOpenPackaging(false);
setOpenSourness(false);
setOpenAgain(false);
setOpenTaste(true);
}, []);
const onOpenPackaging = useCallback(() => {
setOpenFoam(false);
setOpenBitterSweetness(false);
setOpenTaste(false);
setOpenSourness(false);
setOpenAgain(false);
setOpenPackaging(true);
}, []);
const onOpenSourness = useCallback(() => {
setOpenFoam(false);
setOpenBitterSweetness(false);
setOpenTaste(false);
setOpenPackaging(false);
setOpenAgain(false);
setOpenSourness(true);
}, []);
const onOpenAgain = useCallback(() => {
setOpenFoam(false);
setOpenBitterSweetness(false);
setOpenTaste(false);
setOpenPackaging(false);
setOpenSourness(false);
setOpenAgain(true);
}, []);
DropDownPicker.addTheme("DropdownTheme", DropdownTheme);
DropDownPicker.setTheme("DropdownTheme");
async function addBeer() {
const req = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/review/add`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
beer_id: routeParams.beer_id,
foam: itemFoam,
bitter_sweetness: itemBitter_sweetness,
taste: itemTaste,
packaging: itemPackaging,
sourness: itemSourness,
would_again: itemAgain,
}),
});
const res = await req.json();
if (res.code == 201 && res.data._id) {
// window.location.href = `/review/${res.data._id}`;
// TODO: use react router for redirect
alert("Review was added!");
} else {
alert(
"Review was not added successfully. Please check your data and try again.",
);
}
}
return (
<View style={styles.container}>
<View style={styles.form}>
<Text style={styles.text}>
How does your beer taste? Write a review!
</Text>
<Text style={styles.dropdownText} zIndex={6000} zIndexInverse={1000}>
How does the foam look like?
</Text>
<DropDownPicker
open={openFoam}
onOpen={onOpenFoam}
value={itemFoam}
items={foam}
setOpen={setOpenFoam}
setValue={setFoamValue}
setItems={setFoam}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={6000}
zIndexInverse={1000}
/>
<Text style={styles.dropdownText} zIndex={5000} zIndexInverse={2000}>
More bitter, or more sweet?
</Text>
<DropDownPicker
open={openBitterSweetness}
onOpen={onOpenBitterSweetness}
value={itemBitter_sweetness}
items={bitter_sweetness}
setOpen={setOpenBitterSweetness}
setValue={setBitter_sweetnessValue}
setItems={setBitter_sweetness}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={5000}
zIndexInverse={2000}
/>
<Text style={styles.dropdownText} zIndex={4000} zIndexInverse={3000}>
How does it taste?
</Text>
<DropDownPicker
open={openTaste}
onOpen={onOpenTaste}
value={itemTaste}
items={taste}
setOpen={setOpenTaste}
setValue={setTasteValue}
setItems={setTaste}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={4000}
zIndexInverse={3000}
/>
<Text style={styles.dropdownText} zIndex={5000} zIndexInverse={4000}>
How do you like the packaging?
</Text>
<DropDownPicker
open={openPackaging}
onOpen={onOpenPackaging}
value={itemPackaging}
items={packaging}
setOpen={setOpenPackaging}
setValue={setPackagingValue}
setItems={setPackaging}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={3000}
zIndexInverse={4000}
/>
<Text style={styles.dropdownText} zIndex={4000} zIndexInverse={5000}>
Is it sour?
</Text>
<DropDownPicker
open={openSourness}
onOpen={onOpenSourness}
value={itemSourness}
items={sourness}
setOpen={setOpenSourness}
setValue={setSournessValue}
setItems={setSourness}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={2000}
zIndexInverse={5000}
/>
<Text style={styles.dropdownText} zIndex={5000} zIndexInverse={6000}>
Would you drink it again?
</Text>
<DropDownPicker
open={openAgain}
onOpen={onOpenAgain}
value={itemAgain}
items={again}
setOpen={setOpenAgain}
setValue={setAgainValue}
setItems={setAgain}
placeholder="Please select..."
theme="DropdownTheme"
zIndex={1000}
zIndexInverse={6000}
/>
<View style={styles.buttonSend}>
<Button title="Add review" color={colors.gold} onPress={addBeer} />
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
alignItems: "center",
display: "flex",
},
form: {
gap: 5,
width: "80%",
},
buttonSend: {
display: "flex",
alignItems: "center",
marginTop: "2%",
},
input: {
height: "auto",
width: "100%",
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
color: "#fff",
},
imageContainer: {
alignItems: "center",
justifyContent: "center",
display: "flex",
flexDirection: "row",
gap: 10,
},
imageButton: {
backgroundColor: colors.dark,
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
},
imageTextButton: {
color: colors.white,
},
image: {
width: 150,
height: 150,
},
text: {
color: colors.white,
fontSize: 24,
textAlign: "center",
paddingBottom: "3%",
paddingTop: "10%",
},
iconStyle: {
width: 30,
height: 30,
},
dropdownContainer: {
width: "100%",
},
dropdownText: {
color: colors.white,
fontSize: 16,
paddingBottom: 1,
paddingTop: "1%",
display: "flex",
alignItems: "flex-start",
flexDirection: "column",
},
});

View File

@@ -0,0 +1,139 @@
import { View, StyleSheet, FlatList, Image } from "react-native";
import Text from "@components/Text";
import Button from "@components/Button";
import { colors } from "@components/style";
import { router } from "expo-router";
import { useEffect, useState } from "react";
import { useAuth } from "@context/AuthContext";
export default function Tab() {
const { authState } = useAuth();
const user = authState.user;
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const API_HOST = process.env.EXPO_PUBLIC_API_URL.replace("/api/v1", "");
async function fetchData() {
try {
const res = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/review/get`, {
method: "GET",
credentials: "include",
});
let data = await res.json();
// show only logged in user's data
data = data.data.filter((review) => review.user_id == user._id);
let beers = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/beer/get`, {
method: "GET",
credentials: "include",
});
beers = await beers.json();
beers = beers.data;
console.log(beers);
async function getBeerParam(search, beers) {
for (let i = 0; i < beers.length; i++) {
if (beers[i]._id == search) {
return beers[i];
}
}
return null;
}
data.forEach(async (el) => {
el.beer = await getBeerParam(el.beer_id, beers);
});
console.log("reviews", data);
setData(data);
} catch (err) {
console.error(err);
alert("Something went wrong");
}
}
const opt3 = ["Bad", "Medium", "Excellent!"];
const opt5 = [
"Disgust",
"Not great, not terrible",
"Good",
"Why not?",
"Excellent!",
];
const opt2 = ["Yes", "No"];
const sourness = ["Good", "Bad"];
return (
<View style={styles.container}>
<FlatList
data={data}
style={styles.reviewList}
keyExtractor={(item) => String(item._id)}
renderItem={({ item }) => (
<View style={styles.itemContainer}>
<View>
<Text>{item.beer.name}</Text>
<Text>{item.beer.brand}</Text>
<Text>{item.beer.degree}°</Text>
<Text>{item.beer.packaging}</Text>
<Image
source={
item.beer.imgs[0]
? {
uri: `${API_HOST}/public/uploads/${item.beer.imgs[0]}`,
}
: {
uri: "https://imagesvc.meredithcorp.io/v3/mm/image?url=https:%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F44%2F2020%2F09%2F29%2Flight-beer.jpg",
}
}
style={styles.itemImg}
/>
</View>
<View>
<Text>Foam {opt3[item.foam - 1]}</Text>
<Text>
Bitter / Sweetness {opt3[item.bitter_sweetness - 1]}
</Text>
<Text>Taste {opt5[item.taste - 1]}</Text>
<Text>Packaging {opt5[item.packaging - 1]}</Text>
<Text>Sourness {sourness[item.sourness - 1]}</Text>
<Text>Would again? {opt2[item.would_again - 1]}</Text>
</View>
</View>
)}
/>
</View>
);
}
export const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: "5%",
},
reviewList: {
width: "100%",
paddingHorizontal: "15%",
marginTop: "5%",
},
itemContainer: {
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
marginBottom: "5%",
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
},
itemImg: {
width: 150,
aspectRatio: 1,
resizeMode: "contain",
marginTop: "5%",
},
});

View File

@@ -0,0 +1,17 @@
import { View } from "react-native";
import Button from "@components/Button";
import { colors } from "@components/style";
import { useAuth } from "@context/AuthContext";
import Text from "@components/Text";
export default function Tab() {
const { onLogout, authState } = useAuth();
const user = authState.user;
return (
<View style={{ justifyContent: "center", alignItems: "center", flex: 1 }}>
<Text>Welcome {user.username}</Text>
<Button title="Log out" color={colors.brown} onPress={onLogout} />
</View>
);
}

View File

@@ -0,0 +1,27 @@
import { Redirect, Stack, Slot } from "expo-router";
import { useAuth } from "@context/AuthContext";
import { View, Text, StyleSheet } from "react-native";
export default function AppLayout() {
const { authState } = useAuth();
if (authState.authenticated === null) {
// micro loading co neni skoro videt ale get the fuck out se uz neloguje
return (
<View>
<Text>Loading...</Text>
</View>
);
}
if (!authState.authenticated) {
console.log("get the fuck out");
return <Redirect href="/login" />;
}
return (
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
</Stack>
);
}

12
frontend/app/_layout.js Normal file
View File

@@ -0,0 +1,12 @@
import { Slot } from "expo-router";
import { StatusBar } from "expo-status-bar";
import { AuthProvider } from "./context/AuthContext";
export default function Root() {
return (
<AuthProvider>
<StatusBar style="light" />
<Slot />
</AuthProvider>
);
}

View File

@@ -0,0 +1,139 @@
import { createContext, useContext, useEffect, useState } from "react";
import storageUtil from "./storage";
const TOKEN_KEY = "my-jwt";
export const API_URL = process.env.EXPO_PUBLIC_API_URL;
const AuthContext = createContext(null);
export function useAuth() {
const authContext = useContext(AuthContext);
if (authContext === undefined) {
throw new Error("Context is outside of provider");
}
return authContext;
}
export function AuthProvider({ children }) {
const [authState, setAuthState] = useState({
token: null,
authenticated: null,
});
useEffect(() => {
// tohle se zavola jen poprve pri startu appky
async function loadToken() {
const token = await storageUtil.getItem(TOKEN_KEY);
console.log(`stored: ${token}`);
const resUser = await fetch(`${API_URL}/auth/status`, {
credentials: "include",
});
const userData = await resUser.json();
if (token && resUser.status == 200) {
setAuthState({
token: token,
authenticated: true,
user: userData.data,
});
return;
}
setAuthState({
authenticated: false,
token: null,
user: null,
});
}
loadToken();
}, []);
async function register(username, email, password) {
try {
const res = await fetch(`${API_URL}/auth/signup`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
email,
password,
}),
});
return res;
} catch (err) {
return { error: true, msg: err.response.data };
}
}
async function login(email, password) {
try {
const resLogin = await fetch(`${API_URL}/auth/signin`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
const loginData = await resLogin.json();
const resUser = await fetch(`${API_URL}/auth/status`, {
credentials: "include",
});
if (resUser.status != 200) {
throw Error("Username or password is incorrect!");
}
const userData = await resUser.json();
setAuthState({
token: loginData.data.jwt,
authenticated: true,
user: userData.data,
});
await storageUtil.setItem(TOKEN_KEY, loginData.data.jwt);
} catch (err) {
console.error("Failed to log in", err);
return { error: true, msg: err };
}
}
async function logout() {
let res = await fetch(`${API_URL}/auth/logout`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
res = await res.json();
await storageUtil.delItem(TOKEN_KEY);
setAuthState({
token: null,
authenticated: false,
user: null,
});
}
const value = {
onSignin: register,
onLogin: login,
onLogout: logout,
authState,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

View File

@@ -0,0 +1,34 @@
import * as SecureStore from "expo-secure-store";
import { Platform } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
const storageUtil = {
setItem: async (k, v) => {
if (Platform.OS === "web") {
// web
await AsyncStorage.setItem(k, v);
} else {
// mobile
await SecureStore.setItemAsync(k, v.toString()); // v must be string,
}
},
getItem: async (k) => {
if (Platform.OS === "web") {
// web
return await AsyncStorage.getItem(k);
} else {
// mobile
return await SecureStore.getItemAsync(k);
}
},
delItem: async (k) => {
if (Platform.OS === "web") {
// web
await AsyncStorage.removeItem(k);
} else {
// mobile
await SecureStore.deleteItemAsync(k);
}
},
};
export default storageUtil;

View File

@@ -0,0 +1,6 @@
import { useAuth } from "../context/AuthContext";
export function useIsAutheticated() {
const { authState } = useAuth();
return authState.authenticated;
}

147
frontend/app/login.js Normal file
View File

@@ -0,0 +1,147 @@
import { StyleSheet, TextInput, View, Image } from "react-native";
import Text from "@components/Text";
import Link from "@components/Link";
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
import { useEffect, useState } from "react";
import { router } from "expo-router";
import Button from "../components/Button";
import { colors } from "../components/style";
import { useAuth } from "./context/AuthContext";
function LoginPage() {
const [pass, setPass] = useState("");
const [email, setEmail] = useState("");
const { onLogin, authState } = useAuth();
useEffect(() => {
if (authState.authenticated) {
router.replace("/");
}
}, [authState.authenticated]);
async function login() {
const res = await onLogin(email, pass);
if (res !== undefined && res.error === true) {
alert(res.msg);
return;
}
}
return (
<View style={styles.container}>
<AnimatedLinearGradient
colors={[colors.dark, colors.darkSecondary]}
style={styles.gradient}
/>
<View style={styles.header}>
<Image
source={require("../assets/deguapp_logo.png")}
style={styles.logo}
/>
</View>
<Text style={styles.h1}>Please Log In</Text>
<View style={styles.form}>
<TextInput
style={styles.input}
placeholder="Enter your email"
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
placeholderTextColor={"#aaaaaa"}
returnKeyType="next"
value={email}
onChangeText={(text) => setEmail(text)}
/>
<TextInput
style={styles.input}
secureTextEntry={true}
placeholder="Enter your password"
placeholderTextColor={"#aaaaaa"}
returnKeyType="done"
value={pass}
onChangeText={(text) => setPass(text)}
/>
<View style={styles.btnContainer}>
<Button
style={styles.button}
title="Log In"
color={colors.gold}
onPress={login}
/>
</View>
<View>
<Link href="/signup" style={styles.signup}>
Don't have an account?
</Link>
</View>
</View>
</View>
);
}
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
justifyContent: "center",
alignItems: "center",
},
form: {
flex: 1,
alignItems: "center",
width: "100%",
gap: 15,
},
h1: {
color: "#FFF",
fontSize: 30,
textAlign: "center",
paddingTop: "3%",
paddingBottom: "3%",
},
logo: {
width: "80%",
resizeMode: "contain",
paddingBottom: "0%",
},
header: {
width: "100%",
alignItems: "center",
paddingTop: "20%",
},
input: {
height: "auto",
width: "60%",
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
color: "#fff",
},
btnContainer: {
flexDirection: "row",
gap: 5,
},
button: {
width: "40%",
},
gradient: {
position: "absolute",
left: 0,
right: 0,
top: 0,
height: "100%",
},
signup: {
textDecorationLine: "underline",
fontSize: 14,
marginTop: 10,
fontStyle: "italic",
},
});
export default LoginPage;

172
frontend/app/signup.js Normal file
View File

@@ -0,0 +1,172 @@
import { StyleSheet, TextInput, View, Text, Image } from "react-native";
import { useState } from "react";
import Button from "../components/Button";
import { colors } from "../components/style";
import { Link, router } from "expo-router";
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
import { useAuth } from "./context/AuthContext";
function SignupPage() {
const [pass1, setPass1] = useState("");
const [pass2, setPass2] = useState("");
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const { onSignin } = useAuth();
async function signin() {
if (pass1 != pass2) {
alert("Passwords are not same!");
return;
}
const res = await onSignin(username, email, pass1);
const data = await res.json();
if (res.status == 400) {
if (data.message == "validation error") {
alert(data.data.message);
} else {
alert("Something went wrong");
}
return;
}
if (res.status == 201) {
alert("You have been successfully registered. Please Log In");
router.replace("/login");
return;
}
}
return (
<View style={styles.container}>
<AnimatedLinearGradient
colors={[colors.dark, colors.darkSecondary]}
style={styles.gradient}
/>
<View style={styles.header}>
<Image
source={require("../assets/deguapp_logo.png")}
style={styles.logo}
/>
<Text style={styles.h1}>Please Sign Up</Text>
</View>
<View style={styles.form}>
<TextInput
style={styles.input}
placeholder="Enter your username"
placeholderTextColor={"#aaaaaa"}
returnKeyType="done"
value={username}
onChangeText={(username) => setUsername(username)}
/>
<TextInput
style={styles.input}
placeholder="Enter your email"
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
placeholderTextColor={"#aaaaaa"}
returnKeyType="next"
value={email}
onChangeText={(email) => setEmail(email)}
/>
<TextInput
style={styles.input}
secureTextEntry={true}
placeholder="Enter your password"
placeholderTextColor={"#aaaaaa"}
returnKeyType="done"
value={pass1}
onChangeText={(pass1) => setPass1(pass1)}
/>
<TextInput
style={styles.input}
secureTextEntry={true}
placeholder="Enter your password"
placeholderTextColor={"#aaaaaa"}
returnKeyType="done"
value={pass2}
onChangeText={(pass2) => setPass2(pass2)}
/>
<Button
style={styles.button}
title="Sign Up"
color={colors.gold}
onPress={signin}
/>
<Link href="/login" style={styles.login}>
Already have an account? Log In!
</Link>
</View>
</View>
);
}
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
const styles = StyleSheet.create({
container: {
width: "100%",
height: "100%",
backgroundColor: colors.dark,
justifyContent: "center",
alignItems: "center",
maxHeight: "100%",
},
form: {
flex: 1,
alignItems: "center",
width: "100%",
gap: 15,
},
h1: {
color: "#FFF",
fontSize: 30,
textAlign: "center",
paddingTop: "3%",
paddingBottom: "3%",
},
logo: {
width: "80%",
resizeMode: "contain",
marginTop: "15%",
},
header: {
width: "100%",
alignItems: "center",
},
input: {
height: "auto",
width: "60%",
borderColor: "gray",
borderWidth: 1,
borderRadius: 10,
padding: 13,
color: "#fff",
},
btnContainer: {
flexDirection: "row",
gap: 5,
},
login: {
color: "#FFF",
fontStyle: "italic",
textDecorationLine: "underline",
fontSize: 14,
marginTop: 10,
},
gradient: {
position: "absolute",
left: 0,
right: 0,
top: 0,
height: "100%",
},
});
export default SignupPage;

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 338 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,344 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="500"
height="200"
viewBox="0 0 132.29166 52.916666"
version="1.1"
id="svg1"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"><defs
id="defs1"><rect
x="198.48267"
y="0"
width="321.53085"
height="87.551346"
id="rect37" /></defs><metadata
id="metadata1"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><g
id="g1"
transform="matrix(0.06512959,0,0,0.06512959,6.8792483,9.7851583)"><rect
x="77.363998"
y="101.977"
transform="matrix(0.9063,-0.4226,0.4226,0.9063,-77.0283,82.304)"
style="fill:#ffffff"
width="139.506"
height="225.814"
id="rect1" /><g
id="g3">
<rect
x="46.675999"
y="134.336"
transform="matrix(-0.9063,0.4226,-0.4226,-0.9063,180.4817,283.7283)"
style="fill:#e6e6e6"
width="24.231001"
height="55.067001"
id="rect2" />
<rect
x="122.742"
y="316.82599"
transform="matrix(0.4226,0.9063,-0.9063,0.4226,377.0499,66.0417)"
style="fill:#e6e6e6"
width="27.902"
height="24.231001"
id="rect3" />
</g><rect
x="83.105003"
y="155.774"
transform="matrix(0.9063,-0.4226,0.4226,0.9063,-81.6929,85.8838)"
style="fill:#ffda44"
width="139.506"
height="142.84"
id="rect4" /><rect
x="29.193001"
y="239.44501"
transform="matrix(0.4226,0.9063,-0.9063,0.4226,286.0854,54.063)"
style="fill:#edc10c"
width="142.84"
height="24.231001"
id="rect5" /><g
id="g17">
<rect
x="189.983"
y="197.57201"
transform="matrix(0.9063,-0.4226,0.4226,0.9063,-67.5076,101.6413)"
style="fill:#ffffff"
width="11.014"
height="11.013"
id="rect6" />
<rect
x="104.89"
y="246.17"
transform="matrix(0.9063,-0.4226,0.4226,0.9063,-96.0174,70.233)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect7" />
<rect
x="145.595"
y="231.15401"
transform="rotate(-70.001229,151.10183,236.66096)"
style="fill:#ffffff"
width="11.015"
height="11.014"
id="rect8" />
<rect
x="126.804"
y="277.35999"
transform="rotate(-70.001229,132.31158,282.86764)"
style="fill:#ffffff"
width="11.015"
height="11.015"
id="rect9" />
<rect
x="211.463"
y="249.052"
transform="rotate(-70.001229,216.97024,254.55892)"
style="fill:#ffffff"
width="11.014"
height="11.015"
id="rect10" />
<rect
x="186.33"
y="234.92"
transform="matrix(-0.4226,-0.9063,0.9063,-0.4226,55.0062,515.8975)"
style="fill:#ffffff"
width="11.013"
height="11.014"
id="rect11" />
<rect
x="157.35699"
y="273.54401"
transform="matrix(-0.4226,-0.9063,0.9063,-0.4226,-21.2159,544.5854)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect12" />
<rect
x="173.785"
y="164.619"
transform="matrix(-0.9063,0.4226,-0.4226,-0.9063,413.683,248.5438)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect13" />
<rect
x="145.674"
y="194.836"
transform="rotate(109.99877,151.18131,200.34275)"
style="fill:#ffffff"
width="11.015"
height="11.014"
id="rect14" />
<rect
x="91.181"
y="206.382"
transform="matrix(0.4226,0.9063,-0.9063,0.4226,247.8647,34.7143)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect15" />
<rect
x="112.27"
y="180.34599"
transform="matrix(0.4226,0.9063,-0.9063,0.4226,236.4438,0.5679)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect16" />
<rect
x="295.129"
y="184.19"
transform="matrix(-0.9063,-0.4226,0.4226,-0.9063,570.0236,720.5612)"
style="fill:#ffffff"
width="139.506"
height="225.814"
id="rect17" />
</g><g
id="g19">
<rect
x="361.32999"
y="399.03101"
transform="matrix(-0.4226,0.9063,-0.9063,-0.4226,906.504,244.7769)"
style="fill:#e6e6e6"
width="27.902"
height="24.231001"
id="rect18" />
<rect
x="425.67801"
y="231.979"
transform="matrix(0.4226,-0.9063,0.9063,0.4226,40.456,551.6899)"
style="fill:#e6e6e6"
width="55.067001"
height="24.231001"
id="rect19" />
</g><rect
x="289.383"
y="237.992"
transform="matrix(-0.9063,-0.4226,0.4226,-0.9063,553.8666,741.6097)"
style="fill:#ffda44"
width="139.506"
height="142.84"
id="rect20" /><rect
x="339.94101"
y="321.66199"
transform="matrix(-0.4226,0.9063,-0.9063,-0.4226,887.7116,102.0116)"
style="fill:#edc10c"
width="142.84"
height="24.231001"
id="rect21" /><g
id="g32">
<rect
x="311.00601"
y="279.789"
transform="matrix(-0.9063,-0.4226,0.4226,-0.9063,482.8051,677.6238)"
style="fill:#ffffff"
width="11.014"
height="11.013"
id="rect22" />
<rect
x="396.10001"
y="328.38501"
transform="matrix(-0.9063,-0.4226,0.4226,-0.9063,624.4829,806.2245)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect23" />
<rect
x="355.379"
y="313.37201"
transform="rotate(-109.99877,360.88681,318.87858)"
style="fill:#ffffff"
width="11.015"
height="11.014"
id="rect24" />
<rect
x="374.16699"
y="359.57101"
transform="rotate(-109.99877,379.67388,365.07806)"
style="fill:#ffffff"
width="11.015"
height="11.015"
id="rect25" />
<rect
x="289.509"
y="331.263"
transform="rotate(-109.99877,295.01597,336.77049)"
style="fill:#ffffff"
width="11.014"
height="11.015"
id="rect26" />
<rect
x="314.65701"
y="317.147"
transform="matrix(0.4226,-0.9063,0.9063,0.4226,-107.5657,476.4675)"
style="fill:#ffffff"
width="11.013"
height="11.014"
id="rect27" />
<rect
x="343.63"
y="355.78"
transform="matrix(0.4226,-0.9063,0.9063,0.4226,-125.8494,525.0318)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect28" />
<rect
x="327.181"
y="246.84599"
transform="matrix(0.9063,0.4226,-0.4226,0.9063,137.8144,-116.954)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect29" />
<rect
x="355.31601"
y="277.04401"
transform="rotate(70.001229,360.82315,282.55078)"
style="fill:#ffffff"
width="11.014"
height="11.014"
id="rect30" />
<rect
x="409.784"
y="288.60199"
transform="matrix(-0.4226,0.9063,-0.9063,-0.4226,857.3503,42.0171)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect31" />
<rect
x="388.70401"
y="262.55801"
transform="matrix(-0.4226,0.9063,-0.9063,-0.4226,803.757,24.0718)"
style="fill:#ffffff"
width="11.013"
height="11.013"
id="rect32" />
</g><path
d="M 166.383,72.728 25.824,138.271 127.843,357.05 268.403,291.507 Z M 236.075,259.043 123.754,311.42 69.969,196.078 182.29,143.702 Z M 158.848,93.431 175.706,129.582 63.385,181.958 46.527,145.807 Z m -23.47,242.917 -5.04,-10.809 112.321,-52.376 5.04,10.809 z"
id="path32" /><polygon
points="20.704,183.96 33.448,178.017 26.864,163.897 0,176.424 65.695,317.309 92.559,304.783 85.975,290.663 73.231,296.606 "
id="polygon32" /><path
d="M 345.609,154.948 243.59,373.728 384.15,439.272 486.17,220.493 Z m 7.536,20.703 112.321,52.376 -16.858,36.151 -112.321,-52.376 z m 88.878,102.647 -53.785,115.342 -112.32,-52.376 53.785,-115.342 z m -177.729,87.895 5.039,-10.808 112.32,52.376 -5.04,10.809 z"
id="path33" /><polygon
points="478.719,260.276 491.296,266.141 438.402,379.575 425.824,373.71 419.24,387.83 445.938,400.279 512,258.606 485.304,246.156 "
id="polygon33" /><rect
x="269.70901"
y="88.780998"
width="15.579"
height="35.313"
id="rect33" /><rect
x="205.088"
y="121.389"
transform="matrix(-0.7071,-0.7071,0.7071,-0.7071,289.1103,378.1096)"
width="35.551998"
height="15.579"
id="rect34" /><rect
x="324.328"
y="111.418"
transform="matrix(-0.7071,-0.7071,0.7071,-0.7071,475.6093,455.3818)"
width="15.579"
height="35.541"
id="rect35" /></g><text
xml:space="preserve"
transform="matrix(0.26458333,0,0,0.26458333,-7.2032501,17.070955)"
id="text36"
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:64px;font-family:'Open Sans';-inkscape-font-specification:'Open Sans, Bold';font-variant-ligatures:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-east-asian:normal;letter-spacing:1.48px;text-orientation:sideways;white-space:pre;shape-inside:url(#rect37);opacity:1;fill:#ffd700;fill-opacity:1;stroke:none;stroke-width:1.00157;stroke-dasharray:none"><tspan
x="198.48242"
y="58.231624"
id="tspan1">DeguApp</tspan></text></svg>

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

BIN
frontend/assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

BIN
frontend/assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

BIN
frontend/assets/splash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

19
frontend/babel.config.js Normal file
View File

@@ -0,0 +1,19 @@
module.exports = function (api) {
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
"module-resolver",
{
root: ["."],
alias: {
"@components": "./components",
"@context": "./app/context",
"@assets": "./assets",
},
},
],
],
};
};

15
frontend/biome.json Normal file
View File

@@ -0,0 +1,15 @@
{
"$schema": "https://biomejs.dev/schemas/1.7.3/schema.json",
"files": {
"ignore": [".expo/", ".vscode/", "node_modules/", "dist/"]
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": false,
"rules": {
"recommended": true
}
}
}

View File

@@ -0,0 +1,51 @@
import React from "react";
import { Text, StyleSheet, Pressable } from "react-native";
export default function Button(props) {
const {
onPress,
title = "Button",
color = "black",
textColor = "white",
buttonStyle,
textStyle,
} = props;
return (
<Pressable
style={({ pressed }) => [
{
backgroundColor: pressed
? "rgb(210, 230, 255 )"
: color
? color
: "black",
},
styles.button,
buttonStyle,
]}
onPress={onPress}
>
<Text style={[styles.text, { color: textColor }, textStyle]}>
{title}
</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
button: {
alignItems: "center",
justifyContent: "center",
paddingVertical: 12,
paddingHorizontal: 32,
borderRadius: 4,
elevation: 3,
},
text: {
fontSize: 16,
lineHeight: 21,
fontWeight: "bold",
letterSpacing: 0.25,
//color: textColor,
},
});

View File

@@ -0,0 +1,170 @@
import { StyleSheet } from "react-native";
import { colors } from "@components/style";
export const ICONS = {
ARROW_DOWN: require("@assets/DropdownIcons/arrow-down.png"),
ARROW_UP: require("@assets/DropdownIcons/arrow-up.png"),
TICK: require("@assets/DropdownIcons/tick.png"),
CLOSE: require("../assets/DropdownIcons/close.png"),
};
export default StyleSheet.create({
container: {
width: "100%",
},
style: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
width: "100%",
minHeight: 50,
borderRadius: 8,
borderWidth: 1,
borderColor: "gray",
paddingHorizontal: 10,
paddingVertical: 3,
backgroundColor: colors.dark,
},
label: {
flex: 1,
color: colors.placeholder,
},
labelContainer: {
flex: 1,
flexDirection: "row",
},
arrowIcon: {
width: 20,
height: 20,
},
tickIcon: {
width: 20,
height: 20,
},
closeIcon: {
width: 30,
height: 30,
},
badgeStyle: {
flexDirection: "row",
alignItems: "center",
borderRadius: 15,
backgroundColor: colors.white,
paddingHorizontal: 10,
paddingVertical: 5,
},
badgeDotStyle: {
width: 10,
height: 10,
borderRadius: 10 / 2,
marginRight: 8,
backgroundColor: colors.white,
},
badgeSeparator: {
width: 5,
},
listBody: {
height: "100%",
},
listBodyContainer: {
flexGrow: 1,
alignItems: "center",
},
dropDownContainer: {
position: "absolute",
backgroundColor: colors.darkSecondary,
borderRadius: 10,
borderColor: colors.black,
borderWidth: 1,
width: "100%",
overflow: "hidden",
zIndex: 1000,
},
modalContentContainer: {
flexGrow: 1,
backgroundColor: colors.white,
},
listItemContainer: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
paddingHorizontal: 10,
height: 40,
},
listItemLabel: {
flex: 1,
color: colors.placeholder,
},
iconContainer: {
marginRight: 10,
},
arrowIconContainer: {
marginLeft: 10,
},
tickIconContainer: {
marginLeft: 10,
},
closeIconContainer: {
marginLeft: 10,
},
listParentLabel: {},
listChildLabel: {},
listParentContainer: {},
listChildContainer: {
paddingLeft: 40,
},
searchContainer: {
flexDirection: "row",
alignItems: "center",
padding: 10,
borderBottomColor: colors.darkSecondary,
borderBottomWidth: 1,
},
searchTextInput: {
flexGrow: 1,
flexShrink: 1,
margin: 0,
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 8,
borderColor: colors.darkSecondary,
borderWidth: 1,
color: colors.white,
},
itemSeparator: {
height: 1,
backgroundColor: colors.darkSecondary,
},
flatListContentContainer: {
flexGrow: 1,
},
customItemContainer: {},
customItemLabel: {
fontStyle: "italic",
},
listMessageContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center",
padding: 10,
},
listMessageText: {
color: colors.gold,
},
selectedItemContainer: {},
selectedItemLabel: {},
modalTitle: {
fontSize: 18,
color: colors.gold,
},
extendableBadgeContainer: {
flexDirection: "row",
flexWrap: "wrap",
flex: 1,
},
extendableBadgeItemContainer: {
marginVertical: 3,
marginEnd: 7,
},
});

View File

@@ -0,0 +1,15 @@
import { Link as EXLink } from "expo-router";
const Link = (props) => {
const defaultStyles = {
color: "white",
};
return (
<EXLink style={[defaultStyles, props.style]} href={props.href}>
{props.children}
</EXLink>
);
};
export default Link;

View File

@@ -0,0 +1,13 @@
import React from "react";
import { Text as RNText } from "react-native";
const Text = (props) => {
// Apply your default text color and any other styles here
const defaultStyles = {
color: "white", // Set the default text color to white
};
return <RNText style={[defaultStyles, props.style]}>{props.children}</RNText>;
};
export default Text;

View File

View File

@@ -0,0 +1,12 @@
export const colors = {
gold: "#FFD700ff",
gold: "#ffa500",
brown: "#8B4513ff",
green: "#228B22ff",
charcoal: "#2C3E50ff",
black: "#020405ff",
dark: "#010409",
darkSecondary: "#0D1117",
white: "#FFFFFF",
placeholder: "#aaaaaa",
};

15281
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
frontend/package.json Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "deguapp",
"version": "1.0.0",
"main": "expo-router/entry",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"build:web": "npx expo export",
"format": "npx @biomejs/biome format --write ."
},
"dependencies": {
"@expo/metro-runtime": "~3.2.1",
"@react-native-async-storage/async-storage": "^1.23.1",
"@types/react": "~18.2.45",
"axios": "^1.6.8",
"expo": "^51.0.2",
"expo-constants": "~16.0.1",
"expo-image-picker": "~15.0.4",
"expo-linear-gradient": "~13.0.2",
"expo-linking": "~6.3.1",
"expo-router": "~3.5.11",
"expo-secure-store": "~13.0.1",
"expo-status-bar": "~1.12.1",
"expo-system-ui": "~3.0.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-native": "0.74.1",
"react-native-dropdown-picker": "^5.4.6",
"react-native-range-slider-expo": "^1.4.3",
"react-native-safe-area-context": "4.10.1",
"react-native-screens": "3.31.1",
"react-native-web": "~0.19.6",
"@shopify/flash-list": "1.6.4"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@biomejs/biome": "1.7.3",
"babel-plugin-module-resolver": "^5.0.2"
},
"private": true
}