Compare commits
132 commits
Author | SHA1 | Date | |
---|---|---|---|
ff03e8331d | |||
41748200cc | |||
67944d6017 | |||
9537d8b6bc | |||
8d68d54a31 | |||
1e33bedfff | |||
6020fd647f | |||
a9165e9867 | |||
5918e351c2 | |||
c4fb0b3391 | |||
00afb3f4bf | |||
374b2a79b0 | |||
7175036135 | |||
5ae22d6d36 | |||
d04dfa1bd5 | |||
a5039c27b1 | |||
a5600fee0a | |||
ea188430d0 | |||
cbfe0b2131 | |||
58bcd48ea7 | |||
9843046db7 | |||
a737f40398 | |||
84ad21011a | |||
3bb586bf14 | |||
b58cbfc388 | |||
92bb5a4827 | |||
287576f3c2 | |||
14861078c0 | |||
6ab4f20137 | |||
4f2c1f067a | |||
134814c515 | |||
b9e212c2c0 | |||
3434bf099c | |||
5aef4630a6 | |||
d13b784826 | |||
3d5bf4af1f | |||
d1ef0bfb1c | |||
fbc936e2bb | |||
b761256862 | |||
02b60757bb | |||
0ecc077b9d | |||
2d3c987be0 | |||
4b5827b315 | |||
6c96c6f2c2 | |||
0b26bf9240 | |||
a66c934d79 | |||
d5a449c719 | |||
d1d3814839 | |||
d062fa056e | |||
21cc7ff0ce | |||
d391c60f91 | |||
|
2dc415553d | ||
|
960723c6e4 | ||
|
cb8e9ecf7a | ||
|
426a522683 | ||
|
b6dc6693e2 | ||
|
488193bba8 | ||
|
96f563af56 | ||
c60eff2cbb | |||
e92ffd376a | |||
22061e3f4a | |||
955ee0f126 | |||
197fee1033 | |||
f1dc6bbca3 | |||
c4fea5a06f | |||
b1267dd4cf | |||
d8b89bc8d2 | |||
689dbc39e2 | |||
ef1deaf19b | |||
59aa48817a | |||
64e7cb9d52 | |||
5a9b988c63 | |||
961c60a183 | |||
fed06cd155 | |||
e8d3719adc | |||
978de59d36 | |||
7e49dbeb31 | |||
a2579dbd6d | |||
7a8c9c1035 | |||
1e14057dfa | |||
|
040af1ba36 | ||
|
3c4fc35daa | ||
|
e537b1b32a | ||
|
9877d9288b | ||
dfe81b7a2f | |||
76237b331a | |||
5e8337da29 | |||
9a01fb39ec | |||
a460421497 | |||
2b66ea916b | |||
94a373f779 | |||
e4e77c4df7 | |||
bd9c0e5857 | |||
|
f3b1976a0b | ||
|
f90c68ca06 | ||
|
2fc1aebaac | ||
|
be58b72e04 | ||
|
d80d0273bc | ||
|
3c14ebd2bf | ||
|
9a148b8984 | ||
|
16845b3129 | ||
e7d0093ede | |||
|
d480ebc63c | ||
|
45dfa9a681 | ||
b5ee8fffd1 | |||
d3fb723611 | |||
e934ebf4e4 | |||
8a128a1104 | |||
0fe4072a6e | |||
6b9c34d5d1 | |||
4ae19c09c2 | |||
aa96cbbf3a | |||
1060e35019 | |||
4cc3a6c070 | |||
0a99788a2f | |||
589bc18069 | |||
c3a4e94bd4 | |||
f9bf4eed65 | |||
619c243b8f | |||
fcf9bc6cd3 | |||
d02f472e48 | |||
2ae81f7f82 | |||
f9dfbe719d | |||
e86427e152 | |||
a1f4f3a693 | |||
9d42cee5e3 | |||
e10ed36838 | |||
d36b166416 | |||
2f29f5d34a | |||
|
ff7b80a273 | ||
4deccdbd0b | |||
47d7e79d5d |
47
.forgejo/workflows/docker-image.yml
Normal file
|
@ -0,0 +1,47 @@
|
|||
name: Publish Docker image
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
push_to_registry:
|
||||
name: Push Docker image to Forgejo Packages
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v4
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
git.wbrawner.com/wbrawner/twigs
|
||||
tags: |
|
||||
type=schedule
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
type=sha
|
||||
- name: Set up Docker context
|
||||
run: docker context create builders
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
endpoint: builders
|
||||
- name: Login to Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.wbrawner.com
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.FORGEJO_TOKEN }}
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
26
.forgejo/workflows/pull-request.yml
Normal file
|
@ -0,0 +1,26 @@
|
|||
name: Pull request workflow
|
||||
on: pull_request
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Build and Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: https://git.wbrawner.com/actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
- name: Validate Gradle Wrapper
|
||||
uses: https://git.wbrawner.com/gradle/actions/wrapper-validation@v3
|
||||
- name: Build with Gradle
|
||||
uses: https://git.wbrawner.com/gradle/actions/setup-gradle@v3
|
||||
with:
|
||||
arguments: --stacktrace check
|
||||
- name: Publish JUnit Results
|
||||
uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: Unit Test Results
|
||||
path: "*/build/test-results/test/*.xml"
|
||||
if-no-files-found: error
|
17
.github/workflows/docker-image.yml
vendored
|
@ -1,9 +1,8 @@
|
|||
name: Publish Docker image
|
||||
on:
|
||||
push:
|
||||
branches: main
|
||||
tags:
|
||||
- '*'
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
push_to_registry:
|
||||
|
@ -11,10 +10,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/wbrawner/twigs
|
||||
|
@ -27,17 +26,17 @@ jobs:
|
|||
type=semver,pattern={{major}}
|
||||
type=sha
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v2
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v3
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
|
31
.github/workflows/pull-request.yml
vendored
Normal file
|
@ -0,0 +1,31 @@
|
|||
name: Pull request workflow
|
||||
on: pull_request
|
||||
|
||||
permissions:
|
||||
statuses: write
|
||||
checks: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Build and Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
- name: Validate Gradle Wrapper
|
||||
uses: gradle/wrapper-validation-action@v3
|
||||
- name: Build with Gradle
|
||||
uses: gradle/gradle-build-action@v3
|
||||
with:
|
||||
arguments: --stacktrace build
|
||||
- name: Publish JUnit Results
|
||||
uses: dorny/test-reporter@v1
|
||||
if: always()
|
||||
with:
|
||||
name: Unit Tests
|
||||
path: "*/build/test-results/test/*.xml"
|
||||
reporter: java-junit
|
||||
fail-on-error: true
|
661
COPYING
Normal file
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
|
@ -1,4 +1,4 @@
|
|||
FROM openjdk:17-jdk as builder
|
||||
FROM ibm-semeru-runtimes:open-21-jdk as builder
|
||||
MAINTAINER William Brawner <me@wbrawner.com>
|
||||
|
||||
RUN groupadd --system --gid 1000 gradle \
|
||||
|
@ -8,10 +8,10 @@ COPY --chown=gradle:gradle . /home/gradle/src
|
|||
WORKDIR /home/gradle/src
|
||||
RUN /home/gradle/src/gradlew --console=plain --no-daemon shadowJar
|
||||
|
||||
FROM openjdk:17-slim
|
||||
FROM ibm-semeru-runtimes:open-21-jre
|
||||
EXPOSE 8080
|
||||
RUN groupadd --system --gid 1000 twigs \
|
||||
&& useradd --system --gid twigs --uid 1000 --create-home twigs
|
||||
COPY --from=builder --chown=twigs:twigs /home/gradle/src/app/build/libs/twigs.jar twigs.jar
|
||||
USER twigs
|
||||
CMD /usr/local/openjdk-17/bin/java $JVM_ARGS -jar /twigs.jar
|
||||
CMD /opt/java/openjdk/bin/java $JVM_ARGS -jar /twigs.jar
|
||||
|
|
661
LICENSE
|
@ -1,8 +1,661 @@
|
|||
Copyright 2019 William Patrick Brawner
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
Preamble
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
|
18
README.md
|
@ -1,12 +1,11 @@
|
|||
# Twigs Server
|
||||
# Twigs
|
||||
|
||||
This is the backend application that powers the [Android](../../../twigs-android), [iOS](../../../twigs-ios),
|
||||
and [web](../../../twigs-web) applications for Twigs, a personal finance/budgeting app. None of these apps are complete,
|
||||
so expect bugs, and they are all in various stages of development, so expect some feature disparity between platforms.
|
||||
Twigs is a personal finance application tailored to individuals and small groups that want robust budgeting features
|
||||
without needing to pay a monthly subscription.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- JDK 14 or newer
|
||||
- JDK 17 or newer
|
||||
- PostgreSQL 13 or newer
|
||||
- (optional) Docker
|
||||
|
||||
|
@ -44,3 +43,12 @@ Building the app is also handled with gradle:
|
|||
|
||||
./gradlew shadowJar
|
||||
|
||||
## License
|
||||
|
||||
Copyright (C) 2019-2024 William Brawner
|
||||
|
||||
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/>.
|
||||
|
|
|
@ -1,18 +1,16 @@
|
|||
plugins {
|
||||
kotlin("jvm")
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
`java-library`
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(project(":core"))
|
||||
implementation(project(":service"))
|
||||
implementation(project(":storage"))
|
||||
api(libs.ktor.server.core)
|
||||
api(libs.ktor.serialization)
|
||||
api(libs.kotlinx.coroutines.core)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
testImplementation(project(":testhelpers"))
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
|
|
|
@ -1,62 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.util.pipeline.*
|
||||
|
||||
suspend inline fun PipelineContext<Unit, ApplicationCall>.requireBudgetWithPermission(
|
||||
permissionRepository: PermissionRepository,
|
||||
userId: String,
|
||||
budgetId: String?,
|
||||
permission: Permission,
|
||||
otherwise: () -> Unit
|
||||
) {
|
||||
if (budgetId.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "budgetId is required")
|
||||
return
|
||||
}
|
||||
permissionRepository.findAll(
|
||||
userId = userId,
|
||||
budgetIds = listOf(budgetId)
|
||||
).firstOrNull {
|
||||
it.permission.isAtLeast(permission)
|
||||
} ?: run {
|
||||
errorResponse(HttpStatusCode.Forbidden, "Insufficient permissions on budget $budgetId")
|
||||
otherwise()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun PipelineContext<Unit, ApplicationCall>.budgetWithPermission(
|
||||
budgetRepository: BudgetRepository,
|
||||
permissionRepository: PermissionRepository,
|
||||
budgetId: String,
|
||||
permission: Permission,
|
||||
block: suspend (Budget) -> Unit
|
||||
) {
|
||||
val session = call.principal<Session>()!!
|
||||
val userPermission = permissionRepository.findAll(
|
||||
userId = session.userId,
|
||||
budgetIds = listOf(budgetId)
|
||||
).firstOrNull()
|
||||
if (userPermission?.permission?.isAtLeast(permission) != true) {
|
||||
errorResponse(HttpStatusCode.Forbidden)
|
||||
return
|
||||
}
|
||||
block(budgetRepository.findAll(ids = listOf(budgetId)).first())
|
||||
}
|
||||
|
||||
suspend inline fun PipelineContext<Unit, ApplicationCall>.errorResponse(
|
||||
httpStatusCode: HttpStatusCode = HttpStatusCode.NotFound,
|
||||
message: String? = null
|
||||
) {
|
||||
message?.let {
|
||||
call.respond(httpStatusCode, ErrorResponse(message))
|
||||
} ?: call.respond(httpStatusCode)
|
||||
}
|
|
@ -1,122 +1,57 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.respondCatching
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.budgetRoutes(
|
||||
budgetRepository: BudgetRepository,
|
||||
permissionRepository: PermissionRepository
|
||||
) {
|
||||
fun Application.budgetRoutes(budgetService: BudgetService) {
|
||||
routing {
|
||||
route("/api/budgets") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
val session = call.principal<Session>()!!
|
||||
val budgetIds = permissionRepository.findAll(userId = session.userId).map { it.budgetId }
|
||||
if (budgetIds.isEmpty()) {
|
||||
call.respond(emptyList<BudgetResponse>())
|
||||
return@get
|
||||
call.respondCatching {
|
||||
budgetService.budgetsForUser(userId = requireSession().userId)
|
||||
}
|
||||
val budgets = budgetRepository.findAll(ids = budgetIds).map {
|
||||
BudgetResponse(it, permissionRepository.findAll(budgetIds = listOf(it.id)))
|
||||
}
|
||||
call.respond(budgets)
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
budgetWithPermission(
|
||||
budgetRepository,
|
||||
permissionRepository,
|
||||
call.parameters["id"]!!,
|
||||
Permission.READ
|
||||
) { budget ->
|
||||
val users = permissionRepository.findAll(budgetIds = listOf(budget.id))
|
||||
call.respond(BudgetResponse(budget, users))
|
||||
call.respondCatching {
|
||||
budgetService.budget(
|
||||
budgetId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<BudgetRequest>()
|
||||
if (request.name.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Name cannot be empty or null")
|
||||
return@post
|
||||
call.respondCatching {
|
||||
budgetService.save(request = call.receive(), userId = requireSession().userId)
|
||||
}
|
||||
val budget = budgetRepository.save(
|
||||
Budget(
|
||||
name = request.name,
|
||||
description = request.description
|
||||
)
|
||||
)
|
||||
val users = request.users?.map {
|
||||
permissionRepository.save(
|
||||
UserPermission(
|
||||
budgetId = budget.id,
|
||||
userId = it.user,
|
||||
permission = it.permission
|
||||
)
|
||||
)
|
||||
}?.toMutableSet() ?: mutableSetOf()
|
||||
if (users.none { it.userId == session.userId }) {
|
||||
users.add(
|
||||
permissionRepository.save(
|
||||
UserPermission(
|
||||
budgetId = budget.id,
|
||||
userId = session.userId,
|
||||
permission = Permission.OWNER
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
call.respond(BudgetResponse(budget, users))
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
budgetWithPermission(
|
||||
budgetRepository,
|
||||
permissionRepository,
|
||||
call.parameters["id"]!!,
|
||||
Permission.MANAGE
|
||||
) { budget ->
|
||||
val request = call.receive<BudgetRequest>()
|
||||
val name = request.name ?: budget.name
|
||||
val description = request.description ?: budget.description
|
||||
val users = request.users?.map {
|
||||
permissionRepository.save(UserPermission(budget.id, it.user, it.permission))
|
||||
} ?: permissionRepository.findAll(budgetIds = listOf(budget.id))
|
||||
permissionRepository.findAll(budgetIds = listOf(budget.id)).forEach {
|
||||
if (it.permission != Permission.OWNER && users.none { userPermission -> userPermission.userId == it.userId }) {
|
||||
permissionRepository.delete(it)
|
||||
}
|
||||
}
|
||||
call.respond(
|
||||
BudgetResponse(
|
||||
budgetRepository.save(budget.copy(name = name, description = description)),
|
||||
users
|
||||
)
|
||||
call.respondCatching {
|
||||
budgetService.save(
|
||||
request = call.receive(),
|
||||
userId = requireSession().userId,
|
||||
budgetId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
budgetWithPermission(
|
||||
budgetRepository,
|
||||
permissionRepository,
|
||||
budgetId = call.parameters["id"]!!,
|
||||
Permission.OWNER
|
||||
) { budget ->
|
||||
budgetRepository.delete(budget)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
call.respondCatching {
|
||||
budgetService.delete(
|
||||
budgetId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,139 +1,64 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.CategoryRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.service.category.CategoryRequest
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.respondCatching
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.categoryRoutes(
|
||||
categoryRepository: CategoryRepository,
|
||||
permissionRepository: PermissionRepository
|
||||
) {
|
||||
fun Application.categoryRoutes(categoryService: CategoryService) {
|
||||
routing {
|
||||
route("/api/categories") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
val session = call.principal<Session>()!!
|
||||
val budgetIds = permissionRepository.findAll(
|
||||
budgetIds = call.request.queryParameters.getAll("budgetIds"),
|
||||
userId = session.userId
|
||||
).map { it.budgetId }
|
||||
if (budgetIds.isEmpty()) {
|
||||
call.respond(emptyList<CategoryResponse>())
|
||||
return@get
|
||||
call.respondCatching {
|
||||
categoryService.categories(
|
||||
budgetIds = call.request.queryParameters.getAll("budgetIds").orEmpty(),
|
||||
userId = requireSession().userId,
|
||||
expense = call.request.queryParameters["expense"]?.toBoolean(),
|
||||
archived = call.request.queryParameters["archived"]?.toBoolean()
|
||||
)
|
||||
}
|
||||
call.respond(categoryRepository.findAll(
|
||||
budgetIds = budgetIds,
|
||||
expense = call.request.queryParameters["expense"]?.toBoolean(),
|
||||
archived = call.request.queryParameters["archived"]?.toBoolean()
|
||||
).map { it.asResponse() })
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val budgetIds = permissionRepository.findAll(userId = session.userId).map { it.budgetId }
|
||||
if (budgetIds.isEmpty()) {
|
||||
errorResponse()
|
||||
return@get
|
||||
call.respondCatching {
|
||||
categoryService.category(
|
||||
categoryId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
categoryRepository.findAll(
|
||||
ids = call.parameters.getAll("id"),
|
||||
budgetIds = budgetIds
|
||||
)
|
||||
.map { it.asResponse() }
|
||||
.firstOrNull()?.let {
|
||||
call.respond(it)
|
||||
} ?: errorResponse()
|
||||
}
|
||||
|
||||
post {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<CategoryRequest>()
|
||||
if (request.title.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty")
|
||||
return@post
|
||||
call.respondCatching {
|
||||
categoryService.save(call.receive<CategoryRequest>(), requireSession().userId)
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
|
||||
return@post
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
request.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@post
|
||||
}
|
||||
call.respond(
|
||||
categoryRepository.save(
|
||||
Category(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<CategoryRequest>()
|
||||
val category = categoryRepository.findAll(ids = call.parameters.getAll("id"))
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@put
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
category.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@put
|
||||
call.respondCatching {
|
||||
categoryService.save(
|
||||
request = call.receive<CategoryRequest>(),
|
||||
userId = requireSession().userId,
|
||||
categoryId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
call.respond(
|
||||
categoryRepository.save(
|
||||
category.copy(
|
||||
title = request.title ?: category.title,
|
||||
description = request.description ?: category.description,
|
||||
amount = request.amount ?: category.amount,
|
||||
expense = request.expense ?: category.expense,
|
||||
archived = request.archived ?: category.archived,
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val categoryId = call.parameters.entries().first().value
|
||||
val category = categoryRepository.findAll(ids = categoryId)
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
errorResponse(HttpStatusCode.NotFound)
|
||||
return@delete
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
category.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@delete
|
||||
call.respondCatching {
|
||||
categoryService.delete(
|
||||
call.parameters.getOrFail("id"),
|
||||
requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
categoryRepository.delete(category)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ErrorResponse(val message: String)
|
|
@ -1,158 +1,59 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionRequest
|
||||
import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.respondCatching
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.util.pipeline.*
|
||||
import java.time.Instant
|
||||
|
||||
fun Application.recurringTransactionRoutes(
|
||||
recurringTransactionRepository: RecurringTransactionRepository,
|
||||
permissionRepository: PermissionRepository
|
||||
) {
|
||||
suspend fun PipelineContext<Unit, ApplicationCall>.recurringTransactionAfterPermissionCheck(
|
||||
id: String?,
|
||||
userId: String,
|
||||
success: suspend (RecurringTransaction) -> Unit
|
||||
) {
|
||||
if (id.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "id is required")
|
||||
return
|
||||
}
|
||||
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(id)).firstOrNull()
|
||||
?: run {
|
||||
errorResponse()
|
||||
return
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
userId,
|
||||
recurringTransaction.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
application.log.info("No permissions on budget ${recurringTransaction.budgetId}.")
|
||||
return
|
||||
}
|
||||
success(recurringTransaction)
|
||||
}
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.recurringTransactionRoutes(recurringTransactionService: RecurringTransactionService) {
|
||||
routing {
|
||||
route("/api/recurringtransactions") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
val session = call.principal<Session>()!!
|
||||
val budgetId = call.request.queryParameters["budgetId"]
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@get
|
||||
}
|
||||
call.respond(
|
||||
recurringTransactionRepository.findAll(
|
||||
budgetId = budgetId!!
|
||||
).map { it.asResponse() }
|
||||
)
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
recurringTransactionAfterPermissionCheck(call.parameters["id"]!!, session.userId) {
|
||||
call.respond(it.asResponse())
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<RecurringTransactionRequest>()
|
||||
if (request.title.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty")
|
||||
return@post
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
|
||||
return@post
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
request.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@post
|
||||
}
|
||||
call.respond(
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId,
|
||||
categoryId = request.categoryId,
|
||||
createdBy = session.userId,
|
||||
start = request.start?.toInstant() ?: Instant.now(),
|
||||
finish = request.finish?.toInstant(),
|
||||
frequency = request.frequency.asFrequency()
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<RecurringTransactionRequest>()
|
||||
recurringTransactionAfterPermissionCheck(
|
||||
call.parameters["id"]!!,
|
||||
session.userId
|
||||
) { recurringTransaction ->
|
||||
if (request.budgetId != recurringTransaction.budgetId) {
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
request.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@recurringTransactionAfterPermissionCheck
|
||||
}
|
||||
}
|
||||
call.respond(
|
||||
recurringTransactionRepository.save(
|
||||
recurringTransaction.copy(
|
||||
title = request.title ?: recurringTransaction.title,
|
||||
description = request.description ?: recurringTransaction.description,
|
||||
amount = request.amount ?: recurringTransaction.amount,
|
||||
expense = request.expense ?: recurringTransaction.expense,
|
||||
categoryId = request.categoryId ?: recurringTransaction.categoryId,
|
||||
budgetId = request.budgetId ?: recurringTransaction.budgetId,
|
||||
start = request.start?.toInstant() ?: recurringTransaction.start,
|
||||
finish = request.finish?.toInstant() ?: recurringTransaction.finish,
|
||||
frequency = request.frequency.asFrequency()
|
||||
)
|
||||
).asResponse()
|
||||
call.respondCatching {
|
||||
recurringTransactionService.recurringTransactions(
|
||||
budgetId = call.request.queryParameters.getOrFail("budgetId"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
call.respondCatching {
|
||||
recurringTransactionService.recurringTransaction(
|
||||
call.parameters.getOrFail("id"),
|
||||
requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
call.respondCatching {
|
||||
recurringTransactionService.save(
|
||||
request = call.receive<RecurringTransactionRequest>(),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
recurringTransactionService.save(
|
||||
request = call.receive<RecurringTransactionRequest>(),
|
||||
userId = requireSession().userId,
|
||||
recurringTransactionId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
recurringTransactionAfterPermissionCheck(call.parameters["id"]!!, session.userId) {
|
||||
val response = if (recurringTransactionRepository.delete(it)) {
|
||||
HttpStatusCode.NoContent
|
||||
} else {
|
||||
HttpStatusCode.InternalServerError
|
||||
}
|
||||
call.respond(response)
|
||||
call.respondCatching {
|
||||
recurringTransactionService.delete(call.parameters.getOrFail("id"), requireSession().userId)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,169 +1,85 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.storage.TransactionRepository
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.respondCatching
|
||||
import com.wbrawner.twigs.service.transaction.BalanceResponse
|
||||
import com.wbrawner.twigs.service.transaction.TransactionRequest
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import java.time.Instant
|
||||
|
||||
fun Application.transactionRoutes(
|
||||
transactionRepository: TransactionRepository,
|
||||
permissionRepository: PermissionRepository
|
||||
) {
|
||||
fun Application.transactionRoutes(transactionService: TransactionService) {
|
||||
routing {
|
||||
route("/api/transactions") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
val session = call.principal<Session>()!!
|
||||
call.respond(
|
||||
transactionRepository.findAll(
|
||||
budgetIds = permissionRepository.findAll(
|
||||
budgetIds = call.request.queryParameters.getAll("budgetIds"),
|
||||
userId = session.userId
|
||||
).map { it.budgetId },
|
||||
call.respondCatching {
|
||||
transactionService.transactions(
|
||||
budgetIds = call.request.queryParameters.getAll("budgetIds").orEmpty(),
|
||||
categoryIds = call.request.queryParameters.getAll("categoryIds"),
|
||||
from = call.request.queryParameters["from"]?.let { Instant.parse(it) },
|
||||
to = call.request.queryParameters["to"]?.let { Instant.parse(it) },
|
||||
expense = call.request.queryParameters["expense"]?.toBoolean(),
|
||||
).map { it.asResponse() })
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val transaction = transactionRepository.findAll(
|
||||
ids = call.parameters.getAll("id"),
|
||||
budgetIds = permissionRepository.findAll(
|
||||
userId = session.userId
|
||||
call.respondCatching {
|
||||
transactionService.transaction(
|
||||
transactionId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
.map { it.budgetId }
|
||||
)
|
||||
.map { it.asResponse() }
|
||||
.firstOrNull()
|
||||
transaction?.let {
|
||||
call.respond(it)
|
||||
} ?: errorResponse()
|
||||
}
|
||||
}
|
||||
|
||||
get("/sum") {
|
||||
val categoryId = call.request.queryParameters["categoryId"]
|
||||
val budgetId = call.request.queryParameters["budgetId"]
|
||||
val from = call.request.queryParameters["from"]?.toInstant() ?: firstOfMonth
|
||||
val to = call.request.queryParameters["to"]?.toInstant() ?: endOfMonth
|
||||
val balance = if (!categoryId.isNullOrBlank()) {
|
||||
if (!budgetId.isNullOrBlank()) {
|
||||
errorResponse(
|
||||
HttpStatusCode.BadRequest,
|
||||
"budgetId and categoryId cannot be provided together"
|
||||
call.respondCatching {
|
||||
BalanceResponse(
|
||||
transactionService.sum(
|
||||
budgetId = call.request.queryParameters["budgetId"],
|
||||
categoryId = call.request.queryParameters["categoryId"],
|
||||
from = call.request.queryParameters["from"]?.toInstant() ?: firstOfMonth,
|
||||
to = call.request.queryParameters["to"]?.toInstant() ?: endOfMonth,
|
||||
userId = requireSession().userId,
|
||||
)
|
||||
return@get
|
||||
}
|
||||
transactionRepository.sumByCategory(categoryId, from, to)
|
||||
} else if (!budgetId.isNullOrBlank()) {
|
||||
transactionRepository.sumByBudget(budgetId, from, to)
|
||||
} else {
|
||||
errorResponse(HttpStatusCode.BadRequest, "budgetId or categoryId must be provided to sum")
|
||||
return@get
|
||||
)
|
||||
}
|
||||
call.respond(BalanceResponse(balance))
|
||||
}
|
||||
|
||||
post {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<TransactionRequest>()
|
||||
if (request.title.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty")
|
||||
return@post
|
||||
call.respondCatching {
|
||||
transactionService.save(
|
||||
request = call.receive<TransactionRequest>(),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
|
||||
return@post
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
request.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@post
|
||||
}
|
||||
call.respond(
|
||||
transactionRepository.save(
|
||||
Transaction(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId,
|
||||
categoryId = request.categoryId,
|
||||
createdBy = session.userId,
|
||||
date = request.date?.let { Instant.parse(it) } ?: Instant.now()
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<TransactionRequest>()
|
||||
val transaction = transactionRepository.findAll(ids = call.parameters.getAll("id"))
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
errorResponse()
|
||||
return@put
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
transaction.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@put
|
||||
call.respondCatching {
|
||||
transactionService.save(
|
||||
request = call.receive<TransactionRequest>(),
|
||||
userId = requireSession().userId,
|
||||
transactionId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
call.respond(
|
||||
transactionRepository.save(
|
||||
transaction.copy(
|
||||
title = request.title ?: transaction.title,
|
||||
description = request.description ?: transaction.description,
|
||||
amount = request.amount ?: transaction.amount,
|
||||
expense = request.expense ?: transaction.expense,
|
||||
date = request.date?.let { Instant.parse(it) } ?: transaction.date,
|
||||
categoryId = request.categoryId ?: transaction.categoryId,
|
||||
budgetId = request.budgetId ?: transaction.budgetId,
|
||||
createdBy = transaction.createdBy,
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val transaction = transactionRepository.findAll(ids = call.parameters.getAll("id"))
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
errorResponse()
|
||||
return@delete
|
||||
}
|
||||
requireBudgetWithPermission(
|
||||
permissionRepository,
|
||||
session.userId,
|
||||
transaction.budgetId,
|
||||
Permission.WRITE
|
||||
) {
|
||||
return@delete
|
||||
}
|
||||
val response = if (transactionRepository.delete(transaction)) {
|
||||
call.respondCatching {
|
||||
transactionService.delete(
|
||||
transactionId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
} else {
|
||||
HttpStatusCode.InternalServerError
|
||||
}
|
||||
call.respond(response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,202 +1,84 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.User
|
||||
import com.wbrawner.twigs.storage.PasswordResetRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.storage.SessionRepository
|
||||
import com.wbrawner.twigs.storage.UserRepository
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.respondCatching
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import java.time.Instant
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.userRoutes(
|
||||
emailService: EmailService,
|
||||
passwordResetRepository: PasswordResetRepository,
|
||||
permissionRepository: PermissionRepository,
|
||||
sessionRepository: SessionRepository,
|
||||
userRepository: UserRepository
|
||||
) {
|
||||
fun Application.userRoutes(userService: UserService) {
|
||||
routing {
|
||||
route("/api/users") {
|
||||
post("/login") {
|
||||
val request = call.receive<LoginRequest>()
|
||||
val user =
|
||||
userRepository.findAll(nameOrEmail = request.username, password = request.password.hash())
|
||||
.firstOrNull()
|
||||
?: userRepository.findAll(nameOrEmail = request.username, password = request.password.hash())
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
errorResponse(HttpStatusCode.Unauthorized, "Invalid credentials")
|
||||
return@post
|
||||
}
|
||||
val session = sessionRepository.save(Session(userId = user.id))
|
||||
call.respond(session.asResponse())
|
||||
call.respondCatching {
|
||||
userService.login(call.receive())
|
||||
}
|
||||
}
|
||||
|
||||
post("/register") {
|
||||
val request = call.receive<UserRequest>()
|
||||
if (request.username.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Username must not be null or blank")
|
||||
return@post
|
||||
call.respondCatching {
|
||||
userService.register(call.receive())
|
||||
}
|
||||
if (request.password.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Password must not be null or blank")
|
||||
return@post
|
||||
}
|
||||
|
||||
|
||||
route("/resetpassword") {
|
||||
post {
|
||||
call.respondCatching {
|
||||
userService.requestPasswordResetEmail(call.receive())
|
||||
HttpStatusCode.Accepted
|
||||
}
|
||||
}
|
||||
val existingUser = userRepository.findAll(nameOrEmail = request.username).firstOrNull()
|
||||
?: request.email?.let {
|
||||
return@let if (it.isBlank()) {
|
||||
null
|
||||
} else {
|
||||
userRepository.findAll(nameOrEmail = it).firstOrNull()
|
||||
}
|
||||
}
|
||||
existingUser?.let {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Username or email already taken")
|
||||
return@post
|
||||
|
||||
put {
|
||||
call.respondCatching {
|
||||
userService.resetPassword(call.receive())
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
call.respond(
|
||||
userRepository.save(
|
||||
User(
|
||||
name = request.username,
|
||||
password = request.password.hash(),
|
||||
email = if (request.email.isNullOrBlank()) null else request.email
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
val query = call.request.queryParameters.getAll("query")
|
||||
if (query?.firstOrNull()?.isNotBlank() == true) {
|
||||
call.respond(userRepository.findAll(nameLike = query.first()).map { it.asResponse() })
|
||||
return@get
|
||||
call.respondCatching {
|
||||
userService.users(
|
||||
query = call.request.queryParameters["query"],
|
||||
budgetIds = call.request.queryParameters.getAll("budgetId"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
}
|
||||
permissionRepository.findAll(
|
||||
budgetIds = call.request.queryParameters.getAll("budgetId")
|
||||
).mapNotNull {
|
||||
userRepository.findAll(ids = listOf(it.userId))
|
||||
.firstOrNull()
|
||||
?.asResponse()
|
||||
}.run { call.respond(this) }
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
userRepository.findAll(ids = call.parameters.getAll("id"))
|
||||
.firstOrNull()
|
||||
?.asResponse()
|
||||
?.let { call.respond(it) }
|
||||
?: errorResponse(HttpStatusCode.NotFound)
|
||||
}
|
||||
|
||||
post {
|
||||
val request = call.receive<UserRequest>()
|
||||
if (request.username.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Username must not be null or blank")
|
||||
return@post
|
||||
call.respondCatching {
|
||||
userService.user(call.parameters.getOrFail("id"))
|
||||
}
|
||||
if (request.password.isNullOrBlank()) {
|
||||
errorResponse(HttpStatusCode.BadRequest, "Password must not be null or blank")
|
||||
return@post
|
||||
}
|
||||
call.respond(
|
||||
userRepository.save(
|
||||
User(
|
||||
name = request.username,
|
||||
password = request.password,
|
||||
email = request.email
|
||||
)
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
val request = call.receive<UserRequest>()
|
||||
// TODO: Add some kind of admin denotation to allow admins to edit other users
|
||||
if (call.parameters["id"] != session.userId) {
|
||||
errorResponse(HttpStatusCode.Forbidden)
|
||||
return@put
|
||||
call.respondCatching {
|
||||
userService.save(
|
||||
request = call.receive(),
|
||||
targetUserId = call.parameters.getOrFail("id"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
}
|
||||
call.respond(
|
||||
userRepository.save(
|
||||
userRepository.findAll(ids = call.parameters.getAll("id"))
|
||||
.first()
|
||||
.run {
|
||||
copy(
|
||||
name = request.username ?: name,
|
||||
password = request.password?.hash() ?: password,
|
||||
email = request.email ?: email
|
||||
)
|
||||
}
|
||||
).asResponse()
|
||||
)
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
val session = call.principal<Session>()!!
|
||||
// TODO: Add some kind of admin denotation to allow admins to delete other users
|
||||
val user = userRepository.findAll(call.parameters.entries().first().value).firstOrNull()
|
||||
if (user == null) {
|
||||
errorResponse()
|
||||
return@delete
|
||||
call.respondCatching {
|
||||
userService.delete(
|
||||
targetUserId = call.parameters.getOrFail("id"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
if (user.id != session.userId) {
|
||||
errorResponse(HttpStatusCode.Forbidden)
|
||||
return@delete
|
||||
}
|
||||
userRepository.delete(user)
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/api/resetpassword") {
|
||||
post {
|
||||
val request = call.receive<ResetPasswordRequest>()
|
||||
userRepository.findAll(nameOrEmail = request.username)
|
||||
.firstOrNull()
|
||||
?.let {
|
||||
val email = it.email ?: return@let
|
||||
val passwordResetToken = passwordResetRepository.save(PasswordResetToken(userId = it.id))
|
||||
emailService.sendPasswordResetEmail(passwordResetToken, email)
|
||||
}
|
||||
call.respond(HttpStatusCode.Accepted)
|
||||
}
|
||||
}
|
||||
|
||||
route("/api/passwordreset") {
|
||||
post {
|
||||
val request = call.receive<PasswordResetRequest>()
|
||||
val passwordResetToken = passwordResetRepository.findAll(listOf(request.token))
|
||||
.firstOrNull()
|
||||
?: run {
|
||||
errorResponse(HttpStatusCode.Unauthorized, "Invalid token")
|
||||
return@post
|
||||
}
|
||||
if (passwordResetToken.expiration.isBefore(Instant.now())) {
|
||||
errorResponse(HttpStatusCode.Unauthorized, "Token expired")
|
||||
return@post
|
||||
}
|
||||
userRepository.findAll(listOf(passwordResetToken.userId))
|
||||
.firstOrNull()
|
||||
?.let {
|
||||
userRepository.save(it.copy(password = request.password.hash()))
|
||||
passwordResetRepository.delete(passwordResetToken)
|
||||
}
|
||||
?: run {
|
||||
errorResponse(HttpStatusCode.InternalServerError, "Invalid token")
|
||||
return@post
|
||||
}
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import java.net.URI
|
||||
import java.util.*
|
||||
|
||||
plugins {
|
||||
java
|
||||
|
@ -24,11 +23,13 @@ dependencies {
|
|||
implementation(libs.kotlin.reflect)
|
||||
implementation(libs.bundles.ktor.server)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.bcrypt)
|
||||
implementation(libs.logback)
|
||||
implementation(libs.mail)
|
||||
implementation(project(mapOf("path" to ":service")))
|
||||
testImplementation(project(":testhelpers"))
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
testImplementation(libs.ktor.client.content.negotiation)
|
||||
testImplementation(libs.ktor.server.test)
|
||||
}
|
||||
|
||||
description = "twigs-server"
|
||||
|
@ -51,3 +52,10 @@ tasks.shadowJar {
|
|||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
reports {
|
||||
junitXml.required.set(true)
|
||||
html.required.set(false)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,128 +1,214 @@
|
|||
package com.wbrawner.twigs.server
|
||||
|
||||
import ch.qos.logback.classic.Level
|
||||
import at.favre.lib.crypto.bcrypt.BCrypt
|
||||
import com.github.mustachejava.DefaultMustacheFactory
|
||||
import com.wbrawner.twigs.*
|
||||
import com.wbrawner.twigs.db.*
|
||||
import com.wbrawner.twigs.model.CookieSession
|
||||
import com.wbrawner.twigs.model.HeaderSession
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.*
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.budget.DefaultBudgetService
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.category.DefaultCategoryService
|
||||
import com.wbrawner.twigs.service.recurringtransaction.DefaultRecurringTransactionService
|
||||
import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionService
|
||||
import com.wbrawner.twigs.service.transaction.DefaultTransactionService
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import com.wbrawner.twigs.service.user.DefaultUserService
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import com.wbrawner.twigs.storage.PasswordHasher
|
||||
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
|
||||
import com.wbrawner.twigs.web.webRoutes
|
||||
import com.zaxxer.hikari.HikariConfig
|
||||
import com.zaxxer.hikari.HikariDataSource
|
||||
import io.ktor.client.request.forms.*
|
||||
import io.ktor.http.*
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.cio.*
|
||||
import io.ktor.server.engine.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.plugins.callloging.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
import io.ktor.server.plugins.cors.routing.*
|
||||
import io.ktor.server.plugins.forwardedheaders.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.sessions.*
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.lang.RuntimeException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
fun main(args: Array<String>): Unit = io.ktor.server.cio.EngineMain.main(args)
|
||||
fun main() {
|
||||
embeddedServer(
|
||||
CIO,
|
||||
port = System.getenv("PORT")?.toIntOrNull() ?: 8080,
|
||||
module = Application::module
|
||||
).start(wait = true)
|
||||
}
|
||||
|
||||
private const val DATABASE_VERSION = 3
|
||||
|
||||
fun Application.module() {
|
||||
val dbType = environment.config.propertyOrNull("twigs.database.type")?.getString() ?: "sqlite"
|
||||
val dbHost = environment.config.propertyOrNull("twigs.database.host")?.getString() ?: "localhost"
|
||||
val dbPort = environment.config.propertyOrNull("twigs.database.port")?.getString() ?: "5432"
|
||||
val dbName = environment.config.propertyOrNull("twigs.database.name")?.getString() ?: "twigs"
|
||||
val dbUser = environment.config.propertyOrNull("twigs.database.user")?.getString() ?: "twigs"
|
||||
val dbPass = environment.config.propertyOrNull("twigs.database.password")?.getString() ?: "twigs"
|
||||
val dbType = System.getenv("TWIGS_DB_TYPE") ?: "sqlite"
|
||||
val dbHost = System.getenv("TWIGS_DB_HOST") ?: "localhost"
|
||||
val dbPort = System.getenv("TWIGS_DB_PORT") ?: "5432"
|
||||
val dbName = System.getenv("TWIGS_DB_NAME") ?: "twigs"
|
||||
val dbUser = System.getenv("TWIGS_DB_USER") ?: "twigs"
|
||||
val dbPass = System.getenv("TWIGS_DB_PASS") ?: "twigs"
|
||||
val jdbcUrl = when (dbType) {
|
||||
"postgresql" -> {
|
||||
"jdbc:$dbType://$dbHost:$dbPort/$dbName?stringtype=unspecified"
|
||||
}
|
||||
|
||||
"sqlite" -> {
|
||||
Class.forName("org.sqlite.JDBC")
|
||||
"jdbc:$dbType:$dbName"
|
||||
}
|
||||
|
||||
else -> {
|
||||
throw RuntimeException("Unsupported DB type: $dbType")
|
||||
}
|
||||
}
|
||||
(LoggerFactory.getLogger("com.zaxxer.hikari") as ch.qos.logback.classic.Logger).level = Level.DEBUG
|
||||
HikariDataSource(HikariConfig().apply {
|
||||
setJdbcUrl(jdbcUrl)
|
||||
username = dbUser
|
||||
password = dbPass
|
||||
}).also {
|
||||
val metadataRepository = JdbcMetadataRepository(it)
|
||||
val metadata = runBlocking {
|
||||
val metadata = (metadataRepository.findAll().firstOrNull() ?: DatabaseMetadata())
|
||||
var version = metadata.version
|
||||
while (currentCoroutineContext().isActive && version++ < DATABASE_VERSION) {
|
||||
metadataRepository.runMigration(version)
|
||||
metadataRepository.save(metadata.copy(version = version))
|
||||
}
|
||||
if (metadata.salt.isBlank()) {
|
||||
metadataRepository.save(
|
||||
metadata.copy(
|
||||
salt = System.getenv("TWIGS_PW_SALT")
|
||||
?: randomString(16)
|
||||
)
|
||||
)
|
||||
} else {
|
||||
metadata
|
||||
}
|
||||
}
|
||||
val budgetRepository = JdbcBudgetRepository(it)
|
||||
val categoryRepository = JdbcCategoryRepository(it)
|
||||
val permissionRepository = JdbcPermissionRepository(it)
|
||||
val passwordResetRepository = JdbcPasswordResetRepository(it)
|
||||
val passwordHasher = PasswordHasher { password ->
|
||||
String(BCrypt.withDefaults().hash(10, metadata.salt.toByteArray(), password.toByteArray()))
|
||||
}
|
||||
val recurringTransactionRepository = JdbcRecurringTransactionRepository(it)
|
||||
val sessionRepository = JdbcSessionRepository(it)
|
||||
val transactionRepository = JdbcTransactionRepository(it)
|
||||
val userRepository = JdbcUserRepository(it)
|
||||
val emailService = SmtpEmailService(
|
||||
from = System.getenv("TWIGS_SMTP_FROM"),
|
||||
host = System.getenv("TWIGS_SMTP_HOST"),
|
||||
port = System.getenv("TWIGS_SMTP_PORT")?.toIntOrNull(),
|
||||
username = System.getenv("TWIGS_SMTP_USER"),
|
||||
password = System.getenv("TWIGS_SMTP_PASS"),
|
||||
)
|
||||
val jobs = listOf(
|
||||
SessionCleanupJob(sessionRepository),
|
||||
RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
|
||||
)
|
||||
val sessionValidator: suspend ApplicationCall.(Session) -> Principal? = validate@{ session ->
|
||||
application.environment.log.info("Validating session")
|
||||
val storedSession = sessionRepository.findAll(session.token)
|
||||
.firstOrNull()
|
||||
if (storedSession == null) {
|
||||
application.environment.log.info("Did not find session!")
|
||||
return@validate null
|
||||
} else {
|
||||
application.environment.log.info("Found session!")
|
||||
}
|
||||
return@validate if (twoWeeksFromNow.isAfter(storedSession.expiration)) {
|
||||
sessionRepository.save(storedSession.updateExpiration(newExpiration = twoWeeksFromNow))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
moduleWithDependencies(
|
||||
emailService = SmtpEmailService(
|
||||
from = environment.config.propertyOrNull("twigs.smtp.from")?.getString(),
|
||||
host = environment.config.propertyOrNull("twigs.smtp.host")?.getString(),
|
||||
port = environment.config.propertyOrNull("twigs.smtp.port")?.getString()?.toIntOrNull(),
|
||||
username = environment.config.propertyOrNull("twigs.smtp.user")?.getString(),
|
||||
password = environment.config.propertyOrNull("twigs.smtp.pass")?.getString(),
|
||||
budgetService = DefaultBudgetService(budgetRepository, permissionRepository),
|
||||
categoryService = DefaultCategoryService(categoryRepository, permissionRepository),
|
||||
recurringTransactionService = DefaultRecurringTransactionService(
|
||||
recurringTransactionRepository,
|
||||
permissionRepository
|
||||
),
|
||||
metadataRepository = MetadataRepository(it),
|
||||
budgetRepository = JdbcBudgetRepository(it),
|
||||
categoryRepository = JdbcCategoryRepository(it),
|
||||
passwordResetRepository = JdbcPasswordResetRepository(it),
|
||||
permissionRepository = JdbcPermissionRepository(it),
|
||||
recurringTransactionRepository = JdbcRecurringTransactionRepository(it),
|
||||
sessionRepository = JdbcSessionRepository(it),
|
||||
transactionRepository = JdbcTransactionRepository(it),
|
||||
userRepository = JdbcUserRepository(it)
|
||||
transactionService = DefaultTransactionService(
|
||||
transactionRepository,
|
||||
categoryRepository,
|
||||
permissionRepository
|
||||
),
|
||||
userService = DefaultUserService(
|
||||
emailService,
|
||||
passwordResetRepository,
|
||||
permissionRepository,
|
||||
sessionRepository,
|
||||
userRepository,
|
||||
passwordHasher
|
||||
),
|
||||
jobs = jobs,
|
||||
sessionValidator = sessionValidator
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun Application.moduleWithDependencies(
|
||||
emailService: EmailService,
|
||||
metadataRepository: MetadataRepository,
|
||||
budgetRepository: BudgetRepository,
|
||||
categoryRepository: CategoryRepository,
|
||||
passwordResetRepository: PasswordResetRepository,
|
||||
permissionRepository: PermissionRepository,
|
||||
recurringTransactionRepository: RecurringTransactionRepository,
|
||||
sessionRepository: SessionRepository,
|
||||
transactionRepository: TransactionRepository,
|
||||
userRepository: UserRepository
|
||||
budgetService: BudgetService,
|
||||
categoryService: CategoryService,
|
||||
recurringTransactionService: RecurringTransactionService,
|
||||
transactionService: TransactionService,
|
||||
userService: UserService,
|
||||
jobs: List<Job>,
|
||||
sessionValidator: suspend ApplicationCall.(Session) -> Principal?
|
||||
) {
|
||||
install(XForwardedHeaders)
|
||||
install(CallLogging)
|
||||
install(Authentication) {
|
||||
session<Session> {
|
||||
challenge {
|
||||
call.respond(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
validate { session ->
|
||||
application.environment.log.info("Validating session")
|
||||
val storedSession = sessionRepository.findAll(session.token)
|
||||
.firstOrNull()
|
||||
if (storedSession == null) {
|
||||
application.environment.log.info("Did not find session!")
|
||||
return@validate null
|
||||
} else {
|
||||
application.environment.log.info("Found session!")
|
||||
}
|
||||
return@validate if (twoWeeksFromNow.isAfter(storedSession.expiration)) {
|
||||
sessionRepository.save(storedSession.copy(expiration = twoWeeksFromNow))
|
||||
} else {
|
||||
null
|
||||
}
|
||||
validate(sessionValidator)
|
||||
}
|
||||
session<CookieSession>(TWIGS_SESSION_COOKIE) {
|
||||
challenge {
|
||||
call.respond(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
validate(sessionValidator)
|
||||
}
|
||||
}
|
||||
install(Sessions) {
|
||||
header<Session>("Authorization") {
|
||||
serializer = object : SessionSerializer<Session> {
|
||||
override fun deserialize(text: String): Session {
|
||||
override fun deserialize(text: String): HeaderSession {
|
||||
this@moduleWithDependencies.environment.log.info("Deserializing session!")
|
||||
return Session(token = text.substringAfter("Bearer "))
|
||||
return HeaderSession(token = text.substringAfter("Bearer "))
|
||||
}
|
||||
|
||||
override fun serialize(session: Session): String = session.token
|
||||
}
|
||||
}
|
||||
|
||||
cookie<CookieSession>(TWIGS_SESSION_COOKIE) {
|
||||
serializer = object : SessionSerializer<CookieSession> {
|
||||
override fun deserialize(text: String): CookieSession {
|
||||
this@moduleWithDependencies.environment.log.info("Deserializing session!")
|
||||
return CookieSession(token = text)
|
||||
}
|
||||
|
||||
override fun serialize(session: CookieSession): String = session.token
|
||||
}
|
||||
cookie.httpOnly = true
|
||||
cookie.secure = true
|
||||
cookie.extensions["SameSite"] = "Strict"
|
||||
}
|
||||
}
|
||||
install(ContentNegotiation) {
|
||||
json(json = Json {
|
||||
|
@ -135,11 +221,15 @@ fun Application.moduleWithDependencies(
|
|||
prettyPrint = false
|
||||
useArrayPolymorphism = true
|
||||
})
|
||||
|
||||
formData()
|
||||
}
|
||||
install(CORS) {
|
||||
allowHost("twigs.wbrawner.com", listOf("http", "https")) // TODO: Make configurable
|
||||
allowHost("localhost:4200", listOf("http", "https")) // TODO: Make configurable
|
||||
allowMethod(HttpMethod.Options)
|
||||
allowMethod(HttpMethod.Get)
|
||||
allowMethod(HttpMethod.Post)
|
||||
allowMethod(HttpMethod.Put)
|
||||
allowMethod(HttpMethod.Delete)
|
||||
allowHeader(HttpHeaders.Authorization)
|
||||
|
@ -162,33 +252,16 @@ fun Application.moduleWithDependencies(
|
|||
allowHeader("DNT")
|
||||
allowCredentials = true
|
||||
}
|
||||
budgetRoutes(budgetRepository, permissionRepository)
|
||||
categoryRoutes(categoryRepository, permissionRepository)
|
||||
recurringTransactionRoutes(recurringTransactionRepository, permissionRepository)
|
||||
transactionRoutes(transactionRepository, permissionRepository)
|
||||
userRoutes(emailService, passwordResetRepository, permissionRepository, sessionRepository, userRepository)
|
||||
webRoutes()
|
||||
install(Mustache) {
|
||||
mustacheFactory = DefaultMustacheFactory("templates")
|
||||
}
|
||||
budgetRoutes(budgetService)
|
||||
categoryRoutes(categoryService)
|
||||
recurringTransactionRoutes(recurringTransactionService)
|
||||
transactionRoutes(transactionService)
|
||||
userRoutes(userService)
|
||||
webRoutes(budgetService, categoryService, transactionService, userService)
|
||||
launch {
|
||||
val metadata = (metadataRepository.findAll().firstOrNull() ?: DatabaseMetadata())
|
||||
var version = metadata.version
|
||||
while (currentCoroutineContext().isActive && version++ < DATABASE_VERSION) {
|
||||
metadataRepository.runMigration(version)
|
||||
metadataRepository.save(metadata.copy(version = version))
|
||||
}
|
||||
salt = metadata.salt.ifEmpty {
|
||||
metadataRepository.save(
|
||||
metadata.copy(
|
||||
salt = environment.config
|
||||
.propertyOrNull("twigs.password.salt")
|
||||
?.getString()
|
||||
?: randomString(16)
|
||||
)
|
||||
).salt
|
||||
}
|
||||
val jobs = listOf(
|
||||
SessionCleanupJob(sessionRepository),
|
||||
RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
|
||||
)
|
||||
while (currentCoroutineContext().isActive) {
|
||||
jobs.forEach { it.run() }
|
||||
delay(TimeUnit.HOURS.toMillis(1))
|
||||
|
|
|
@ -1,30 +0,0 @@
|
|||
ktor {
|
||||
deployment {
|
||||
port = 8080
|
||||
port = ${?TWIGS_PORT}
|
||||
}
|
||||
application {
|
||||
modules = [ com.wbrawner.twigs.server.ApplicationKt.module ]
|
||||
}
|
||||
}
|
||||
|
||||
twigs {
|
||||
database {
|
||||
type = ${?TWIGS_DB_TYPE}
|
||||
host = ${?TWIGS_DB_HOST}
|
||||
port = ${?TWIGS_DB_PORT}
|
||||
name = ${?TWIGS_DB_NAME}
|
||||
user = ${?TWIGS_DB_USER}
|
||||
password = ${?TWIGS_DB_PASS}
|
||||
}
|
||||
password {
|
||||
salt = ${?TWIGS_PW_SALT}
|
||||
}
|
||||
smtp {
|
||||
from = ${?TWIGS_SMTP_FROM}
|
||||
host = ${?TWIGS_SMTP_HOST}
|
||||
port = ${?TWIGS_SMTP_PORT}
|
||||
user = ${?TWIGS_SMTP_USER}
|
||||
pass = ${?TWIGS_SMTP_PASS}
|
||||
}
|
||||
}
|
|
@ -3,9 +3,9 @@ package com.wbrawner.twigs.server
|
|||
import com.wbrawner.twigs.model.*
|
||||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import com.wbrawner.twigs.storage.TransactionRepository
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeRecurringTransactionsRepository
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeRecurringTransactionRepository
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeTransactionRepository
|
||||
import kotlinx.coroutines.test.runBlockingTest
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
@ -21,13 +21,13 @@ class RecurringTransactionProcessingJobTest {
|
|||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
recurringTransactionRepository = FakeRecurringTransactionsRepository()
|
||||
recurringTransactionRepository = FakeRecurringTransactionRepository()
|
||||
transactionRepository = FakeTransactionRepository()
|
||||
job = RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are created every day`() = runBlockingTest {
|
||||
fun `daily transactions are created every day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -49,7 +49,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are only created once per day`() = runBlockingTest {
|
||||
fun `daily transactions are only created once per day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -71,7 +71,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are created every other day`() = runBlockingTest {
|
||||
fun `daily transactions are created every other day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -90,7 +90,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `weekly transactions are created every thursday`() = runBlockingTest {
|
||||
fun `weekly transactions are created every thursday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -113,7 +113,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `weekly transactions are created every third thursday`() = runBlockingTest {
|
||||
fun `weekly transactions are created every third thursday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -134,7 +134,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 1st of month`() = runBlockingTest {
|
||||
fun `monthly transactions are created every 1st of month`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -157,7 +157,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
|
||||
@Test
|
||||
fun `monthly transactions are created every last day of month when greater than max days in month`() =
|
||||
runBlockingTest {
|
||||
runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -180,7 +180,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 6 months`() = runBlockingTest {
|
||||
fun `monthly transactions are created every 6 months`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -201,7 +201,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 2nd tuesday`() = runBlockingTest {
|
||||
fun `monthly transactions are created every 2nd tuesday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -228,7 +228,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every last friday`() = runBlockingTest {
|
||||
fun `monthly transactions are created every last friday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -255,7 +255,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created in the new year`() = runBlockingTest {
|
||||
fun `monthly transactions are created in the new year`() = runTest {
|
||||
val start = Instant.parse("1971-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -280,7 +280,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every march 31st`() = runBlockingTest {
|
||||
fun `yearly transactions are created every march 31st`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -303,7 +303,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every other march 31st`() = runBlockingTest {
|
||||
fun `yearly transactions are created every other march 31st`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
@ -324,7 +324,7 @@ class RecurringTransactionProcessingJobTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every february 29th`() = runBlockingTest {
|
||||
fun `yearly transactions are created every february 29th`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
|
|
82
app/src/test/kotlin/com/wbrawner/twigs/server/api/ApiTest.kt
Normal file
|
@ -0,0 +1,82 @@
|
|||
package com.wbrawner.twigs.server.api
|
||||
|
||||
import com.wbrawner.twigs.server.moduleWithDependencies
|
||||
import com.wbrawner.twigs.service.budget.DefaultBudgetService
|
||||
import com.wbrawner.twigs.service.category.DefaultCategoryService
|
||||
import com.wbrawner.twigs.service.recurringtransaction.DefaultRecurringTransactionService
|
||||
import com.wbrawner.twigs.service.transaction.DefaultTransactionService
|
||||
import com.wbrawner.twigs.service.user.DefaultUserService
|
||||
import com.wbrawner.twigs.test.helpers.FakeEmailService
|
||||
import com.wbrawner.twigs.test.helpers.repository.*
|
||||
import io.ktor.client.*
|
||||
import io.ktor.client.plugins.contentnegotiation.*
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.testing.*
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
|
||||
open class ApiTest {
|
||||
lateinit var budgetRepository: FakeBudgetRepository
|
||||
lateinit var categoryRepository: FakeCategoryRepository
|
||||
lateinit var emailService: FakeEmailService
|
||||
lateinit var metadataRepository: FakeMetadataRepository
|
||||
lateinit var passwordResetRepository: FakePasswordResetRepository
|
||||
lateinit var permissionRepository: FakePermissionRepository
|
||||
lateinit var recurringTransactionRepository: FakeRecurringTransactionRepository
|
||||
lateinit var sessionRepository: FakeSessionRepository
|
||||
lateinit var transactionRepository: FakeTransactionRepository
|
||||
lateinit var userRepository: FakeUserRepository
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
budgetRepository = FakeBudgetRepository()
|
||||
categoryRepository = FakeCategoryRepository()
|
||||
emailService = FakeEmailService()
|
||||
metadataRepository = FakeMetadataRepository()
|
||||
passwordResetRepository = FakePasswordResetRepository()
|
||||
permissionRepository = FakePermissionRepository()
|
||||
recurringTransactionRepository = FakeRecurringTransactionRepository()
|
||||
sessionRepository = FakeSessionRepository()
|
||||
transactionRepository = FakeTransactionRepository()
|
||||
userRepository = FakeUserRepository()
|
||||
}
|
||||
|
||||
fun apiTest(test: suspend ApiTest.(client: HttpClient) -> Unit) = testApplication {
|
||||
application {
|
||||
moduleWithDependencies(
|
||||
budgetService = DefaultBudgetService(budgetRepository, permissionRepository),
|
||||
categoryService = DefaultCategoryService(categoryRepository, permissionRepository),
|
||||
recurringTransactionService = DefaultRecurringTransactionService(
|
||||
recurringTransactionRepository,
|
||||
permissionRepository
|
||||
),
|
||||
transactionService = DefaultTransactionService(
|
||||
transactionRepository,
|
||||
categoryRepository,
|
||||
permissionRepository
|
||||
),
|
||||
userService = DefaultUserService(
|
||||
emailService,
|
||||
passwordResetRepository,
|
||||
permissionRepository,
|
||||
sessionRepository,
|
||||
userRepository,
|
||||
{ it }
|
||||
),
|
||||
jobs = listOf(),
|
||||
sessionValidator = {
|
||||
sessionRepository.findAll(it.token).firstOrNull()
|
||||
}
|
||||
)
|
||||
}
|
||||
val client = createClient {
|
||||
install(ContentNegotiation) {
|
||||
json(json = Json {
|
||||
encodeDefaults = true
|
||||
explicitNulls = false
|
||||
})
|
||||
}
|
||||
}
|
||||
test(client)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,419 @@
|
|||
package com.wbrawner.twigs.server.api
|
||||
|
||||
import com.wbrawner.twigs.model.*
|
||||
import com.wbrawner.twigs.service.budget.BudgetRequest
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.user.UserPermissionRequest
|
||||
import com.wbrawner.twigs.service.user.UserPermissionResponse
|
||||
import io.ktor.client.call.*
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.http.*
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class BudgetRouteTest : ApiTest() {
|
||||
|
||||
@Test
|
||||
fun `fetching budgets requires authentication`() = apiTest { client ->
|
||||
val response = client.get("/api/budgets")
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fetching budgets returns empty list when there are no budgets`() = apiTest { client ->
|
||||
val session = Session()
|
||||
sessionRepository.save(session)
|
||||
val response = client.get("/api/budgets") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
assertEquals(0, response.body<List<BudgetResponse>>().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fetching budgets only returns budgets for current user`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val currentUserBudget = budgetRepository.save(Budget(name = "Test User's Budget"))
|
||||
val otherUserBudget = budgetRepository.save(Budget(name = "Other User's Budget"))
|
||||
permissionRepository.save(
|
||||
UserPermission(
|
||||
budgetId = currentUserBudget.id,
|
||||
userId = users[0].id,
|
||||
Permission.OWNER
|
||||
)
|
||||
)
|
||||
permissionRepository.save(UserPermission(budgetId = otherUserBudget.id, userId = users[1].id, Permission.OWNER))
|
||||
val response = client.get("/api/budgets") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
val returnedBudgets = response.body<List<BudgetResponse>>()
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
assertEquals(1, returnedBudgets.size)
|
||||
assertEquals(currentUserBudget.id, returnedBudgets.first().id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `creating budgets requires authentication`() = apiTest { client ->
|
||||
val request = BudgetRequest("Test Budget", "A budget for testing")
|
||||
val response = client.post("/api/budgets") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `newly created budgets are saved`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermissionRequest(users[0].id, Permission.OWNER),
|
||||
UserPermissionRequest(users[1].id, Permission.READ),
|
||||
)
|
||||
val request = BudgetRequest("Test Budget", "A budget for testing", permissions)
|
||||
val response = client.post("/api/budgets") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val responseBody: BudgetResponse = response.body()
|
||||
assert(responseBody.id.isNotEmpty())
|
||||
assertEquals("Test Budget", responseBody.name)
|
||||
assertEquals("A budget for testing", responseBody.description)
|
||||
assertEquals(2, responseBody.users.size)
|
||||
assert(responseBody.users.containsAll(permissions.map { UserPermissionResponse(it.user, it.permission) }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `newly created budgets include current user as owner if omitted`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermissionRequest(users[1].id, Permission.OWNER),
|
||||
)
|
||||
val request = BudgetRequest("Test Budget", "A budget for testing", permissions)
|
||||
val response = client.post("/api/budgets") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val responseBody: BudgetResponse = response.body()
|
||||
assert(responseBody.id.isNotEmpty())
|
||||
assertEquals("Test Budget", responseBody.name)
|
||||
assertEquals("A budget for testing", responseBody.description)
|
||||
assertEquals(2, responseBody.users.size)
|
||||
val expectedPermissions = listOf(
|
||||
UserPermissionResponse(users[0].id, Permission.OWNER),
|
||||
UserPermissionResponse(users[1].id, Permission.OWNER),
|
||||
)
|
||||
assert(responseBody.users.containsAll(expectedPermissions))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets requires authentication`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets returns forbidden for users with read only access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.READ),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets returns forbidden for users with write only access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.WRITE),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets returns success for users with manage access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val updatedBudget: BudgetResponse = response.body()
|
||||
assertEquals(request.name, updatedBudget.name)
|
||||
assertEquals(request.description, updatedBudget.description)
|
||||
val expectedUsers = permissions.map { UserPermissionResponse(it.userId, it.permission) }
|
||||
val updatedUsers = updatedBudget.users
|
||||
assertEquals(expectedUsers, updatedUsers)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets returns forbidden for users with no access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating non-existent budgets returns not found`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||
val response = client.put("/api/budgets/random-budget-id") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `updating budgets returns forbidden for users with manage access attempting to remove owner`() =
|
||||
apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget =
|
||||
budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val request = BudgetRequest(
|
||||
"Update Budget",
|
||||
"An update budget for testing",
|
||||
setOf(
|
||||
UserPermissionRequest(users[0].id, Permission.OWNER),
|
||||
UserPermissionRequest(users[0].id, Permission.MANAGE),
|
||||
)
|
||||
)
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting budgets requires authentication`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting budgets returns forbidden for users with read only access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.READ),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting budgets returns forbidden for users with write only access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.WRITE),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting budgets returns forbidden for users with manage access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
}
|
||||
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `deleting budgets returns success for users with owner access`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val permissions = setOf(
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.OWNER),
|
||||
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||
)
|
||||
permissions.forEach {
|
||||
permissionRepository.save(it)
|
||||
}
|
||||
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
header("Content-Type", "application/json")
|
||||
}
|
||||
assertEquals(HttpStatusCode.NoContent, response.status)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
package com.wbrawner.twigs.server.api
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.randomString
|
||||
import com.wbrawner.twigs.service.ErrorResponse
|
||||
import com.wbrawner.twigs.service.user.PasswordResetRequest
|
||||
import com.wbrawner.twigs.service.user.ResetPasswordRequest
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.TEST_USER
|
||||
import io.ktor.client.call.*
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.http.*
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.Instant
|
||||
import java.util.*
|
||||
|
||||
class PasswordResetRouteTest : ApiTest() {
|
||||
@Test
|
||||
fun `reset password with invalid username returns 202`() = apiTest { client ->
|
||||
val request = ResetPasswordRequest(username = "invaliduser")
|
||||
val response = client.post("/api/users/resetpassword") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Accepted, response.status)
|
||||
assert(emailService.emails.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `reset password with valid username returns 202`() = apiTest { client ->
|
||||
val request = ResetPasswordRequest(username = "testuser")
|
||||
val response = client.post("/api/users/resetpassword") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Accepted, response.status)
|
||||
assertEquals(1, emailService.emails.size)
|
||||
val email = emailService.emails.first()
|
||||
assertEquals(TEST_USER.email, email.to)
|
||||
assertEquals(1, passwordResetRepository.entities.size)
|
||||
val passwordReset = passwordResetRepository.entities.first()
|
||||
assertEquals(TEST_USER.id, passwordReset.userId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password reset with invalid token returns 401`() = apiTest { client ->
|
||||
val request = PasswordResetRequest(token = randomString(), password = "newpass")
|
||||
val response = client.put("/api/users/resetpassword") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val error = response.body<ErrorResponse>()
|
||||
assertEquals("Invalid token", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password reset with expired token returns 401`() = apiTest { client ->
|
||||
val token = passwordResetRepository.save(PasswordResetToken(expiration = twoWeeksAgo))
|
||||
val request = PasswordResetRequest(token = token.id, password = "newpass")
|
||||
val response = client.put("/api/users/resetpassword") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val error = response.body<ErrorResponse>()
|
||||
assertEquals("Token expired", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `password reset with valid token returns 204`() = apiTest { client ->
|
||||
val token =
|
||||
passwordResetRepository.save(PasswordResetToken(userId = userRepository.findAll("testuser").first().id))
|
||||
val request = PasswordResetRequest(token = token.id, password = "newpass")
|
||||
val response = client.put("/api/users/resetpassword") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.NoContent, response.status)
|
||||
assertEquals(
|
||||
"newpass",
|
||||
userRepository.findAll(TEST_USER.name).first().password
|
||||
)
|
||||
assert(passwordResetRepository.entities.isEmpty())
|
||||
}
|
||||
}
|
||||
|
||||
private val twoWeeksAgo: Instant
|
||||
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||
add(Calendar.DATE, -14)
|
||||
toInstant()
|
||||
}
|
|
@ -0,0 +1,249 @@
|
|||
package com.wbrawner.twigs.server.api
|
||||
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.User
|
||||
import com.wbrawner.twigs.service.ErrorResponse
|
||||
import com.wbrawner.twigs.service.user.*
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.OTHER_USER
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.TEST_USER
|
||||
import io.ktor.client.call.*
|
||||
import io.ktor.client.request.*
|
||||
import io.ktor.http.*
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertNotNull
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class UserRouteTest : ApiTest() {
|
||||
@Test
|
||||
fun `login with invalid username returns 401`() = apiTest { client ->
|
||||
val request = LoginRequest("invalid", "pass")
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("Invalid credentials", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login with empty username returns 401`() = apiTest { client ->
|
||||
val request = LoginRequest("", "pass")
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("Invalid credentials", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login with invalid password returns 401`() = apiTest { client ->
|
||||
val request = LoginRequest(TEST_USER.name, "pass")
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("Invalid credentials", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login with empty password returns 401`() = apiTest { client ->
|
||||
val request = LoginRequest(TEST_USER.name, "")
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("Invalid credentials", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login with valid username and password returns 200`() = apiTest { client ->
|
||||
val request = LoginRequest(TEST_USER.name, TEST_USER.password)
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val session = response.body<SessionResponse>()
|
||||
assertEquals(TEST_USER.id, session.userId)
|
||||
assert(session.token.isNotBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login with valid email and password returns 200`() = apiTest { client ->
|
||||
val request = LoginRequest(requireNotNull(TEST_USER.email), TEST_USER.password)
|
||||
val response = client.post("/api/users/login") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val session = response.body<SessionResponse>()
|
||||
assertEquals(TEST_USER.id, session.userId)
|
||||
assert(session.token.isNotBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with null username returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(password = "")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("username must not be null or blank", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with empty username returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(username = "", password = "")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("username must not be null or blank", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with null password returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(username = "test@example.com")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("password must not be null or blank", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with empty password returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(username = "test@example.com", password = "")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("password must not be null or blank", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with existing username returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(username = TEST_USER.name, password = "password")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("username or email already taken", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with existing email returns 400`() = apiTest { client ->
|
||||
val request = UserRequest(username = "testuser2", email = TEST_USER.email, password = "password")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val errorBody = response.body<ErrorResponse>()
|
||||
assertEquals("username or email already taken", errorBody.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register with valid username and password returns 200`() = apiTest { client ->
|
||||
val initialUserCount = userRepository.entities.size
|
||||
val request = UserRequest("newuser", "newpass")
|
||||
val response = client.post("/api/users/register") {
|
||||
header("Content-Type", "application/json")
|
||||
setBody(request)
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val userResponse = response.body<UserResponse>()
|
||||
assert(userResponse.id.isNotBlank())
|
||||
assertEquals(request.username, userResponse.username)
|
||||
assertEquals(null, userResponse.email)
|
||||
assertEquals(initialUserCount + 1, userRepository.entities.size)
|
||||
val savedUser: User? = userRepository.findAll("newuser").firstOrNull()
|
||||
assertNotNull(savedUser)
|
||||
requireNotNull(savedUser)
|
||||
assertEquals(userResponse.id, savedUser.id)
|
||||
assertEquals(request.username, savedUser.name)
|
||||
assertEquals(null, savedUser.email)
|
||||
assertEquals("newpass", savedUser.password)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `get users requires authentication`() = apiTest { client ->
|
||||
val response = client.get("/api/users")
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `get users with empty query returns 400`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val response = client.get("/api/users?query=") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
val error: ErrorResponse = response.body()
|
||||
assertEquals("query cannot be empty", error.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `get users with valid query but no matches returns empty list`() = apiTest { client ->
|
||||
val users = listOf(
|
||||
User(name = "testuser", password = "testpassword"),
|
||||
User(name = "otheruser", password = "otherpassword"),
|
||||
)
|
||||
users.forEach { userRepository.save(it) }
|
||||
val session = Session(userId = users.first().id)
|
||||
sessionRepository.save(session)
|
||||
val response = client.get("/api/users?query=something") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val userQueryResponse: List<UserResponse> = response.body()
|
||||
assertEquals(0, userQueryResponse.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `get users with valid query and matches returns list`() = apiTest { client ->
|
||||
val session = Session(userId = TEST_USER.id)
|
||||
sessionRepository.save(session)
|
||||
val response = client.get("/api/users?query=user") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val userQueryResponse: List<UserResponse> = response.body()
|
||||
assertEquals(2, userQueryResponse.size)
|
||||
assertEquals(TEST_USER.asResponse(), userQueryResponse[0])
|
||||
assertEquals(OTHER_USER.asResponse(), userQueryResponse[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `get users with empty budgetId returns 400`() = apiTest { client ->
|
||||
val session = Session(userId = TEST_USER.id)
|
||||
sessionRepository.save(session)
|
||||
val response = client.get("/api/users?budgetId=") {
|
||||
header("Authorization", "Bearer ${session.token}")
|
||||
}
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
}
|
||||
}
|
|
@ -15,8 +15,11 @@ buildscript {
|
|||
plugins {
|
||||
java
|
||||
alias(libs.plugins.kotlin.jvm)
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
}
|
||||
|
||||
val javaVersion = JavaVersion.VERSION_17
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
|
@ -27,7 +30,11 @@ allprojects {
|
|||
}
|
||||
group = "com.wbrawner"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
tasks.withType<JavaCompile> {
|
||||
sourceCompatibility = javaVersion.majorVersion
|
||||
targetCompatibility = javaVersion.majorVersion
|
||||
}
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions.jvmTarget = "16"
|
||||
kotlinOptions.jvmTarget = javaVersion.majorVersion
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,7 +6,6 @@ plugins {
|
|||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(libs.ktor.server.auth)
|
||||
api(libs.bcrypt)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import at.favre.lib.crypto.bcrypt.BCrypt
|
||||
import com.wbrawner.twigs.model.Frequency
|
||||
import java.time.Instant
|
||||
import java.time.format.DateTimeParseException
|
||||
import java.util.*
|
||||
|
||||
private val CALENDAR_FIELDS = intArrayOf(
|
||||
|
@ -51,9 +51,12 @@ fun randomString(length: Int = 32): String {
|
|||
return id.toString()
|
||||
}
|
||||
|
||||
lateinit var salt: String
|
||||
fun String.hash(): String = String(BCrypt.withDefaults().hash(10, salt.toByteArray(), this.toByteArray()))
|
||||
|
||||
fun String.toInstant(): Instant = Instant.parse(this)
|
||||
|
||||
fun String.toInstantOrNull(): Instant? = try {
|
||||
Instant.parse(this)
|
||||
} catch (e: DateTimeParseException) {
|
||||
null
|
||||
}
|
||||
|
||||
fun String.asFrequency(): Frequency = Frequency.parse(this)
|
||||
|
|
|
@ -6,9 +6,20 @@ import com.wbrawner.twigs.twoWeeksFromNow
|
|||
import io.ktor.server.auth.*
|
||||
import java.time.Instant
|
||||
|
||||
data class Session(
|
||||
open class Session(
|
||||
override val id: String = randomString(),
|
||||
val userId: String = "",
|
||||
val token: String = randomString(255),
|
||||
var expiration: Instant = twoWeeksFromNow
|
||||
) : Principal, Identifiable
|
||||
open val token: String = randomString(255),
|
||||
val expiration: Instant = twoWeeksFromNow
|
||||
) : Principal, Identifiable {
|
||||
fun updateExpiration(newExpiration: Instant) = Session(
|
||||
id = id,
|
||||
userId = userId,
|
||||
token = token,
|
||||
expiration = newExpiration
|
||||
)
|
||||
}
|
||||
|
||||
data class HeaderSession(override val token: String) : Session(token = token)
|
||||
|
||||
data class CookieSession(override val token: String) : Session(token = token)
|
|
@ -13,7 +13,7 @@ class JdbcPermissionRepository(dataSource: DataSource) :
|
|||
override val conflictFields: Collection<String> =
|
||||
listOf(Fields.USER_ID.name.lowercase(), Fields.BUDGET_ID.name.lowercase())
|
||||
|
||||
override fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> =
|
||||
override suspend fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> =
|
||||
dataSource.connection.use { conn ->
|
||||
if (budgetIds.isNullOrEmpty() && userId.isNullOrBlank()) {
|
||||
throw Error("budgetIds or userId must be provided")
|
||||
|
@ -32,6 +32,10 @@ class JdbcPermissionRepository(dataSource: DataSource) :
|
|||
conn.executeQuery(sql.toString(), params)
|
||||
}
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<UserPermission> {
|
||||
throw UnsupportedOperationException("UserPermission requires a userId and budgetId")
|
||||
}
|
||||
|
||||
override fun ResultSet.toEntity(): UserPermission = UserPermission(
|
||||
budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
|
||||
userId = getString(Fields.USER_ID.name.lowercase()),
|
||||
|
|
|
@ -1,16 +1,21 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.storage.Repository
|
||||
import java.sql.ResultSet
|
||||
import java.sql.SQLException
|
||||
import javax.sql.DataSource
|
||||
|
||||
class MetadataRepository(dataSource: DataSource) :
|
||||
JdbcRepository<DatabaseMetadata, MetadataRepository.Fields>(dataSource) {
|
||||
interface MetadataRepository : Repository<DatabaseMetadata> {
|
||||
fun runMigration(toVersion: Int)
|
||||
}
|
||||
|
||||
class JdbcMetadataRepository(dataSource: DataSource) :
|
||||
JdbcRepository<DatabaseMetadata, JdbcMetadataRepository.Fields>(dataSource), MetadataRepository {
|
||||
override val tableName: String = TABLE_METADATA
|
||||
override val fields: Map<Fields, (DatabaseMetadata) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf()
|
||||
|
||||
suspend fun runMigration(toVersion: Int) {
|
||||
override fun runMigration(toVersion: Int) {
|
||||
val queries = MetadataRepository::class.java
|
||||
.getResource("/sql/$toVersion.sql")
|
||||
?.readText()
|
||||
|
|
|
@ -9,11 +9,12 @@ services:
|
|||
- db
|
||||
environment:
|
||||
TWIGS_DB_HOST: db
|
||||
TWIGS_DB_TYPE: postgresql
|
||||
networks:
|
||||
- twigs
|
||||
|
||||
db:
|
||||
image: postgres:13
|
||||
image: postgres:17
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
[versions]
|
||||
bcrypt = "0.9.0"
|
||||
hikari = "5.0.1"
|
||||
junit = "5.8.2"
|
||||
kotlin = "1.6.21"
|
||||
kotlinx-coroutines = "1.6.2"
|
||||
ktor = "2.0.2"
|
||||
logback = "1.2.11"
|
||||
bcrypt = "0.10.2"
|
||||
hikari = "6.2.1"
|
||||
junit = "5.11.3"
|
||||
kotlin = "2.0.21"
|
||||
kotlinx-coroutines = "1.9.0"
|
||||
ktor = "2.3.13"
|
||||
logback = "1.5.12"
|
||||
mail = "1.6.2"
|
||||
postgres = "42.3.8"
|
||||
shadow = "7.0.0"
|
||||
sqlite = "3.42.0.0"
|
||||
postgres = "42.7.4"
|
||||
shadow = "8.1.1"
|
||||
sqlite = "3.47.0.0"
|
||||
|
||||
[libraries]
|
||||
bcrypt = { module = "at.favre.lib:bcrypt", version.ref = "bcrypt" }
|
||||
|
@ -18,8 +18,10 @@ junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.re
|
|||
junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine" }
|
||||
kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
|
||||
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
|
||||
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
|
||||
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
|
||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
|
||||
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
|
||||
ktor-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||||
ktor-server-auth = { module = "io.ktor:ktor-server-auth", version.ref = "ktor" }
|
||||
ktor-server-call-logging = { module = "io.ktor:ktor-server-call-logging", version.ref = "ktor" }
|
||||
|
@ -27,7 +29,10 @@ ktor-server-cio = { module = "io.ktor:ktor-server-cio", version.ref = "ktor" }
|
|||
ktor-server-content-negotiation = { module = "io.ktor:ktor-server-content-negotiation", version.ref = "ktor" }
|
||||
ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor" }
|
||||
ktor-server-cors = { module = "io.ktor:ktor-server-cors", version.ref = "ktor" }
|
||||
ktor-server-forwarded-headers = { module = "io.ktor:ktor-server-forwarded-header", version.ref = "ktor" }
|
||||
ktor-server-mustache = { module = "io.ktor:ktor-server-mustache", version.ref = "ktor" }
|
||||
ktor-server-sessions = { module = "io.ktor:ktor-server-sessions", version.ref = "ktor" }
|
||||
ktor-server-test = { module = "io.ktor:ktor-server-test-host", version.ref = "ktor" }
|
||||
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
|
||||
mail = { module = "com.sun.mail:javax.mail", version.ref = "mail" }
|
||||
postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" }
|
||||
|
@ -40,6 +45,7 @@ ktor-server = [
|
|||
"ktor-server-content-negotiation",
|
||||
"ktor-server-core",
|
||||
"ktor-server-cors",
|
||||
"ktor-server-forwarded-headers",
|
||||
"ktor-server-sessions"
|
||||
]
|
||||
|
||||
|
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
7
gradle/wrapper/gradle-wrapper.properties
vendored
|
@ -1,6 +1,7 @@
|
|||
#Fri Feb 07 18:11:46 CST 2020
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-all.zip
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
|
297
gradlew
vendored
|
@ -1,7 +1,7 @@
|
|||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
|
@ -15,80 +15,116 @@
|
|||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
@ -97,87 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the
|
|||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
|
60
gradlew.bat
vendored
|
@ -13,8 +13,10 @@
|
|||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
|
@ -25,10 +27,14 @@
|
|||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
|
@ -37,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
|
|||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto init
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
|
@ -51,48 +57,36 @@ goto fail
|
|||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto init
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:init
|
||||
@rem Get command-line arguments, handling Windows variants
|
||||
|
||||
if not "%OS%" == "Windows_NT" goto win9xME_args
|
||||
|
||||
:win9xME_args
|
||||
@rem Slurp the command line arguments.
|
||||
set CMD_LINE_ARGS=
|
||||
set _SKIP=2
|
||||
|
||||
:win9xME_args_slurp
|
||||
if "x%~1" == "x" goto execute
|
||||
|
||||
set CMD_LINE_ARGS=%*
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
|
3
renovate.json
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
|
||||
}
|
1
service/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
build/
|
19
service/build.gradle.kts
Normal file
|
@ -0,0 +1,19 @@
|
|||
plugins {
|
||||
`java-library`
|
||||
alias(libs.plugins.kotlin.jvm)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(libs.ktor.server.core)
|
||||
implementation(project(":storage"))
|
||||
api(libs.ktor.serialization)
|
||||
api(libs.kotlinx.coroutines.core)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
59
service/src/main/java/com/wbrawner/twigs/service/ApiUtils.kt
Normal file
|
@ -0,0 +1,59 @@
|
|||
package com.wbrawner.twigs.service
|
||||
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.util.pipeline.*
|
||||
|
||||
suspend fun PermissionRepository.requirePermission(
|
||||
userId: String,
|
||||
budgetIds: List<String>,
|
||||
permission: Permission
|
||||
): List<UserPermission> {
|
||||
val uniqueBudgetIds = budgetIds.toSet()
|
||||
val allPermissions = findAll(budgetIds = uniqueBudgetIds.toList(), userId = userId)
|
||||
if (allPermissions.size != uniqueBudgetIds.size) {
|
||||
throw HttpException(HttpStatusCode.NotFound)
|
||||
} else if (allPermissions.any { !it.permission.isAtLeast(permission) }) {
|
||||
throw HttpException(HttpStatusCode.Forbidden)
|
||||
}
|
||||
return allPermissions
|
||||
}
|
||||
|
||||
suspend fun PermissionRepository.requirePermission(
|
||||
userId: String,
|
||||
budgetId: String,
|
||||
permission: Permission
|
||||
): List<UserPermission> = requirePermission(userId, listOf(budgetId), permission)
|
||||
|
||||
suspend fun Pair<BudgetRepository, PermissionRepository>.budgetWithPermission(
|
||||
userId: String,
|
||||
budgetId: String,
|
||||
permission: Permission
|
||||
): BudgetResponse {
|
||||
val budget = first.findAll(ids = listOf(budgetId)).firstOrNull() ?: throw HttpException(HttpStatusCode.NotFound)
|
||||
return BudgetResponse(budget, second.requirePermission(userId, budgetId, permission))
|
||||
}
|
||||
|
||||
fun PipelineContext<Unit, ApplicationCall>.requireSession() = requireNotNull(call.principal<Session>()) {
|
||||
"Session required but was null"
|
||||
}
|
||||
|
||||
suspend inline fun <reified T : Any> ApplicationCall.respondCatching(block: () -> T) =
|
||||
try {
|
||||
val response = block()
|
||||
if (response is HttpStatusCode) {
|
||||
respond(status = response, message = Unit)
|
||||
} else {
|
||||
respond(HttpStatusCode.OK, response)
|
||||
}
|
||||
} catch (e: HttpException) {
|
||||
respond(e.statusCode, e.toResponse())
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.wbrawner.twigs.service
|
||||
|
||||
import io.ktor.http.*
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ErrorResponse(val message: String)
|
||||
|
||||
class HttpException(
|
||||
val statusCode: HttpStatusCode,
|
||||
override val cause: Throwable? = null,
|
||||
override val message: String? = null
|
||||
) : Throwable() {
|
||||
constructor(statusCode: HttpStatusCode) : this(statusCode = statusCode, message = statusCode.description)
|
||||
|
||||
fun toResponse(): ErrorResponse =
|
||||
ErrorResponse(requireNotNull(message) { "Cannot send error to client without message" })
|
||||
}
|
|
@ -1,9 +1,10 @@
|
|||
package com.wbrawner.twigs
|
||||
package com.wbrawner.twigs.service.budget
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.service.user.UserPermissionRequest
|
||||
import com.wbrawner.twigs.service.user.UserPermissionResponse
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.util.*
|
||||
|
||||
@Serializable
|
||||
data class BudgetRequest(
|
||||
|
@ -15,12 +16,12 @@ data class BudgetRequest(
|
|||
@Serializable
|
||||
data class BudgetResponse(
|
||||
val id: String,
|
||||
val name: String?,
|
||||
val description: String?,
|
||||
private val users: List<UserPermissionResponse>
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val users: List<UserPermissionResponse>
|
||||
) {
|
||||
constructor(budget: Budget, users: Iterable<UserPermission>) : this(
|
||||
Objects.requireNonNull<String>(budget.id),
|
||||
requireNotNull(budget.id),
|
||||
budget.name,
|
||||
budget.description,
|
||||
users.map { userPermission: UserPermission ->
|
|
@ -0,0 +1,130 @@
|
|||
package com.wbrawner.twigs.service.budget
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.budgetWithPermission
|
||||
import com.wbrawner.twigs.service.user.UserPermissionRequest
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import io.ktor.http.*
|
||||
|
||||
interface BudgetService {
|
||||
suspend fun budgetsForUser(userId: String): List<BudgetResponse>
|
||||
|
||||
suspend fun budget(budgetId: String, userId: String): BudgetResponse
|
||||
|
||||
suspend fun save(request: BudgetRequest, userId: String, budgetId: String? = null): BudgetResponse
|
||||
|
||||
suspend fun delete(budgetId: String, userId: String)
|
||||
}
|
||||
|
||||
class DefaultBudgetService(
|
||||
private val budgetRepository: BudgetRepository,
|
||||
private val permissionRepository: PermissionRepository
|
||||
) : BudgetService {
|
||||
private val budgetPermissionRepository = budgetRepository to permissionRepository
|
||||
override suspend fun budgetsForUser(userId: String): List<BudgetResponse> {
|
||||
val budgetIds = permissionRepository.findAll(userId = userId).map { it.budgetId }
|
||||
if (budgetIds.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
return budgetRepository.findAll(ids = budgetIds).map {
|
||||
BudgetResponse(it, permissionRepository.findAll(budgetIds = listOf(it.id)))
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun budget(budgetId: String, userId: String): BudgetResponse =
|
||||
budgetPermissionRepository.budgetWithPermission(userId, budgetId, Permission.READ)
|
||||
|
||||
override suspend fun save(request: BudgetRequest, userId: String, budgetId: String?): BudgetResponse {
|
||||
val budget = if (budgetId?.isNotBlank() == true) {
|
||||
budgetPermissionRepository.budgetWithPermission(
|
||||
budgetId = budgetId,
|
||||
userId = userId,
|
||||
permission = Permission.MANAGE
|
||||
).run {
|
||||
Budget(
|
||||
id = budgetId,
|
||||
name = request.name ?: name,
|
||||
description = request.description ?: description
|
||||
)
|
||||
}
|
||||
} else {
|
||||
if (request.name.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "Name cannot be empty or null")
|
||||
}
|
||||
Budget(
|
||||
name = request.name,
|
||||
description = request.description
|
||||
)
|
||||
}
|
||||
val users = budgetId?.let {
|
||||
// If user is owner, apply changes
|
||||
// If user is manager, make sure they're not changing ownership
|
||||
val oldUsers = permissionRepository.findAll(budgetIds = listOf(budgetId))
|
||||
val oldPermissions = oldUsers.associate { it.userId to it.permission }
|
||||
val currentUserPermission = oldPermissions[userId] ?: throw HttpException(HttpStatusCode.NotFound)
|
||||
val newUsers = request.users?.map { userPermission ->
|
||||
if (userPermission.permission == Permission.OWNER
|
||||
&& oldPermissions[userPermission.user] !== Permission.OWNER
|
||||
&& currentUserPermission != Permission.OWNER
|
||||
) {
|
||||
// The user is attempting to add a new owner
|
||||
throw HttpException(
|
||||
HttpStatusCode.Forbidden,
|
||||
message = "You must be an owner to be able to modify other users' ownership"
|
||||
)
|
||||
}
|
||||
userPermission
|
||||
} ?: return@let oldUsers.map { UserPermissionRequest(it.userId, it.permission) }
|
||||
oldPermissions.filterValues { it == Permission.OWNER }
|
||||
.forEach { (user, permission) ->
|
||||
if (newUsers.none { it.user == user && it.permission == permission }
|
||||
&& currentUserPermission != Permission.OWNER
|
||||
) {
|
||||
// The user is attempting to remove a previous owner
|
||||
throw HttpException(
|
||||
HttpStatusCode.Forbidden,
|
||||
message = "You must be an owner to be able to modify other users' ownership"
|
||||
)
|
||||
}
|
||||
}
|
||||
oldUsers.forEach { oldUserPermission ->
|
||||
if (newUsers.none { it.user == oldUserPermission.userId && it.permission == oldUserPermission.permission }) {
|
||||
permissionRepository.delete(oldUserPermission)
|
||||
}
|
||||
}
|
||||
newUsers
|
||||
} ?: run {
|
||||
val newUsers = request.users
|
||||
?.toMutableList()
|
||||
?: mutableListOf()
|
||||
val currentUserPermission = newUsers.firstOrNull { it.user == userId }
|
||||
if (currentUserPermission == null || currentUserPermission.permission != Permission.OWNER) {
|
||||
newUsers.removeIf { it.user == userId }
|
||||
newUsers.add(UserPermissionRequest(userId, Permission.OWNER))
|
||||
}
|
||||
newUsers
|
||||
}
|
||||
val savedBudget = budgetRepository.save(budget)
|
||||
return BudgetResponse(
|
||||
savedBudget,
|
||||
users.map {
|
||||
permissionRepository.save(
|
||||
UserPermission(
|
||||
budgetId = savedBudget.id,
|
||||
userId = it.user,
|
||||
permission = it.permission
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun delete(budgetId: String, userId: String) {
|
||||
val budgetResponse = budgetPermissionRepository.budgetWithPermission(userId, budgetId, Permission.OWNER)
|
||||
budgetRepository.delete(Budget(budgetResponse.id, budgetResponse.name, budgetResponse.description))
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.wbrawner.twigs
|
||||
package com.wbrawner.twigs.service.category
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import kotlinx.serialization.Serializable
|
|
@ -0,0 +1,104 @@
|
|||
package com.wbrawner.twigs.service.category
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.requirePermission
|
||||
import com.wbrawner.twigs.storage.CategoryRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import io.ktor.http.*
|
||||
|
||||
interface CategoryService {
|
||||
suspend fun categories(
|
||||
budgetIds: List<String>,
|
||||
userId: String,
|
||||
expense: Boolean? = null,
|
||||
archived: Boolean? = null,
|
||||
): List<CategoryResponse>
|
||||
|
||||
suspend fun category(categoryId: String, userId: String): CategoryResponse
|
||||
|
||||
suspend fun save(request: CategoryRequest, userId: String, categoryId: String? = null): CategoryResponse
|
||||
|
||||
suspend fun delete(categoryId: String, userId: String)
|
||||
}
|
||||
|
||||
class DefaultCategoryService(
|
||||
private val categoryRepository: CategoryRepository,
|
||||
private val permissionRepository: PermissionRepository
|
||||
) : CategoryService {
|
||||
|
||||
override suspend fun categories(
|
||||
budgetIds: List<String>,
|
||||
userId: String,
|
||||
expense: Boolean?,
|
||||
archived: Boolean?,
|
||||
): List<CategoryResponse> {
|
||||
val validBudgetIds = permissionRepository.findAll(
|
||||
budgetIds = budgetIds,
|
||||
userId = userId
|
||||
).map { it.budgetId }
|
||||
if (validBudgetIds.isEmpty()) {
|
||||
return emptyList()
|
||||
}
|
||||
return categoryRepository.findAll(
|
||||
budgetIds = budgetIds,
|
||||
expense = expense,
|
||||
archived = archived
|
||||
).map { it.asResponse() }
|
||||
}
|
||||
|
||||
override suspend fun category(categoryId: String, userId: String): CategoryResponse {
|
||||
val budgetIds = permissionRepository.findAll(userId = userId).map { it.budgetId }
|
||||
if (budgetIds.isEmpty()) {
|
||||
throw HttpException(HttpStatusCode.NotFound)
|
||||
}
|
||||
return categoryRepository.findAll(
|
||||
ids = listOf(categoryId),
|
||||
budgetIds = budgetIds
|
||||
)
|
||||
.map { it.asResponse() }
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
}
|
||||
|
||||
override suspend fun save(request: CategoryRequest, userId: String, categoryId: String?): CategoryResponse {
|
||||
val category = categoryId?.let {
|
||||
categoryRepository.findAll(ids = listOf(categoryId)).firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
} ?: run {
|
||||
if (request.title.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
|
||||
}
|
||||
Category(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId
|
||||
)
|
||||
}
|
||||
permissionRepository.requirePermission(userId, category.budgetId, Permission.WRITE)
|
||||
return categoryRepository.save(
|
||||
category.copy(
|
||||
title = request.title?.ifBlank { category.title } ?: category.title,
|
||||
description = request.description ?: category.description,
|
||||
amount = request.amount ?: category.amount,
|
||||
expense = request.expense ?: category.expense,
|
||||
archived = request.archived ?: category.archived,
|
||||
budgetId = request.budgetId?.ifBlank { category.budgetId } ?: category.budgetId
|
||||
)
|
||||
).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun delete(categoryId: String, userId: String) {
|
||||
val category = categoryRepository.findAll(ids = listOf(categoryId))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(userId, category.budgetId, Permission.WRITE)
|
||||
categoryRepository.delete(category)
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.wbrawner.twigs
|
||||
package com.wbrawner.twigs.service.recurringtransaction
|
||||
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import kotlinx.serialization.Serializable
|
|
@ -0,0 +1,110 @@
|
|||
package com.wbrawner.twigs.service.recurringtransaction
|
||||
|
||||
import com.wbrawner.twigs.asFrequency
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.requirePermission
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import com.wbrawner.twigs.toInstant
|
||||
import io.ktor.http.*
|
||||
import java.time.Instant
|
||||
|
||||
interface RecurringTransactionService {
|
||||
suspend fun recurringTransactions(
|
||||
budgetId: String,
|
||||
userId: String,
|
||||
): List<RecurringTransactionResponse>
|
||||
|
||||
suspend fun recurringTransaction(recurringTransactionId: String, userId: String): RecurringTransactionResponse
|
||||
|
||||
suspend fun save(
|
||||
request: RecurringTransactionRequest,
|
||||
userId: String,
|
||||
recurringTransactionId: String? = null
|
||||
): RecurringTransactionResponse
|
||||
|
||||
suspend fun delete(recurringTransactionId: String, userId: String)
|
||||
}
|
||||
|
||||
class DefaultRecurringTransactionService(
|
||||
private val recurringTransactionRepository: RecurringTransactionRepository,
|
||||
private val permissionRepository: PermissionRepository
|
||||
) : RecurringTransactionService {
|
||||
override suspend fun recurringTransactions(
|
||||
budgetId: String,
|
||||
userId: String
|
||||
): List<RecurringTransactionResponse> {
|
||||
permissionRepository.requirePermission(userId, budgetId, Permission.READ)
|
||||
return recurringTransactionRepository.findAll(budgetId = budgetId)
|
||||
.map { it.asResponse() }
|
||||
}
|
||||
|
||||
override suspend fun recurringTransaction(
|
||||
recurringTransactionId: String,
|
||||
userId: String
|
||||
): RecurringTransactionResponse {
|
||||
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(recurringTransactionId))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.READ)
|
||||
return recurringTransaction.asResponse()
|
||||
}
|
||||
|
||||
override suspend fun save(
|
||||
request: RecurringTransactionRequest,
|
||||
userId: String,
|
||||
recurringTransactionId: String?
|
||||
): RecurringTransactionResponse {
|
||||
val recurringTransaction = recurringTransactionId?.let {
|
||||
recurringTransactionRepository.findAll(ids = listOf(it))
|
||||
.firstOrNull()
|
||||
?.also { recurringTransaction ->
|
||||
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
|
||||
}
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
} ?: run {
|
||||
if (request.title.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
|
||||
}
|
||||
RecurringTransaction(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId,
|
||||
categoryId = request.categoryId,
|
||||
createdBy = userId,
|
||||
start = request.start?.toInstant() ?: Instant.now(),
|
||||
finish = request.finish?.toInstant(),
|
||||
frequency = request.frequency.asFrequency()
|
||||
)
|
||||
}
|
||||
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
|
||||
return recurringTransactionRepository.save(
|
||||
recurringTransaction.copy(
|
||||
title = request.title?.ifBlank { recurringTransaction.title } ?: recurringTransaction.title,
|
||||
description = request.description ?: recurringTransaction.description,
|
||||
amount = request.amount ?: recurringTransaction.amount,
|
||||
expense = request.expense ?: recurringTransaction.expense,
|
||||
budgetId = request.budgetId?.ifBlank { recurringTransaction.budgetId } ?: recurringTransaction.budgetId,
|
||||
categoryId = request.categoryId ?: recurringTransaction.categoryId,
|
||||
start = request.start?.toInstant() ?: recurringTransaction.start,
|
||||
finish = request.finish?.toInstant() ?: recurringTransaction.finish,
|
||||
frequency = request.frequency.asFrequency()
|
||||
)
|
||||
).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun delete(recurringTransactionId: String, userId: String) {
|
||||
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(recurringTransactionId))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
|
||||
recurringTransactionRepository.delete(recurringTransaction)
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.wbrawner.twigs
|
||||
package com.wbrawner.twigs.service.transaction
|
||||
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import kotlinx.serialization.Serializable
|
|
@ -0,0 +1,167 @@
|
|||
package com.wbrawner.twigs.service.transaction
|
||||
|
||||
import com.wbrawner.twigs.endOfMonth
|
||||
import com.wbrawner.twigs.firstOfMonth
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.requirePermission
|
||||
import com.wbrawner.twigs.storage.CategoryRepository
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import com.wbrawner.twigs.storage.TransactionRepository
|
||||
import com.wbrawner.twigs.toInstant
|
||||
import com.wbrawner.twigs.toInstantOrNull
|
||||
import io.ktor.http.*
|
||||
import java.time.Instant
|
||||
|
||||
interface TransactionService {
|
||||
suspend fun transactions(
|
||||
budgetIds: List<String>,
|
||||
categoryIds: List<String>? = null,
|
||||
from: Instant? = null,
|
||||
to: Instant? = null,
|
||||
expense: Boolean? = null,
|
||||
userId: String,
|
||||
): List<TransactionResponse>
|
||||
|
||||
suspend fun transaction(transactionId: String, userId: String): TransactionResponse
|
||||
|
||||
suspend fun sum(
|
||||
userId: String,
|
||||
budgetId: String? = null,
|
||||
categoryId: String? = null,
|
||||
from: Instant? = null,
|
||||
to: Instant? = null,
|
||||
): Long
|
||||
|
||||
suspend fun save(
|
||||
request: TransactionRequest,
|
||||
userId: String,
|
||||
transactionId: String? = null
|
||||
): TransactionResponse
|
||||
|
||||
suspend fun delete(transactionId: String, userId: String)
|
||||
}
|
||||
|
||||
class DefaultTransactionService(
|
||||
private val transactionRepository: TransactionRepository,
|
||||
private val categoryRepository: CategoryRepository,
|
||||
private val permissionRepository: PermissionRepository
|
||||
) : TransactionService {
|
||||
override suspend fun transactions(
|
||||
budgetIds: List<String>,
|
||||
categoryIds: List<String>?,
|
||||
from: Instant?,
|
||||
to: Instant?,
|
||||
expense: Boolean?,
|
||||
userId: String
|
||||
): List<TransactionResponse> {
|
||||
permissionRepository.requirePermission(userId, budgetIds, Permission.READ)
|
||||
return transactionRepository.findAll(
|
||||
budgetIds = budgetIds,
|
||||
categoryIds = categoryIds,
|
||||
from = from,
|
||||
to = to,
|
||||
expense = expense
|
||||
).map { it.asResponse() }
|
||||
}
|
||||
|
||||
override suspend fun transaction(
|
||||
transactionId: String,
|
||||
userId: String
|
||||
): TransactionResponse {
|
||||
val transaction = transactionRepository.findAll(ids = listOf(transactionId))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.READ)
|
||||
return transaction.asResponse()
|
||||
}
|
||||
|
||||
override suspend fun sum(
|
||||
userId: String,
|
||||
budgetId: String?,
|
||||
categoryId: String?,
|
||||
from: Instant?,
|
||||
to: Instant?
|
||||
): Long {
|
||||
if (budgetId.isNullOrBlank() && categoryId.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId or categoryId must be provided to sum")
|
||||
}
|
||||
if (budgetId?.isNotBlank() == true && categoryId?.isNotBlank() == true) {
|
||||
throw HttpException(
|
||||
HttpStatusCode.BadRequest,
|
||||
message = "budgetId and categoryId cannot be provided together"
|
||||
)
|
||||
}
|
||||
return if (!categoryId.isNullOrBlank()) {
|
||||
val category = categoryRepository.findAll(ids = listOf(categoryId)).firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(
|
||||
userId = userId,
|
||||
budgetId = category.budgetId,
|
||||
permission = Permission.READ
|
||||
)
|
||||
transactionRepository.sumByCategory(category.id, from ?: firstOfMonth, to ?: endOfMonth)
|
||||
} else if (!budgetId.isNullOrBlank()) {
|
||||
permissionRepository.requirePermission(userId = userId, budgetId = budgetId, permission = Permission.READ)
|
||||
transactionRepository.sumByBudget(budgetId, from ?: firstOfMonth, to ?: endOfMonth)
|
||||
} else {
|
||||
error("Somehow we didn't return either a budget or category sum")
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun save(
|
||||
request: TransactionRequest,
|
||||
userId: String,
|
||||
transactionId: String?
|
||||
): TransactionResponse {
|
||||
val transaction = transactionId?.let {
|
||||
transactionRepository.findAll(ids = listOf(it))
|
||||
.firstOrNull()
|
||||
?.also { transaction ->
|
||||
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.WRITE)
|
||||
}
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
} ?: run {
|
||||
if (request.title.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
|
||||
}
|
||||
if (request.budgetId.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
|
||||
}
|
||||
if (request.date?.toInstantOrNull() == null) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "invalid date")
|
||||
}
|
||||
Transaction(
|
||||
title = request.title,
|
||||
description = request.description,
|
||||
amount = request.amount ?: 0L,
|
||||
expense = request.expense ?: true,
|
||||
budgetId = request.budgetId,
|
||||
categoryId = request.categoryId,
|
||||
date = request.date.toInstant(),
|
||||
createdBy = userId,
|
||||
)
|
||||
}
|
||||
permissionRepository.requirePermission(userId, request.budgetId ?: transaction.budgetId, Permission.WRITE)
|
||||
return transactionRepository.save(
|
||||
transaction.copy(
|
||||
title = request.title?.ifBlank { transaction.title } ?: transaction.title,
|
||||
description = request.description ?: transaction.description,
|
||||
amount = request.amount ?: transaction.amount,
|
||||
expense = request.expense ?: transaction.expense,
|
||||
budgetId = request.budgetId?.ifBlank { transaction.budgetId } ?: transaction.budgetId,
|
||||
categoryId = request.categoryId ?: transaction.categoryId,
|
||||
date = request.date?.toInstantOrNull() ?: transaction.date
|
||||
)
|
||||
).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun delete(transactionId: String, userId: String) {
|
||||
val transaction = transactionRepository.findAll(ids = listOf(transactionId))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.WRITE)
|
||||
transactionRepository.delete(transaction)
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.wbrawner.twigs
|
||||
package com.wbrawner.twigs.service.user
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.model.Permission
|
|
@ -0,0 +1,178 @@
|
|||
package com.wbrawner.twigs.service.user
|
||||
|
||||
import com.wbrawner.twigs.EmailService
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.User
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.storage.*
|
||||
import io.ktor.http.*
|
||||
import java.time.Instant
|
||||
|
||||
interface UserService {
|
||||
|
||||
suspend fun login(request: LoginRequest): SessionResponse
|
||||
|
||||
suspend fun register(request: UserRequest): UserResponse
|
||||
|
||||
suspend fun requestPasswordResetEmail(request: ResetPasswordRequest)
|
||||
|
||||
suspend fun resetPassword(request: PasswordResetRequest)
|
||||
suspend fun users(query: String?, budgetIds: List<String>?, requestingUserId: String): List<UserResponse>
|
||||
|
||||
suspend fun user(userId: String): UserResponse
|
||||
|
||||
suspend fun session(token: String): SessionResponse
|
||||
|
||||
suspend fun save(request: UserRequest, targetUserId: String, requestingUserId: String): UserResponse
|
||||
|
||||
suspend fun delete(targetUserId: String, requestingUserId: String)
|
||||
}
|
||||
|
||||
class DefaultUserService(
|
||||
private val emailService: EmailService,
|
||||
private val passwordResetRepository: PasswordResetRepository,
|
||||
private val permissionRepository: PermissionRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
private val userRepository: UserRepository,
|
||||
private val passwordHasher: PasswordHasher
|
||||
) : UserService {
|
||||
|
||||
override suspend fun login(request: LoginRequest): SessionResponse {
|
||||
val user = userRepository.findAll(
|
||||
nameOrEmail = request.username,
|
||||
password = passwordHasher.hash(request.password)
|
||||
)
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.Unauthorized, message = "Invalid credentials")
|
||||
return sessionRepository.save(Session(userId = user.id)).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun register(request: UserRequest): UserResponse {
|
||||
if (request.username.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "username must not be null or blank")
|
||||
}
|
||||
if (request.password.isNullOrBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "password must not be null or blank")
|
||||
}
|
||||
val existingUser = userRepository.findAll(nameOrEmail = request.username).firstOrNull()
|
||||
?: request.email?.let {
|
||||
if (it.isBlank()) {
|
||||
null
|
||||
} else {
|
||||
userRepository.findAll(nameOrEmail = it).firstOrNull()
|
||||
}
|
||||
}
|
||||
existingUser?.let {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "username or email already taken")
|
||||
}
|
||||
return userRepository.save(
|
||||
User(
|
||||
name = request.username,
|
||||
password = passwordHasher.hash(request.password),
|
||||
email = if (request.email.isNullOrBlank()) null else request.email
|
||||
)
|
||||
).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun requestPasswordResetEmail(request: ResetPasswordRequest) {
|
||||
userRepository.findAll(nameOrEmail = request.username)
|
||||
.firstOrNull()
|
||||
?.let {
|
||||
val email = it.email ?: return@let
|
||||
val passwordResetToken = passwordResetRepository.save(PasswordResetToken(userId = it.id))
|
||||
emailService.sendPasswordResetEmail(passwordResetToken, email)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetPassword(request: PasswordResetRequest) {
|
||||
val passwordResetToken = passwordResetRepository.findAll(listOf(request.token))
|
||||
.firstOrNull()
|
||||
?: throw HttpException(HttpStatusCode.Unauthorized, message = "Invalid token")
|
||||
if (passwordResetToken.expiration.isBefore(Instant.now())) {
|
||||
throw HttpException(HttpStatusCode.Unauthorized, message = "Token expired")
|
||||
}
|
||||
if (request.password.isBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "password cannot be empty")
|
||||
}
|
||||
userRepository.findAll(listOf(passwordResetToken.userId))
|
||||
.firstOrNull()
|
||||
?.let {
|
||||
userRepository.save(it.copy(password = passwordHasher.hash(request.password)))
|
||||
passwordResetRepository.delete(passwordResetToken)
|
||||
}
|
||||
?: throw HttpException(HttpStatusCode.InternalServerError, message = "Invalid token")
|
||||
}
|
||||
|
||||
override suspend fun users(
|
||||
query: String?,
|
||||
budgetIds: List<String>?,
|
||||
requestingUserId: String
|
||||
): List<UserResponse> {
|
||||
if (query != null) {
|
||||
if (query.isBlank()) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "query cannot be empty")
|
||||
}
|
||||
return userRepository.findAll(nameLike = query).map { it.asResponse() }
|
||||
} else if (budgetIds == null || budgetIds.all { it.isBlank() }) {
|
||||
throw HttpException(HttpStatusCode.BadRequest, message = "query or budgetId required but absent")
|
||||
}
|
||||
return permissionRepository.findAll(budgetIds = budgetIds, userId = requestingUserId)
|
||||
.mapNotNull {
|
||||
userRepository.findAll(ids = listOf(it.userId))
|
||||
.firstOrNull()
|
||||
?.asResponse()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun user(
|
||||
userId: String
|
||||
): UserResponse {
|
||||
return userRepository.findAll(ids = listOf(userId))
|
||||
.firstOrNull()
|
||||
?.asResponse()
|
||||
?: throw HttpException(HttpStatusCode.NotFound)
|
||||
}
|
||||
|
||||
override suspend fun session(token: String): SessionResponse {
|
||||
return sessionRepository.findAll(token = token)
|
||||
.firstOrNull()
|
||||
?.asResponse()
|
||||
?: throw HttpException(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
|
||||
override suspend fun save(
|
||||
request: UserRequest,
|
||||
targetUserId: String,
|
||||
requestingUserId: String,
|
||||
): UserResponse {
|
||||
// TODO: Add some kind of admin denotation to allow admins to edit other users
|
||||
if (targetUserId != requestingUserId) {
|
||||
throw HttpException(HttpStatusCode.Forbidden)
|
||||
}
|
||||
return userRepository.save(
|
||||
userRepository.findAll(ids = listOf(targetUserId))
|
||||
.first()
|
||||
.run {
|
||||
val newPassword = if (request.password.isNullOrBlank()) {
|
||||
password
|
||||
} else {
|
||||
passwordHasher.hash(request.password)
|
||||
}
|
||||
copy(
|
||||
name = request.username ?: name,
|
||||
password = newPassword,
|
||||
email = request.email ?: email
|
||||
)
|
||||
}
|
||||
).asResponse()
|
||||
}
|
||||
|
||||
override suspend fun delete(targetUserId: String, requestingUserId: String) {
|
||||
// TODO: Add some kind of admin denotation to allow admins to delete other users
|
||||
if (targetUserId != requestingUserId) {
|
||||
throw HttpException(HttpStatusCode.Forbidden)
|
||||
}
|
||||
userRepository.delete(userRepository.findAll(targetUserId).first())
|
||||
}
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
rootProject.name = "twigs"
|
||||
include("core", "api", "app", "storage", "db", "web")
|
||||
include("testhelpers")
|
||||
include("service")
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.wbrawner.twigs.storage
|
|||
import com.wbrawner.twigs.model.UserPermission
|
||||
|
||||
interface PermissionRepository : Repository<UserPermission> {
|
||||
fun findAll(
|
||||
suspend fun findAll(
|
||||
budgetIds: List<String>? = null,
|
||||
userId: String? = null
|
||||
): List<UserPermission>
|
||||
|
|
|
@ -10,3 +10,7 @@ interface UserRepository : Repository<User> {
|
|||
|
||||
fun findAll(nameLike: String): List<User>
|
||||
}
|
||||
|
||||
fun interface PasswordHasher {
|
||||
fun hash(password: String): String
|
||||
}
|
|
@ -8,5 +8,12 @@ dependencies {
|
|||
implementation(project(":storage"))
|
||||
api(libs.kotlinx.coroutines.test)
|
||||
api(libs.junit.jupiter.api)
|
||||
implementation(project(mapOf("path" to ":db")))
|
||||
runtimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
||||
tasks {
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.wbrawner.twigs.test.helpers
|
||||
|
||||
import com.wbrawner.twigs.EmailService
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
|
||||
class FakeEmailService : EmailService {
|
||||
val emails = mutableListOf<FakeEmail<*>>()
|
||||
|
||||
override fun sendPasswordResetEmail(token: PasswordResetToken, to: String) {
|
||||
emails.add(FakeEmail(to, token))
|
||||
}
|
||||
}
|
||||
|
||||
data class FakeEmail<Data>(val to: String, val data: Data)
|
|
@ -0,0 +1,6 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
|
||||
class FakeBudgetRepository : FakeRepository<Budget>(), BudgetRepository
|
|
@ -0,0 +1,18 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import com.wbrawner.twigs.storage.CategoryRepository
|
||||
|
||||
class FakeCategoryRepository : FakeRepository<Category>(), CategoryRepository {
|
||||
override fun findAll(
|
||||
budgetIds: List<String>,
|
||||
ids: List<String>?,
|
||||
expense: Boolean?,
|
||||
archived: Boolean?
|
||||
): List<Category> = entities.filter {
|
||||
budgetIds.contains(it.budgetId)
|
||||
&& ids?.contains(it.id) ?: true
|
||||
&& it.expense == (expense ?: it.expense)
|
||||
&& it.archived == (archived ?: it.archived)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.db.DatabaseMetadata
|
||||
import com.wbrawner.twigs.db.MetadataRepository
|
||||
import com.wbrawner.twigs.storage.Repository
|
||||
|
||||
const val TEST_SALT = "testtesttesttest"
|
||||
|
||||
class FakeMetadataRepository : Repository<DatabaseMetadata>, MetadataRepository {
|
||||
var metadata = DatabaseMetadata(salt = TEST_SALT)
|
||||
override fun runMigration(toVersion: Int) {
|
||||
metadata = metadata.copy(version = toVersion)
|
||||
}
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<DatabaseMetadata> = listOf(metadata)
|
||||
|
||||
override suspend fun delete(item: DatabaseMetadata): Boolean = false
|
||||
|
||||
override suspend fun save(item: DatabaseMetadata): DatabaseMetadata {
|
||||
metadata = item
|
||||
return metadata
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.storage.PasswordResetRepository
|
||||
|
||||
class FakePasswordResetRepository : FakeRepository<PasswordResetToken>(), PasswordResetRepository
|
|
@ -0,0 +1,26 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
|
||||
class FakePermissionRepository : PermissionRepository {
|
||||
val permissions: MutableList<UserPermission> = mutableListOf()
|
||||
override suspend fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> =
|
||||
permissions.filter { userPermission ->
|
||||
budgetIds?.contains(userPermission.budgetId) ?: true
|
||||
&& userId?.let { it == userPermission.userId } ?: true
|
||||
}
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<UserPermission> {
|
||||
throw UnsupportedOperationException("UserPermission requires a userId and budgetId")
|
||||
}
|
||||
|
||||
override suspend fun save(item: UserPermission): UserPermission {
|
||||
permissions.removeIf { it.budgetId == item.budgetId && it.userId == item.userId }
|
||||
permissions.add(item)
|
||||
return item
|
||||
}
|
||||
|
||||
override suspend fun delete(item: UserPermission): Boolean =
|
||||
permissions.removeIf { it.budgetId == item.budgetId && it.userId == item.userId }
|
||||
}
|
|
@ -4,7 +4,7 @@ import com.wbrawner.twigs.model.RecurringTransaction
|
|||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import java.time.Instant
|
||||
|
||||
class FakeRecurringTransactionsRepository : FakeRepository<RecurringTransaction>(), RecurringTransactionRepository {
|
||||
class FakeRecurringTransactionRepository : FakeRepository<RecurringTransaction>(), RecurringTransactionRepository {
|
||||
override suspend fun findAll(now: Instant): List<RecurringTransaction> = entities.filter {
|
||||
(it.start == now || it.start.isBefore(now)) && it.finish?.isAfter(now) ?: true
|
||||
}
|
|
@ -4,7 +4,7 @@ import com.wbrawner.twigs.Identifiable
|
|||
import com.wbrawner.twigs.storage.Repository
|
||||
|
||||
abstract class FakeRepository<T : Identifiable> : Repository<T> {
|
||||
val entities = mutableListOf<T>()
|
||||
open val entities = mutableListOf<T>()
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<T> = if (ids == null) {
|
||||
entities
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.SessionRepository
|
||||
import java.util.function.Predicate
|
||||
|
||||
class FakeSessionRepository : FakeRepository<Session>(), SessionRepository {
|
||||
var expirationPredicate: Predicate<in Session> = Predicate { false }
|
||||
|
||||
override fun findAll(token: String): List<Session> = entities.filter { it.token == token }
|
||||
|
||||
override fun deleteExpired() {
|
||||
entities.removeIf(expirationPredicate)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.User
|
||||
import com.wbrawner.twigs.storage.UserRepository
|
||||
|
||||
class FakeUserRepository : FakeRepository<User>(), UserRepository {
|
||||
override val entities: MutableList<User> = mutableListOf(TEST_USER, OTHER_USER)
|
||||
|
||||
override fun findAll(nameOrEmail: String, password: String?): List<User> {
|
||||
return entities.filter { user ->
|
||||
(user.name.equals(nameOrEmail, ignoreCase = true) || user.email.equals(
|
||||
nameOrEmail,
|
||||
ignoreCase = true
|
||||
)) && password?.let { user.password == it } ?: true
|
||||
}
|
||||
}
|
||||
|
||||
override fun findAll(nameLike: String): List<User> {
|
||||
return entities.filter { it.name.contains(nameLike, ignoreCase = true) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
val TEST_USER = User(
|
||||
id = "id-test-user",
|
||||
name = "testuser",
|
||||
email = "test@example.com",
|
||||
password = "testpass"
|
||||
)
|
||||
|
||||
val OTHER_USER = User(
|
||||
id = "id-other-user",
|
||||
name = "otheruser",
|
||||
email = "other@example.com",
|
||||
password = "otherpass"
|
||||
)
|
||||
}
|
||||
}
|
|
@ -1,5 +1,3 @@
|
|||
import java.util.*
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
alias(libs.plugins.kotlin.jvm)
|
||||
|
@ -7,7 +5,10 @@ plugins {
|
|||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
implementation(project(":core"))
|
||||
implementation(project(":service"))
|
||||
api(libs.ktor.server.core)
|
||||
api(libs.ktor.server.mustache)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
@ -15,37 +16,3 @@ dependencies {
|
|||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
// TODO: Replace this hack with either a git submodule or an internal Kotlin-based UI
|
||||
tasks.register("package") {
|
||||
doLast {
|
||||
val built = File(rootProject.rootDir.parent, "twigs-web/dist/twigs")
|
||||
if (built.exists()) {
|
||||
built.deleteRecursively()
|
||||
}
|
||||
val dest = File(project.projectDir, "src/main/resources/twigs")
|
||||
if (dest.exists()) {
|
||||
dest.deleteRecursively()
|
||||
}
|
||||
var command = listOf(
|
||||
"cd", "../../twigs-web", ";",
|
||||
"npm", "i", ";",
|
||||
"npm", "run", "package"
|
||||
)
|
||||
command = if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows")) {
|
||||
listOf("powershell", "-Command") + command
|
||||
} else {
|
||||
listOf("bash", "-c", "\"${command.joinToString(" ")}\"")
|
||||
}
|
||||
exec {
|
||||
commandLine(command)
|
||||
}
|
||||
if (!built.copyRecursively(dest, true) || !dest.isDirectory) {
|
||||
throw GradleException("Failed to copy files from ${built.absolutePath} to ${dest.absolutePath}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//tasks.getByName("processResources") {
|
||||
// dependsOn.add("package")
|
||||
//}
|
||||
|
|
28
web/src/main/kotlin/com/wbrawner/twigs/web/Page.kt
Normal file
|
@ -0,0 +1,28 @@
|
|||
package com.wbrawner.twigs.web
|
||||
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.user.UserResponse
|
||||
|
||||
interface Page {
|
||||
val title: String
|
||||
val error: String?
|
||||
}
|
||||
|
||||
interface AuthenticatedPage : Page {
|
||||
val user: UserResponse
|
||||
val budgets: List<BudgetListItem>
|
||||
}
|
||||
|
||||
data class BudgetListItem(val id: String, val name: String, val description: String, val selected: Boolean)
|
||||
|
||||
fun BudgetResponse.toBudgetListItem(selectedId: String? = null) = BudgetListItem(
|
||||
id = id,
|
||||
name = name.orEmpty(),
|
||||
description = description.orEmpty(),
|
||||
selected = id == selectedId
|
||||
)
|
||||
|
||||
object NotFoundPage : Page {
|
||||
override val title: String = "404 Not Found"
|
||||
override val error: String? = null
|
||||
}
|
|
@ -1,24 +1,52 @@
|
|||
package com.wbrawner.twigs.web
|
||||
|
||||
import com.wbrawner.twigs.model.CookieSession
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import com.wbrawner.twigs.web.budget.budgetWebRoutes
|
||||
import com.wbrawner.twigs.web.category.categoryWebRoutes
|
||||
import com.wbrawner.twigs.web.transaction.transactionWebRoutes
|
||||
import com.wbrawner.twigs.web.user.userWebRoutes
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.http.content.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
|
||||
fun Application.webRoutes() {
|
||||
fun Application.webRoutes(
|
||||
budgetService: BudgetService,
|
||||
categoryService: CategoryService,
|
||||
transactionService: TransactionService,
|
||||
userService: UserService
|
||||
) {
|
||||
routing {
|
||||
static {
|
||||
resources("web")
|
||||
default("index.html")
|
||||
}
|
||||
intercept(ApplicationCallPipeline.Setup) {
|
||||
if (!call.request.path().startsWith("/api") && !call.request.path().matches(Regex(".*\\.\\w+$"))) {
|
||||
call.resolveResource("web/index.html")?.let {
|
||||
call.respond(it)
|
||||
return@intercept finish()
|
||||
staticResources("/", "static")
|
||||
get("/") {
|
||||
call.sessions.get(CookieSession::class)
|
||||
?.let {
|
||||
try {
|
||||
userService.session(it.token)
|
||||
} catch (e: HttpException) {
|
||||
application.environment.log.debug("Failed to retrieve session for user", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
?.let { session ->
|
||||
application.environment.log.info("Session found!")
|
||||
budgetService.budgetsForUser(session.userId)
|
||||
.firstOrNull()
|
||||
?.let { budget ->
|
||||
call.respondRedirect("/budgets/${budget.id}")
|
||||
} ?: call.respondRedirect("/budgets")
|
||||
} ?: call.respond(MustacheContent("index.mustache", null))
|
||||
}
|
||||
}
|
||||
budgetWebRoutes(budgetService, categoryService, transactionService, userService)
|
||||
categoryWebRoutes(budgetService, categoryService, transactionService, userService)
|
||||
transactionWebRoutes(budgetService, categoryService, transactionService, userService)
|
||||
userWebRoutes(userService)
|
||||
}
|
33
web/src/main/kotlin/com/wbrawner/twigs/web/WebUtils.kt
Normal file
|
@ -0,0 +1,33 @@
|
|||
package com.wbrawner.twigs.web
|
||||
|
||||
import io.ktor.http.*
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import java.text.DateFormat
|
||||
import java.text.DecimalFormat
|
||||
import java.text.NumberFormat
|
||||
import java.util.*
|
||||
|
||||
val currencyFormat = NumberFormat.getCurrencyInstance(Locale.US)
|
||||
val decimalFormat = DecimalFormat.getNumberInstance(Locale.US).apply {
|
||||
with(this as DecimalFormat) {
|
||||
decimalFormatSymbols = decimalFormatSymbols.apply {
|
||||
currencySymbol = ""
|
||||
isGroupingUsed = false
|
||||
}
|
||||
}
|
||||
}
|
||||
val shortDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US)
|
||||
|
||||
|
||||
fun Parameters.getAmount() = decimalFormat.parse(get("amount"))
|
||||
?.toDouble()
|
||||
?.toBigDecimal()
|
||||
?.times(BigDecimal(100))
|
||||
?.toLong()
|
||||
?: 0L
|
||||
|
||||
fun Long?.toDecimalString(): String {
|
||||
if (this == null) return ""
|
||||
return decimalFormat.format(toBigDecimal().divide(BigDecimal(100), 2, RoundingMode.HALF_UP))
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.wbrawner.twigs.web.budget
|
||||
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.user.UserResponse
|
||||
import com.wbrawner.twigs.web.AuthenticatedPage
|
||||
import com.wbrawner.twigs.web.BudgetListItem
|
||||
import com.wbrawner.twigs.web.category.CategoryWithBalanceResponse
|
||||
|
||||
data class BudgetListPage(
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = "Budgets"
|
||||
}
|
||||
|
||||
data class BudgetDetailsPage(
|
||||
val budget: BudgetResponse,
|
||||
val balances: BudgetBalances,
|
||||
val incomeCategories: List<CategoryWithBalanceResponse>,
|
||||
val expenseCategories: List<CategoryWithBalanceResponse>,
|
||||
val archivedIncomeCategories: List<CategoryWithBalanceResponse>,
|
||||
val archivedExpenseCategories: List<CategoryWithBalanceResponse>,
|
||||
val transactionCount: String,
|
||||
val monthAndYear: String,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = budget.name.orEmpty()
|
||||
}
|
||||
|
||||
data class BudgetFormPage(
|
||||
val budget: BudgetResponse,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = if (budget.id.isBlank()) {
|
||||
"New Budget"
|
||||
} else {
|
||||
"Edit Budget"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,242 @@
|
|||
package com.wbrawner.twigs.web.budget
|
||||
|
||||
import com.wbrawner.twigs.endOfMonth
|
||||
import com.wbrawner.twigs.firstOfMonth
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.budget.BudgetRequest
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import com.wbrawner.twigs.toInstantOrNull
|
||||
import com.wbrawner.twigs.web.NotFoundPage
|
||||
import com.wbrawner.twigs.web.category.CategoryWithBalanceResponse
|
||||
import com.wbrawner.twigs.web.toBudgetListItem
|
||||
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import java.math.BigDecimal
|
||||
import java.math.RoundingMode
|
||||
import java.text.NumberFormat
|
||||
import java.time.YearMonth
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.*
|
||||
import kotlin.math.abs
|
||||
|
||||
fun Application.budgetWebRoutes(
|
||||
budgetService: BudgetService,
|
||||
categoryService: CategoryService,
|
||||
transactionService: TransactionService,
|
||||
userService: UserService
|
||||
) {
|
||||
routing {
|
||||
authenticate(TWIGS_SESSION_COOKIE) {
|
||||
route("/budgets") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() }
|
||||
call.respond(MustacheContent("budgets.mustache", BudgetListPage(budgets, user)))
|
||||
}
|
||||
|
||||
route("/new") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"budget-form.mustache",
|
||||
BudgetFormPage(
|
||||
budget = BudgetResponse(
|
||||
id = "",
|
||||
name = "",
|
||||
description = "",
|
||||
users = listOf()
|
||||
),
|
||||
budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
try {
|
||||
val request = call.receiveParameters().toBudgetRequest()
|
||||
val budget = budgetService.save(request, user.id)
|
||||
call.respondRedirect("/budgets/${budget.id}")
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent(
|
||||
"budget-form.mustache",
|
||||
BudgetFormPage(
|
||||
budget = BudgetResponse(
|
||||
id = "",
|
||||
name = call.parameters["name"].orEmpty(),
|
||||
description = call.parameters["description"].orEmpty(),
|
||||
users = listOf()
|
||||
),
|
||||
budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() },
|
||||
user = user,
|
||||
error = e.message
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/{id}") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("id")
|
||||
val budgets = budgetService.budgetsForUser(userId = user.id).toMutableList()
|
||||
val budget = budgets.firstOrNull { it.id == budgetId }
|
||||
?: run {
|
||||
call.respond(MustacheContent("404.mustache", NotFoundPage))
|
||||
return@get
|
||||
}
|
||||
val numberFormat = NumberFormat.getCurrencyInstance(Locale.US)
|
||||
val categories = categoryService.categories(budgetIds = listOf(budget.id), userId = user.id)
|
||||
.map { category ->
|
||||
val categoryBalance =
|
||||
abs(transactionService.sum(categoryId = category.id, userId = user.id))
|
||||
CategoryWithBalanceResponse(
|
||||
category = category,
|
||||
amountLabel = category.amount.toCurrencyString(numberFormat),
|
||||
balance = categoryBalance,
|
||||
balanceLabel = categoryBalance.toCurrencyString(numberFormat),
|
||||
remainingAmountLabel = (category.amount - categoryBalance).toCurrencyString(
|
||||
numberFormat
|
||||
)
|
||||
)
|
||||
}
|
||||
.toMutableSet()
|
||||
val incomeCategories = categories.extractIf { !it.category.expense && !it.category.archived }
|
||||
val archivedIncomeCategories =
|
||||
categories.extractIf { !it.category.expense && it.category.archived }
|
||||
val expenseCategories = categories.extractIf { it.category.expense && !it.category.archived }
|
||||
val archivedExpenseCategories =
|
||||
categories.extractIf { it.category.expense && it.category.archived }
|
||||
val transactions = transactionService.transactions(
|
||||
budgetIds = listOf(budget.id),
|
||||
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
|
||||
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
|
||||
userId = user.id
|
||||
)
|
||||
// TODO: Allow user-configurable locale
|
||||
val budgetBalance = transactionService.sum(budgetId = budget.id, userId = user.id)
|
||||
.toCurrencyString(numberFormat)
|
||||
val expectedIncome = incomeCategories.sumOf { it.category.amount }
|
||||
val actualIncome = transactions.sumOf { if (it.expense == false) it.amount ?: 0L else 0L }
|
||||
val expectedExpenses = expenseCategories.sumOf { it.category.amount }
|
||||
val actualExpenses = transactions.sumOf { if (it.expense == true) it.amount ?: 0L else 0L }
|
||||
val balances = BudgetBalances(
|
||||
cashFlow = budgetBalance,
|
||||
expectedIncome = expectedIncome,
|
||||
expectedIncomeLabel = expectedIncome.toCurrencyString(numberFormat),
|
||||
actualIncome = actualIncome,
|
||||
actualIncomeLabel = actualIncome.toCurrencyString(numberFormat),
|
||||
expectedExpenses = expectedExpenses,
|
||||
expectedExpensesLabel = expectedExpenses.toCurrencyString(numberFormat),
|
||||
actualExpenses = actualExpenses,
|
||||
actualExpensesLabel = actualExpenses.toCurrencyString(numberFormat),
|
||||
)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"budget-details.mustache", BudgetDetailsPage(
|
||||
budget = budget,
|
||||
balances = balances,
|
||||
incomeCategories = incomeCategories,
|
||||
expenseCategories = expenseCategories,
|
||||
archivedIncomeCategories = archivedIncomeCategories,
|
||||
archivedExpenseCategories = archivedExpenseCategories,
|
||||
transactionCount = NumberFormat.getNumberInstance(Locale.US)
|
||||
.format(transactions.size),
|
||||
monthAndYear = YearMonth.now().format(DateTimeFormatter.ofPattern("MMMM yyyy")),
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) }.sortedBy { it.name },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
route("/edit") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budget = budgetService.budget(
|
||||
budgetId = call.parameters.getOrFail("id"),
|
||||
userId = user.id
|
||||
)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"budget-form.mustache",
|
||||
BudgetFormPage(
|
||||
budget = budget,
|
||||
budgets = budgetService.budgetsForUser(user.id)
|
||||
.map { it.toBudgetListItem(budget.id) },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
route("/delete") {
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("id")
|
||||
budgetService.delete(budgetId = budgetId, userId = user.id)
|
||||
call.respondRedirect("/")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class BudgetBalances(
|
||||
val cashFlow: String,
|
||||
val expectedIncome: Long,
|
||||
val expectedIncomeLabel: String,
|
||||
val actualIncome: Long,
|
||||
val actualIncomeLabel: String,
|
||||
val expectedExpenses: Long,
|
||||
val expectedExpensesLabel: String,
|
||||
val actualExpenses: Long,
|
||||
val actualExpensesLabel: String,
|
||||
) {
|
||||
val maxProgressBarValue: Long = maxOf(expectedExpenses, expectedIncome, actualIncome, actualExpenses)
|
||||
}
|
||||
|
||||
private fun Parameters.toBudgetRequest() = BudgetRequest(
|
||||
name = get("name"),
|
||||
description = get("description"),
|
||||
users = setOf() // TODO: Enable adding users at budget creation
|
||||
)
|
||||
|
||||
private fun <T> MutableCollection<T>.extractIf(predicate: (T) -> Boolean): List<T> {
|
||||
val extracted = mutableListOf<T>()
|
||||
val iterator = iterator()
|
||||
while (iterator.hasNext()) {
|
||||
val item = iterator.next()
|
||||
if (predicate(item)) {
|
||||
extracted.add(item)
|
||||
iterator.remove()
|
||||
}
|
||||
}
|
||||
return extracted
|
||||
}
|
||||
|
||||
fun Long.toCurrencyString(formatter: NumberFormat): String = formatter.format(
|
||||
this.toBigDecimal().divide(BigDecimal(100), 2, RoundingMode.HALF_UP)
|
||||
)
|
|
@ -0,0 +1,67 @@
|
|||
package com.wbrawner.twigs.web.category
|
||||
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.category.CategoryResponse
|
||||
import com.wbrawner.twigs.service.transaction.TransactionResponse
|
||||
import com.wbrawner.twigs.service.user.UserResponse
|
||||
import com.wbrawner.twigs.web.AuthenticatedPage
|
||||
import com.wbrawner.twigs.web.BudgetListItem
|
||||
import com.wbrawner.twigs.web.budget.toCurrencyString
|
||||
import java.text.NumberFormat
|
||||
|
||||
data class CategoryDetailsPage(
|
||||
val category: CategoryWithBalanceResponse,
|
||||
val budget: BudgetResponse,
|
||||
val transactionCount: String,
|
||||
val transactions: List<Map.Entry<String, List<TransactionListItem>>>,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = category.category.title
|
||||
}
|
||||
|
||||
data class TransactionListItem(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val description: String,
|
||||
val budgetId: String,
|
||||
val expenseClass: String,
|
||||
val amountLabel: String
|
||||
)
|
||||
|
||||
fun TransactionResponse.toListItem(numberFormat: NumberFormat) = TransactionListItem(
|
||||
id,
|
||||
title.orEmpty(),
|
||||
description.orEmpty(),
|
||||
budgetId,
|
||||
if (expense != false) "expense" else "income",
|
||||
(amount ?: 0L).toCurrencyString(numberFormat)
|
||||
)
|
||||
|
||||
data class CategoryFormPage(
|
||||
val category: CategoryResponse,
|
||||
val amountLabel: String,
|
||||
val budget: BudgetResponse,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = if (category.id.isBlank()) {
|
||||
"New Category"
|
||||
} else {
|
||||
"Edit Category"
|
||||
}
|
||||
|
||||
val expenseChecked: String = if (category.expense) "checked" else ""
|
||||
val incomeChecked: String = if (!category.expense) "checked" else ""
|
||||
val archivedChecked: String = if (category.archived) "checked" else ""
|
||||
}
|
||||
|
||||
data class CategoryWithBalanceResponse(
|
||||
val category: CategoryResponse,
|
||||
val amountLabel: String,
|
||||
val balance: Long,
|
||||
val balanceLabel: String,
|
||||
val remainingAmountLabel: String,
|
||||
)
|
|
@ -0,0 +1,245 @@
|
|||
package com.wbrawner.twigs.web.category
|
||||
|
||||
import com.wbrawner.twigs.endOfMonth
|
||||
import com.wbrawner.twigs.firstOfMonth
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.category.CategoryRequest
|
||||
import com.wbrawner.twigs.service.category.CategoryResponse
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import com.wbrawner.twigs.toInstant
|
||||
import com.wbrawner.twigs.toInstantOrNull
|
||||
import com.wbrawner.twigs.web.*
|
||||
import com.wbrawner.twigs.web.budget.toCurrencyString
|
||||
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import io.ktor.util.date.*
|
||||
import java.text.NumberFormat
|
||||
import java.util.*
|
||||
import kotlin.math.abs
|
||||
|
||||
fun Application.categoryWebRoutes(
|
||||
budgetService: BudgetService,
|
||||
categoryService: CategoryService,
|
||||
transactionService: TransactionService,
|
||||
userService: UserService
|
||||
) {
|
||||
routing {
|
||||
authenticate(TWIGS_SESSION_COOKIE) {
|
||||
route("/budgets/{budgetId}/categories") {
|
||||
get {
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
call.respondRedirect("/budgets/$budgetId")
|
||||
}
|
||||
|
||||
route("/new") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"category-form.mustache",
|
||||
CategoryFormPage(
|
||||
CategoryResponse(
|
||||
id = "",
|
||||
title = "",
|
||||
description = "",
|
||||
amount = 0,
|
||||
budgetId = budgetId,
|
||||
expense = call.request.queryParameters["expense"]?.toBoolean() ?: true,
|
||||
archived = false,
|
||||
),
|
||||
amountLabel = 0L.toDecimalString(),
|
||||
budget = budget,
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
try {
|
||||
val request = call.receiveParameters().toCategoryRequest(budgetId)
|
||||
val category = categoryService.save(request, user.id)
|
||||
call.respondRedirect("/budgets/${category.budgetId}/categories/${category.id}")
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent(
|
||||
"category-form.mustache",
|
||||
CategoryFormPage(
|
||||
CategoryResponse(
|
||||
id = "",
|
||||
title = call.parameters["title"].orEmpty(),
|
||||
description = call.parameters["description"].orEmpty(),
|
||||
amount = 0L,
|
||||
expense = call.parameters["expense"]?.toBoolean() ?: false,
|
||||
archived = call.parameters["archived"]?.toBoolean() ?: false,
|
||||
budgetId = budgetId
|
||||
),
|
||||
amountLabel = call.parameters["amount"]?.toLongOrNull().toDecimalString(),
|
||||
budget = budget,
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user,
|
||||
error = e.message
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/{id}") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val categoryId = call.parameters.getOrFail("id")
|
||||
try {
|
||||
val category = categoryService.category(categoryId = categoryId, userId = user.id)
|
||||
val categoryBalance =
|
||||
abs(transactionService.sum(categoryId = category.id, userId = user.id))
|
||||
val categoryWithBalance = CategoryWithBalanceResponse(
|
||||
category = category,
|
||||
amountLabel = category.amount.toCurrencyString(currencyFormat),
|
||||
balance = categoryBalance,
|
||||
balanceLabel = categoryBalance.toCurrencyString(currencyFormat),
|
||||
remainingAmountLabel = (category.amount - categoryBalance).toCurrencyString(
|
||||
currencyFormat
|
||||
)
|
||||
)
|
||||
val transactions = transactionService.transactions(
|
||||
budgetIds = listOf(category.budgetId),
|
||||
categoryIds = listOf(category.id),
|
||||
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
|
||||
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
|
||||
userId = user.id
|
||||
)
|
||||
val transactionCount = NumberFormat.getNumberInstance(Locale.US)
|
||||
.format(transactions.size)
|
||||
val transactionsByDate = transactions.groupBy {
|
||||
shortDateFormat.format(it.date.toInstant().toGMTDate().toJvmDate())
|
||||
}
|
||||
.mapValues { (_, transactions) -> transactions.map { it.toListItem(currencyFormat) } }
|
||||
.entries
|
||||
.sortedByDescending { it.key }
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"category-details.mustache", CategoryDetailsPage(
|
||||
category = categoryWithBalance,
|
||||
transactions = transactionsByDate,
|
||||
transactionCount = transactionCount,
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
budget = budget,
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent("404.mustache", NotFoundPage)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
route("/edit") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val category = categoryService.category(
|
||||
categoryId = call.parameters.getOrFail("id"),
|
||||
userId = user.id
|
||||
)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"category-form.mustache",
|
||||
CategoryFormPage(
|
||||
category = category,
|
||||
amountLabel = category.amount.toDecimalString(),
|
||||
budget = budgets.first { it.id == budgetId },
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val categoryId = call.parameters.getOrFail("id")
|
||||
try {
|
||||
val request = call.receiveParameters().toCategoryRequest(budgetId)
|
||||
val category = categoryService.save(request, userId = user.id, categoryId = categoryId)
|
||||
call.respondRedirect("/budgets/${category.budgetId}/categories/${category.id}")
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent(
|
||||
"category-form.mustache",
|
||||
CategoryFormPage(
|
||||
CategoryResponse(
|
||||
id = "",
|
||||
title = call.parameters["title"].orEmpty(),
|
||||
description = call.parameters["description"].orEmpty(),
|
||||
amount = 0L,
|
||||
expense = call.parameters["expense"]?.toBoolean() ?: false,
|
||||
archived = call.parameters["archived"]?.toBoolean() ?: false,
|
||||
budgetId = budgetId
|
||||
),
|
||||
amountLabel = call.parameters["amount"]?.toLongOrNull().toDecimalString(),
|
||||
budget = budgets.first { it.id == budgetId },
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user,
|
||||
error = e.message
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/delete") {
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val categoryId = call.parameters.getOrFail("id")
|
||||
categoryService.delete(categoryId = categoryId, userId = user.id)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
call.respondRedirect("/budgets/$budgetId")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Parameters.toCategoryRequest(budgetId: String) = CategoryRequest(
|
||||
title = get("title"),
|
||||
description = get("description"),
|
||||
amount = getAmount(),
|
||||
expense = get("expense")?.toBoolean(),
|
||||
archived = get("archived") == "on",
|
||||
budgetId = budgetId
|
||||
)
|
|
@ -0,0 +1,66 @@
|
|||
package com.wbrawner.twigs.web.transaction
|
||||
|
||||
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||
import com.wbrawner.twigs.service.category.CategoryResponse
|
||||
import com.wbrawner.twigs.service.transaction.TransactionResponse
|
||||
import com.wbrawner.twigs.service.user.UserResponse
|
||||
import com.wbrawner.twigs.web.AuthenticatedPage
|
||||
import com.wbrawner.twigs.web.BudgetListItem
|
||||
import com.wbrawner.twigs.web.category.TransactionListItem
|
||||
|
||||
data class TransactionListPage(
|
||||
val budget: BudgetResponse,
|
||||
val transactions: List<Map.Entry<String, List<TransactionListItem>>>,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = "Transactions"
|
||||
}
|
||||
|
||||
|
||||
data class TransactionDetailsPage(
|
||||
val transaction: TransactionResponse,
|
||||
val category: CategoryResponse?,
|
||||
val budget: BudgetResponse,
|
||||
val amountLabel: String,
|
||||
val dateLabel: String,
|
||||
val createdBy: UserResponse,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = transaction.title.orEmpty()
|
||||
}
|
||||
|
||||
data class TransactionFormPage(
|
||||
val transaction: TransactionResponse,
|
||||
val amountLabel: String,
|
||||
val budget: BudgetResponse,
|
||||
val categoryOptions: List<CategoryOption>,
|
||||
override val budgets: List<BudgetListItem>,
|
||||
override val user: UserResponse,
|
||||
override val error: String? = null
|
||||
) : AuthenticatedPage {
|
||||
override val title: String = if (transaction.id.isBlank()) {
|
||||
"New Transaction"
|
||||
} else {
|
||||
"Edit Transaction"
|
||||
}
|
||||
|
||||
data class CategoryOption(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val isSelected: Boolean = false,
|
||||
val isDisabled: Boolean = false
|
||||
) {
|
||||
val selected: String
|
||||
get() = if (isSelected) "selected" else ""
|
||||
|
||||
val disabled: String
|
||||
get() = if (isDisabled) "disabled" else ""
|
||||
}
|
||||
}
|
||||
|
||||
fun CategoryResponse.asOption(selectedCategoryId: String) =
|
||||
TransactionFormPage.CategoryOption(id, title, id == selectedCategoryId)
|
|
@ -0,0 +1,362 @@
|
|||
package com.wbrawner.twigs.web.transaction
|
||||
|
||||
import com.wbrawner.twigs.endOfMonth
|
||||
import com.wbrawner.twigs.firstOfMonth
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.budget.BudgetService
|
||||
import com.wbrawner.twigs.service.category.CategoryService
|
||||
import com.wbrawner.twigs.service.requireSession
|
||||
import com.wbrawner.twigs.service.transaction.TransactionRequest
|
||||
import com.wbrawner.twigs.service.transaction.TransactionResponse
|
||||
import com.wbrawner.twigs.service.transaction.TransactionService
|
||||
import com.wbrawner.twigs.service.user.UserResponse
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import com.wbrawner.twigs.toInstant
|
||||
import com.wbrawner.twigs.toInstantOrNull
|
||||
import com.wbrawner.twigs.web.*
|
||||
import com.wbrawner.twigs.web.budget.toCurrencyString
|
||||
import com.wbrawner.twigs.web.category.toListItem
|
||||
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.auth.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import io.ktor.util.date.*
|
||||
import java.time.Instant
|
||||
import java.time.ZoneOffset.UTC
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
fun Application.transactionWebRoutes(
|
||||
budgetService: BudgetService,
|
||||
categoryService: CategoryService,
|
||||
transactionService: TransactionService,
|
||||
userService: UserService
|
||||
) {
|
||||
routing {
|
||||
authenticate(TWIGS_SESSION_COOKIE) {
|
||||
route("/budgets/{budgetId}/transactions") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val transactions = transactionService.transactions(
|
||||
budgetIds = listOf(budgetId),
|
||||
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
|
||||
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
|
||||
userId = user.id
|
||||
)
|
||||
val transactionsByDate = transactions.groupBy {
|
||||
shortDateFormat.format(it.date.toInstant().toGMTDate().toJvmDate())
|
||||
}
|
||||
.mapValues { (_, transactions) -> transactions.map { it.toListItem(currencyFormat) } }
|
||||
.entries
|
||||
.sortedByDescending { it.key }
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"budget-transactions.mustache",
|
||||
TransactionListPage(
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
budget = budgets.first { it.id == budgetId },
|
||||
transactions = transactionsByDate,
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
route("/new") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
val categoryId = call.request.queryParameters["categoryId"]
|
||||
val transaction = TransactionResponse(
|
||||
id = "",
|
||||
title = "",
|
||||
description = "",
|
||||
amount = 0,
|
||||
budgetId = budgetId,
|
||||
expense = true,
|
||||
date = Instant.now().toHtmlInputString(),
|
||||
categoryId = categoryId,
|
||||
createdBy = user.id
|
||||
)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"transaction-form.mustache",
|
||||
TransactionFormPage(
|
||||
transaction = transaction,
|
||||
amountLabel = 0L.toDecimalString(),
|
||||
budget = budget,
|
||||
categoryOptions = categoryOptions(
|
||||
transaction = transaction,
|
||||
categoryService = categoryService,
|
||||
budgetId = budgetId,
|
||||
user = user
|
||||
),
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val urlBudgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == urlBudgetId }
|
||||
try {
|
||||
val request = call.receiveParameters().toTransactionRequest()
|
||||
.run {
|
||||
copy(
|
||||
date = "$date:00Z",
|
||||
expense = categoryService.category(
|
||||
categoryId = requireNotNull(categoryId),
|
||||
userId = user.id
|
||||
).expense,
|
||||
budgetId = urlBudgetId
|
||||
)
|
||||
}
|
||||
val transaction = transactionService.save(request, user.id)
|
||||
call.respondRedirect("/budgets/${transaction.budgetId}/transactions/${transaction.id}")
|
||||
} catch (e: HttpException) {
|
||||
val transaction = TransactionResponse(
|
||||
id = "",
|
||||
title = call.parameters["title"],
|
||||
description = call.parameters["description"],
|
||||
amount = 0L,
|
||||
budgetId = urlBudgetId,
|
||||
expense = call.parameters["expense"]?.toBoolean() ?: true,
|
||||
date = call.parameters["date"].orEmpty(),
|
||||
categoryId = call.parameters["categoryId"],
|
||||
createdBy = user.id
|
||||
)
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent(
|
||||
"transaction-form.mustache",
|
||||
TransactionFormPage(
|
||||
transaction = transaction,
|
||||
amountLabel = call.parameters["amount"].orEmpty(),
|
||||
budget = budget,
|
||||
categoryOptions = categoryOptions(
|
||||
transaction,
|
||||
categoryService,
|
||||
urlBudgetId,
|
||||
user
|
||||
),
|
||||
budgets = budgets.map { it.toBudgetListItem(urlBudgetId) },
|
||||
user = user,
|
||||
error = e.message
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/{id}") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val transactionId = call.parameters.getOrFail("id")
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
// TODO: Allow user-configurable locale
|
||||
try {
|
||||
val transaction = transactionService.transaction(
|
||||
transactionId = transactionId,
|
||||
userId = user.id
|
||||
)
|
||||
check(transaction.budgetId == budgetId) {
|
||||
// TODO: redirect instead of error?
|
||||
"Attempted to fetch transaction from wrong budget"
|
||||
}
|
||||
val category = transaction.categoryId?.let {
|
||||
categoryService.category(categoryId = it, userId = user.id)
|
||||
}
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
val dateFormat = DateTimeFormatter.ofPattern("H:mm a 'on' MMMM d, yyyy")
|
||||
val transactionInstant = transaction.date.toInstant()
|
||||
val transactionOffset = transactionInstant.atOffset(UTC)
|
||||
val dateLabel = transactionOffset.format(dateFormat)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"transaction-details.mustache", TransactionDetailsPage(
|
||||
transaction = transaction,
|
||||
category = category,
|
||||
budget = budget,
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
amountLabel = transaction.amount?.toCurrencyString(currencyFormat).orEmpty(),
|
||||
dateLabel = dateLabel,
|
||||
createdBy = userService.user(transaction.createdBy),
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent("404.mustache", NotFoundPage)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
route("/edit") {
|
||||
get {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val budgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == budgetId }
|
||||
val transaction = transactionService.transaction(
|
||||
transactionId = call.parameters.getOrFail("id"),
|
||||
userId = user.id
|
||||
)
|
||||
call.respond(
|
||||
MustacheContent(
|
||||
"transaction-form.mustache",
|
||||
TransactionFormPage(
|
||||
transaction = transaction.copy(
|
||||
date = transaction.date.toInstant().toHtmlInputString()
|
||||
),
|
||||
amountLabel = transaction.amount.toDecimalString(),
|
||||
budget = budget,
|
||||
categoryOptions = categoryOptions(transaction, categoryService, budgetId, user),
|
||||
budgets = budgets.map { it.toBudgetListItem(budgetId) },
|
||||
user = user
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val transactionId = call.parameters.getOrFail("id")
|
||||
val urlBudgetId = call.parameters.getOrFail("budgetId")
|
||||
val budgets = budgetService.budgetsForUser(user.id)
|
||||
val budget = budgets.first { it.id == urlBudgetId }
|
||||
try {
|
||||
val request = call.receiveParameters().toTransactionRequest()
|
||||
.run {
|
||||
copy(
|
||||
date = "$date:00Z",
|
||||
expense = categoryService.category(
|
||||
categoryId = requireNotNull(categoryId),
|
||||
userId = user.id
|
||||
).expense,
|
||||
budgetId = urlBudgetId
|
||||
)
|
||||
}
|
||||
val transaction =
|
||||
transactionService.save(request, userId = user.id, transactionId = transactionId)
|
||||
call.respondRedirect("/budgets/${transaction.budgetId}/transactions/${transaction.id}")
|
||||
} catch (e: HttpException) {
|
||||
val transaction = TransactionResponse(
|
||||
id = transactionId,
|
||||
title = call.parameters["title"],
|
||||
description = call.parameters["description"],
|
||||
amount = 0L,
|
||||
budgetId = urlBudgetId,
|
||||
expense = call.parameters["expense"]?.toBoolean() ?: true,
|
||||
date = call.parameters["date"].orEmpty(),
|
||||
categoryId = call.parameters["categoryId"],
|
||||
createdBy = user.id
|
||||
)
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent(
|
||||
"transaction-form.mustache",
|
||||
TransactionFormPage(
|
||||
transaction = transaction,
|
||||
amountLabel = call.parameters["amount"].orEmpty(),
|
||||
budget = budget,
|
||||
categoryOptions = categoryOptions(
|
||||
transaction,
|
||||
categoryService,
|
||||
urlBudgetId,
|
||||
user
|
||||
),
|
||||
budgets = budgets.map { it.toBudgetListItem(urlBudgetId) },
|
||||
user = user,
|
||||
error = e.message
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/delete") {
|
||||
post {
|
||||
val user = userService.user(requireSession().userId)
|
||||
val transactionId = call.parameters.getOrFail("id")
|
||||
val urlBudgetId = call.parameters.getOrFail("budgetId")
|
||||
transactionService.delete(transactionId = transactionId, userId = user.id)
|
||||
call.respondRedirect("/budgets/${urlBudgetId}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun categoryOptions(
|
||||
transaction: TransactionResponse,
|
||||
categoryService: CategoryService,
|
||||
budgetId: String,
|
||||
user: UserResponse
|
||||
): List<TransactionFormPage.CategoryOption> {
|
||||
val selectedCategoryId = transaction.categoryId.orEmpty()
|
||||
val categoryOptions = listOf(
|
||||
TransactionFormPage.CategoryOption(
|
||||
"",
|
||||
"Select a category",
|
||||
isSelected = transaction.categoryId.isNullOrBlank(),
|
||||
isDisabled = true
|
||||
),
|
||||
TransactionFormPage.CategoryOption("income", "Income", isDisabled = true),
|
||||
)
|
||||
.plus(
|
||||
categoryService.categories(
|
||||
budgetIds = listOf(budgetId),
|
||||
userId = user.id,
|
||||
expense = false,
|
||||
archived = false
|
||||
).map { category ->
|
||||
category.asOption(selectedCategoryId)
|
||||
}
|
||||
)
|
||||
.plus(
|
||||
TransactionFormPage.CategoryOption("expense", "Expense", isDisabled = true),
|
||||
)
|
||||
.plus(
|
||||
categoryService.categories(
|
||||
budgetIds = listOf(budgetId),
|
||||
userId = user.id,
|
||||
expense = true,
|
||||
archived = false
|
||||
).map { category ->
|
||||
category.asOption(selectedCategoryId)
|
||||
}
|
||||
)
|
||||
return categoryOptions
|
||||
}
|
||||
|
||||
private fun Parameters.toTransactionRequest() = TransactionRequest(
|
||||
title = get("title"),
|
||||
description = get("description"),
|
||||
amount = getAmount(),
|
||||
expense = false,
|
||||
date = get("date"),
|
||||
categoryId = get("categoryId"),
|
||||
budgetId = get("budgetId"),
|
||||
)
|
||||
|
||||
private fun Instant.toHtmlInputString() = truncatedTo(ChronoUnit.MINUTES).toString().substringBefore(":00Z")
|
11
web/src/main/kotlin/com/wbrawner/twigs/web/user/UserPages.kt
Normal file
|
@ -0,0 +1,11 @@
|
|||
package com.wbrawner.twigs.web.user
|
||||
|
||||
import com.wbrawner.twigs.web.Page
|
||||
|
||||
data class LoginPage(val username: String = "", override val error: String? = null) : Page {
|
||||
override val title: String = "Login"
|
||||
}
|
||||
|
||||
data class RegisterPage(val username: String = "", val email: String = "", override val error: String? = null) : Page {
|
||||
override val title: String = "Register"
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
package com.wbrawner.twigs.web.user
|
||||
|
||||
import com.wbrawner.twigs.model.CookieSession
|
||||
import com.wbrawner.twigs.service.HttpException
|
||||
import com.wbrawner.twigs.service.user.LoginRequest
|
||||
import com.wbrawner.twigs.service.user.UserRequest
|
||||
import com.wbrawner.twigs.service.user.UserService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.mustache.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.sessions.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
const val TWIGS_SESSION_COOKIE = "twigsSession"
|
||||
|
||||
fun Application.userWebRoutes(userService: UserService) {
|
||||
routing {
|
||||
route("/login") {
|
||||
get {
|
||||
call.respond(MustacheContent("login.mustache", LoginPage()))
|
||||
}
|
||||
|
||||
post {
|
||||
val request = call.receiveParameters().toLoginRequest()
|
||||
try {
|
||||
val session = userService.login(request)
|
||||
call.sessions.set(CookieSession(session.token))
|
||||
call.respondRedirect("/")
|
||||
} catch (e: Throwable) {
|
||||
e.printStackTrace()
|
||||
call.respond(
|
||||
status = (e as? HttpException)?.statusCode ?: HttpStatusCode.InternalServerError,
|
||||
MustacheContent("login.mustache", LoginPage(username = request.username, error = e.message))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
route("/logout") {
|
||||
post {
|
||||
call.sessions.clear<CookieSession>()
|
||||
call.respondRedirect("/")
|
||||
}
|
||||
}
|
||||
|
||||
route("/register") {
|
||||
get {
|
||||
call.respond(MustacheContent("register.mustache", RegisterPage()))
|
||||
}
|
||||
|
||||
post {
|
||||
val request = call.receiveParameters()
|
||||
val userRequest = request.toUserRequest()
|
||||
val confirmPassword = request.getOrFail("confirmPassword")
|
||||
if (userRequest.password != confirmPassword) {
|
||||
call.respond(
|
||||
HttpStatusCode.BadRequest,
|
||||
MustacheContent(
|
||||
"register.mustache",
|
||||
userRequest.toPage("passwords don't match")
|
||||
)
|
||||
)
|
||||
return@post
|
||||
}
|
||||
try {
|
||||
userService.register(userRequest)
|
||||
val session = userService.login(
|
||||
LoginRequest(
|
||||
requireNotNull(userRequest.username),
|
||||
requireNotNull(userRequest.password)
|
||||
)
|
||||
)
|
||||
call.sessions.set(CookieSession(session.token))
|
||||
call.respondRedirect("/")
|
||||
} catch (e: HttpException) {
|
||||
call.respond(
|
||||
status = e.statusCode,
|
||||
MustacheContent("register.mustache", userRequest.toPage(error = e.message))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Parameters.toLoginRequest() = LoginRequest(get("username").orEmpty(), get("password").orEmpty())
|
||||
|
||||
private fun Parameters.toUserRequest() = UserRequest(get("username").orEmpty(), get("password").orEmpty(), get("email"))
|
||||
|
||||
private fun UserRequest.toPage(error: String? = null) =
|
||||
RegisterPage(username = username.orEmpty(), email = email.orEmpty(), error = error)
|
BIN
web/src/main/resources/static/favicon.ico
Normal file
After Width: | Height: | Size: 1.1 KiB |
BIN
web/src/main/resources/static/icons/favicon-16x16.png
Normal file
After Width: | Height: | Size: 969 B |
BIN
web/src/main/resources/static/icons/favicon-32x32.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
web/src/main/resources/static/icons/favicon-96x96.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
web/src/main/resources/static/icons/icon-128x128.png
Normal file
After Width: | Height: | Size: 6.6 KiB |
BIN
web/src/main/resources/static/icons/icon-144x144.png
Normal file
After Width: | Height: | Size: 7.3 KiB |
BIN
web/src/main/resources/static/icons/icon-152x152.png
Normal file
After Width: | Height: | Size: 7.7 KiB |
BIN
web/src/main/resources/static/icons/icon-192x192.png
Normal file
After Width: | Height: | Size: 9.6 KiB |
BIN
web/src/main/resources/static/icons/icon-384x384.png
Normal file
After Width: | Height: | Size: 19 KiB |
BIN
web/src/main/resources/static/icons/icon-512x512.png
Normal file
After Width: | Height: | Size: 26 KiB |
BIN
web/src/main/resources/static/icons/icon-72x72.png
Normal file
After Width: | Height: | Size: 3.7 KiB |
BIN
web/src/main/resources/static/icons/icon-96x96.png
Normal file
After Width: | Height: | Size: 5.1 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-128x128.png
Normal file
After Width: | Height: | Size: 4 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-144x144.png
Normal file
After Width: | Height: | Size: 4.5 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-152x152.png
Normal file
After Width: | Height: | Size: 4.7 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-192x192.png
Normal file
After Width: | Height: | Size: 5.8 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-384x384.png
Normal file
After Width: | Height: | Size: 12 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-512x512.png
Normal file
After Width: | Height: | Size: 15 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-72x72.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
web/src/main/resources/static/icons/icon-maskable-96x96.png
Normal file
After Width: | Height: | Size: 3.2 KiB |
BIN
web/src/main/resources/static/icons/touch-icon.png
Normal file
After Width: | Height: | Size: 675 KiB |
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
|
@ -2,20 +2,19 @@
|
|||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="1024"
|
||||
height="1024"
|
||||
viewBox="0 0 270.93333 270.93334"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="0.92.4 (unknown)"
|
||||
sodipodi:docname="White.svg">
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
width="1024"
|
||||
height="1024"
|
||||
viewBox="0 0 270.93333 270.93334"
|
||||
version="1.1"
|
||||
id="svg8"
|
||||
inkscape:version="0.92.4 (unknown)"
|
||||
sodipodi:docname="White.svg">
|
||||
<defs
|
||||
id="defs2" />
|
||||
<sodipodi:namedview
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.3 KiB |