Compare commits
4 commits
Author | SHA1 | Date | |
---|---|---|---|
6bbb421167 | |||
04802434fd | |||
f3edf5044b | |||
f0e937e8b4 |
166 changed files with 1290 additions and 9400 deletions
|
@ -1,47 +0,0 @@
|
|||
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 }}
|
|
@ -1,26 +0,0 @@
|
|||
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
17
.github/workflows/docker-image.yml
vendored
|
@ -1,8 +1,9 @@
|
|||
name: Publish Docker image
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
branches: main
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
push_to_registry:
|
||||
|
@ -10,10 +11,10 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v2
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/wbrawner/twigs
|
||||
|
@ -26,17 +27,17 @@ jobs:
|
|||
type=semver,pattern={{major}}
|
||||
type=sha
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v2
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v2
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
|
40
.github/workflows/pull-request.yml
vendored
40
.github/workflows/pull-request.yml
vendored
|
@ -2,30 +2,24 @@ name: Pull request workflow
|
|||
on: pull_request
|
||||
|
||||
permissions:
|
||||
statuses: write
|
||||
checks: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Build and Test
|
||||
build:
|
||||
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
|
||||
- uses: actions/checkout@v3
|
||||
- name: Setup Gradle
|
||||
uses: gradle/gradle-build-action@v2
|
||||
- name: Run checks with Gradle Wrapper
|
||||
run: ./gradlew check
|
||||
automerge:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.actor == 'wbrawner' }}
|
||||
steps:
|
||||
- name: Enable auto-merge
|
||||
run: gh pr merge --auto --merge "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
28
.gitignore
vendored
28
.gitignore
vendored
|
@ -1,33 +1,15 @@
|
|||
HELP.md
|
||||
/target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
.gradle
|
||||
*.sql
|
||||
|
||||
tags
|
||||
twigs.db
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target
|
||||
|
|
661
COPYING
661
COPYING
|
@ -1,661 +0,0 @@
|
|||
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/>.
|
1218
Cargo.lock
generated
Normal file
1218
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
9
Cargo.toml
Normal file
9
Cargo.toml
Normal file
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "twigs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4"
|
|
@ -1,4 +1,4 @@
|
|||
FROM ibm-semeru-runtimes:open-21-jdk as builder
|
||||
FROM openjdk:17-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 ibm-semeru-runtimes:open-21-jre
|
||||
FROM openjdk:17-slim
|
||||
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 /opt/java/openjdk/bin/java $JVM_ARGS -jar /twigs.jar
|
||||
CMD /usr/local/openjdk-17/bin/java $JVM_ARGS -jar /twigs.jar
|
||||
|
|
661
LICENSE
661
LICENSE
|
@ -1,661 +1,8 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
Copyright 2019 William Patrick Brawner
|
||||
|
||||
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.
|
||||
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:
|
||||
|
||||
Preamble
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of 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 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 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
18
README.md
|
@ -1,11 +1,12 @@
|
|||
# Twigs
|
||||
# Twigs Server
|
||||
|
||||
Twigs is a personal finance application tailored to individuals and small groups that want robust budgeting features
|
||||
without needing to pay a monthly subscription.
|
||||
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.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- JDK 17 or newer
|
||||
- JDK 14 or newer
|
||||
- PostgreSQL 13 or newer
|
||||
- (optional) Docker
|
||||
|
||||
|
@ -43,12 +44,3 @@ 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
api/.gitignore
vendored
1
api/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,18 +0,0 @@
|
|||
plugins {
|
||||
kotlin("jvm")
|
||||
`java-library`
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(project(":core"))
|
||||
implementation(project(":service"))
|
||||
implementation(project(":storage"))
|
||||
api(libs.ktor.server.core)
|
||||
api(libs.kotlinx.coroutines.core)
|
||||
testImplementation(project(":testhelpers"))
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
|
@ -1,60 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
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.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.budgetRoutes(budgetService: BudgetService) {
|
||||
routing {
|
||||
route("/api/budgets") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
call.respondCatching {
|
||||
budgetService.budgetsForUser(userId = requireSession().userId)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
call.respondCatching {
|
||||
budgetService.budget(
|
||||
budgetId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
call.respondCatching {
|
||||
budgetService.save(request = call.receive(), userId = requireSession().userId)
|
||||
}
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
call.respondCatching {
|
||||
budgetService.save(
|
||||
request = call.receive(),
|
||||
userId = requireSession().userId,
|
||||
budgetId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
call.respondCatching {
|
||||
budgetService.delete(
|
||||
budgetId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,66 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
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.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.categoryRoutes(categoryService: CategoryService) {
|
||||
routing {
|
||||
route("/api/categories") {
|
||||
authenticate(optional = false) {
|
||||
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()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
call.respondCatching {
|
||||
categoryService.category(
|
||||
categoryId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
call.respondCatching {
|
||||
categoryService.save(call.receive<CategoryRequest>(), requireSession().userId)
|
||||
}
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
call.respondCatching {
|
||||
categoryService.save(
|
||||
request = call.receive<CategoryRequest>(),
|
||||
userId = requireSession().userId,
|
||||
categoryId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
call.respondCatching {
|
||||
categoryService.delete(
|
||||
call.parameters.getOrFail("id"),
|
||||
requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
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.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.recurringTransactionRoutes(recurringTransactionService: RecurringTransactionService) {
|
||||
routing {
|
||||
route("/api/recurringtransactions") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
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}") {
|
||||
call.respondCatching {
|
||||
recurringTransactionService.delete(call.parameters.getOrFail("id"), requireSession().userId)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,87 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
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.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import java.time.Instant
|
||||
|
||||
fun Application.transactionRoutes(transactionService: TransactionService) {
|
||||
routing {
|
||||
route("/api/transactions") {
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
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(),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
call.respondCatching {
|
||||
transactionService.transaction(
|
||||
transactionId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/sum") {
|
||||
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,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
call.respondCatching {
|
||||
transactionService.save(
|
||||
request = call.receive<TransactionRequest>(),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
call.respondCatching {
|
||||
transactionService.save(
|
||||
request = call.receive<TransactionRequest>(),
|
||||
userId = requireSession().userId,
|
||||
transactionId = call.parameters.getOrFail("id")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
call.respondCatching {
|
||||
transactionService.delete(
|
||||
transactionId = call.parameters.getOrFail("id"),
|
||||
userId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,84 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
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.routing.*
|
||||
import io.ktor.server.util.*
|
||||
|
||||
fun Application.userRoutes(userService: UserService) {
|
||||
routing {
|
||||
route("/api/users") {
|
||||
post("/login") {
|
||||
call.respondCatching {
|
||||
userService.login(call.receive())
|
||||
}
|
||||
}
|
||||
|
||||
post("/register") {
|
||||
call.respondCatching {
|
||||
userService.register(call.receive())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
route("/resetpassword") {
|
||||
post {
|
||||
call.respondCatching {
|
||||
userService.requestPasswordResetEmail(call.receive())
|
||||
HttpStatusCode.Accepted
|
||||
}
|
||||
}
|
||||
|
||||
put {
|
||||
call.respondCatching {
|
||||
userService.resetPassword(call.receive())
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
authenticate(optional = false) {
|
||||
get {
|
||||
call.respondCatching {
|
||||
userService.users(
|
||||
query = call.request.queryParameters["query"],
|
||||
budgetIds = call.request.queryParameters.getAll("budgetId"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
get("/{id}") {
|
||||
call.respondCatching {
|
||||
userService.user(call.parameters.getOrFail("id"))
|
||||
}
|
||||
}
|
||||
|
||||
put("/{id}") {
|
||||
call.respondCatching {
|
||||
userService.save(
|
||||
request = call.receive(),
|
||||
targetUserId = call.parameters.getOrFail("id"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
delete("/{id}") {
|
||||
call.respondCatching {
|
||||
userService.delete(
|
||||
targetUserId = call.parameters.getOrFail("id"),
|
||||
requestingUserId = requireSession().userId
|
||||
)
|
||||
HttpStatusCode.NoContent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
1
app/.gitignore
vendored
1
app/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,61 +0,0 @@
|
|||
import java.net.URI
|
||||
|
||||
plugins {
|
||||
java
|
||||
kotlin("jvm")
|
||||
application
|
||||
alias(libs.plugins.shadow)
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
maven {
|
||||
url = URI("https://repo.maven.apache.org/maven2")
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":api"))
|
||||
implementation(project(":core"))
|
||||
implementation(project(":db"))
|
||||
implementation(project(":web"))
|
||||
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.ktor.client.content.negotiation)
|
||||
testImplementation(libs.ktor.server.test)
|
||||
}
|
||||
|
||||
description = "twigs-server"
|
||||
|
||||
val twigsMain = "com.wbrawner.twigs.server.ApplicationKt"
|
||||
|
||||
application {
|
||||
mainClass.set(twigsMain)
|
||||
}
|
||||
|
||||
tasks.shadowJar {
|
||||
manifest {
|
||||
attributes("Main-Class" to twigsMain)
|
||||
archiveBaseName.set("twigs")
|
||||
archiveClassifier.set("")
|
||||
archiveVersion.set("")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
reports {
|
||||
junitXml.required.set(true)
|
||||
html.required.set(false)
|
||||
}
|
||||
}
|
|
@ -1,274 +0,0 @@
|
|||
package com.wbrawner.twigs.server
|
||||
|
||||
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.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.*
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
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 = 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")
|
||||
}
|
||||
}
|
||||
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(
|
||||
budgetService = DefaultBudgetService(budgetRepository, permissionRepository),
|
||||
categoryService = DefaultCategoryService(categoryRepository, permissionRepository),
|
||||
recurringTransactionService = DefaultRecurringTransactionService(
|
||||
recurringTransactionRepository,
|
||||
permissionRepository
|
||||
),
|
||||
transactionService = DefaultTransactionService(
|
||||
transactionRepository,
|
||||
categoryRepository,
|
||||
permissionRepository
|
||||
),
|
||||
userService = DefaultUserService(
|
||||
emailService,
|
||||
passwordResetRepository,
|
||||
permissionRepository,
|
||||
sessionRepository,
|
||||
userRepository,
|
||||
passwordHasher
|
||||
),
|
||||
jobs = jobs,
|
||||
sessionValidator = sessionValidator
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun Application.moduleWithDependencies(
|
||||
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(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): HeaderSession {
|
||||
this@moduleWithDependencies.environment.log.info("Deserializing session!")
|
||||
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 {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
explicitNulls = false
|
||||
isLenient = true
|
||||
allowSpecialFloatingPointValues = true
|
||||
allowStructuredMapKeys = true
|
||||
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)
|
||||
allowHeader(HttpHeaders.Accept)
|
||||
allowHeader(HttpHeaders.AcceptEncoding)
|
||||
allowHeader(HttpHeaders.AcceptLanguage)
|
||||
allowHeader(HttpHeaders.Connection)
|
||||
allowHeader(HttpHeaders.ContentType)
|
||||
allowHeader(HttpHeaders.Host)
|
||||
allowHeader(HttpHeaders.Origin)
|
||||
allowHeader(HttpHeaders.AccessControlRequestHeaders)
|
||||
allowHeader(HttpHeaders.AccessControlRequestMethod)
|
||||
allowHeader("Sec-Fetch-Dest")
|
||||
allowHeader("Sec-Fetch-Mode")
|
||||
allowHeader("Sec-Fetch-Site")
|
||||
allowHeader("sec-ch-ua")
|
||||
allowHeader("sec-ch-ua-mobile")
|
||||
allowHeader("sec-ch-ua-platform")
|
||||
allowHeader(HttpHeaders.UserAgent)
|
||||
allowHeader("DNT")
|
||||
allowCredentials = true
|
||||
}
|
||||
install(Mustache) {
|
||||
mustacheFactory = DefaultMustacheFactory("templates")
|
||||
}
|
||||
budgetRoutes(budgetService)
|
||||
categoryRoutes(categoryService)
|
||||
recurringTransactionRoutes(recurringTransactionService)
|
||||
transactionRoutes(transactionService)
|
||||
userRoutes(userService)
|
||||
webRoutes(budgetService, categoryService, transactionService, userService)
|
||||
launch {
|
||||
while (currentCoroutineContext().isActive) {
|
||||
jobs.forEach { it.run() }
|
||||
delay(TimeUnit.HOURS.toMillis(1))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface Job {
|
||||
suspend fun run()
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
package com.wbrawner.twigs.server
|
||||
|
||||
import com.wbrawner.twigs.model.Frequency
|
||||
import com.wbrawner.twigs.model.Position
|
||||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import com.wbrawner.twigs.storage.TransactionRepository
|
||||
import java.time.*
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.util.*
|
||||
import kotlin.math.ceil
|
||||
|
||||
class RecurringTransactionProcessingJob(
|
||||
private val recurringTransactionRepository: RecurringTransactionRepository,
|
||||
private val transactionRepository: TransactionRepository
|
||||
) : Job {
|
||||
override suspend fun run() {
|
||||
val now = Instant.now()
|
||||
val maxDaysInMonth = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"))
|
||||
.getActualMaximum(Calendar.DAY_OF_MONTH)
|
||||
createTransactions(now, maxDaysInMonth)
|
||||
}
|
||||
|
||||
suspend fun createTransactions(now: Instant, maxDaysInMonth: Int) {
|
||||
recurringTransactionRepository.findAll(now).forEach {
|
||||
val zonedNow = now.atZone(ZoneId.of("UTC"))
|
||||
when (it.frequency) {
|
||||
is Frequency.Daily -> {
|
||||
if (it.lastRun != null && ChronoUnit.DAYS.between(it.lastRun, now) < it.frequency.count)
|
||||
return@forEach
|
||||
}
|
||||
is Frequency.Weekly -> {
|
||||
it.lastRun?.let { last ->
|
||||
val zonedLastRun = last.atZone(ZoneId.of("UTC"))
|
||||
if (ChronoUnit.WEEKS.between(zonedLastRun, zonedNow) < it.frequency.count)
|
||||
return@forEach
|
||||
}
|
||||
if (!(it.frequency as Frequency.Weekly).daysOfWeek.contains(DayOfWeek.from(zonedNow)))
|
||||
return@forEach
|
||||
}
|
||||
is Frequency.Monthly -> {
|
||||
it.lastRun?.let { last ->
|
||||
val zonedLastRun = last.atZone(ZoneId.of("UTC"))
|
||||
val monthsPassed = ((zonedNow.year * 12) + zonedNow.monthValue) - ((zonedLastRun.year * 12) + zonedLastRun.monthValue)
|
||||
if (monthsPassed < it.frequency.count)
|
||||
return@forEach
|
||||
}
|
||||
val frequency = (it.frequency as Frequency.Monthly).dayOfMonth
|
||||
frequency.day?.let { day ->
|
||||
if (zonedNow.dayOfMonth != Integer.min(day, maxDaysInMonth))
|
||||
return@forEach
|
||||
}
|
||||
frequency.positionalDayOfWeek?.let { positionalDayOfWeek ->
|
||||
if (positionalDayOfWeek.dayOfWeek != DayOfWeek.from(now.atZone(ZoneId.of("UTC"))))
|
||||
return@forEach
|
||||
val dayOfMonth = now.atZone(ZoneId.of("UTC")).dayOfMonth
|
||||
val position = ceil(dayOfMonth / 7.0).toInt()
|
||||
when (positionalDayOfWeek.position) {
|
||||
Position.FIRST -> if (position != 1) return@forEach
|
||||
Position.SECOND -> if (position != 2) return@forEach
|
||||
Position.THIRD -> if (position != 3) return@forEach
|
||||
Position.FOURTH -> if (position != 4) return@forEach
|
||||
Position.LAST -> {
|
||||
if (dayOfMonth + 7 <= maxDaysInMonth)
|
||||
return@forEach
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
is Frequency.Yearly -> {
|
||||
it.lastRun?.let { last ->
|
||||
val zonedLastRun = last.atZone(ZoneId.of("UTC"))
|
||||
if (zonedNow.year - zonedLastRun.year < it.frequency.count)
|
||||
return@forEach
|
||||
}
|
||||
with((it.frequency as Frequency.Yearly).dayOfYear) {
|
||||
// If the user has selected Feb 29th, then on non-leap years we'll adjust the date to Feb 28th
|
||||
val adjustedMonthDay =
|
||||
if (this.month == Month.FEBRUARY && this.dayOfMonth == 29 && !Year.isLeap(zonedNow.year.toLong())) {
|
||||
MonthDay.of(2, 28)
|
||||
} else {
|
||||
this
|
||||
}
|
||||
if (MonthDay.from(zonedNow) != adjustedMonthDay)
|
||||
return@forEach
|
||||
}
|
||||
}
|
||||
}
|
||||
transactionRepository.save(it.toTransaction(now))
|
||||
recurringTransactionRepository.save(it.copy(lastRun = now))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
package com.wbrawner.twigs.server
|
||||
|
||||
import com.wbrawner.twigs.storage.SessionRepository
|
||||
|
||||
class SessionCleanupJob(private val sessionRepository: SessionRepository) : Job {
|
||||
override suspend fun run() {
|
||||
sessionRepository.deleteExpired()
|
||||
}
|
||||
}
|
|
@ -1,77 +0,0 @@
|
|||
package com.wbrawner.twigs.server
|
||||
|
||||
import com.wbrawner.twigs.EmailService
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import java.util.*
|
||||
import javax.mail.*
|
||||
import javax.mail.internet.InternetAddress
|
||||
import javax.mail.internet.MimeBodyPart
|
||||
import javax.mail.internet.MimeMessage
|
||||
import javax.mail.internet.MimeMultipart
|
||||
|
||||
|
||||
class SmtpEmailService(
|
||||
val from: String?,
|
||||
val host: String?,
|
||||
val port: Int?,
|
||||
val username: String?,
|
||||
val password: String?
|
||||
) : EmailService {
|
||||
private val canSendEmail = !from.isNullOrBlank()
|
||||
&& !host.isNullOrBlank()
|
||||
&& port != null
|
||||
&& !username.isNullOrBlank()
|
||||
&& !password.isNullOrBlank()
|
||||
|
||||
private val session = Session.getInstance(
|
||||
Properties().apply {
|
||||
put("mail.smtp.auth", "true")
|
||||
put("mail.smtp.host", host ?: "")
|
||||
put("mail.smtp.port", port ?: 25)
|
||||
put("mail.smtp.from", from ?: "")
|
||||
},
|
||||
object : Authenticator() {
|
||||
override fun getPasswordAuthentication(): PasswordAuthentication {
|
||||
return PasswordAuthentication(username, password)
|
||||
}
|
||||
})
|
||||
|
||||
override fun sendPasswordResetEmail(token: PasswordResetToken, to: String) {
|
||||
val resetUrl = "twigs://resetpassword?token=${token.id}"
|
||||
val plainText = javaClass.getResource("/email/plain/passwordreset.txt")
|
||||
?.readText()
|
||||
?.replace("{reset_url}", resetUrl)
|
||||
val html = javaClass.getResource("/email/html/passwordreset.html")
|
||||
?.readText()
|
||||
?.replace("{reset_url}", resetUrl)
|
||||
sendEmail(
|
||||
plainText,
|
||||
html,
|
||||
to,
|
||||
"Twigs Password Reset" // TODO: Localization
|
||||
)
|
||||
}
|
||||
|
||||
private fun sendEmail(plainText: String?, html: String?, to: String, subject: String) {
|
||||
if (!canSendEmail) return
|
||||
if (plainText.isNullOrBlank() && html.isNullOrBlank()) return
|
||||
val message = MimeMessage(session)
|
||||
message.setFrom(InternetAddress(from, "Twigs"))
|
||||
message.setRecipients(Message.RecipientType.TO, to)
|
||||
val multipart: Multipart = MimeMultipart("alternative").apply {
|
||||
plainText?.let {
|
||||
addBodyPart(it.asMimeBodyPart("text/plain; charset=utf-8"))
|
||||
}
|
||||
html?.let {
|
||||
addBodyPart(it.asMimeBodyPart("text/html; charset=utf-8"))
|
||||
}
|
||||
}
|
||||
message.setContent(multipart)
|
||||
message.subject = subject
|
||||
Transport.send(message)
|
||||
}
|
||||
|
||||
private fun String.asMimeBodyPart(mimeType: String): MimeBodyPart = MimeBodyPart().apply {
|
||||
setContent(this@asMimeBodyPart, mimeType)
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Twigs - Reset Your Password</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"
|
||||
"/>
|
||||
</head>
|
||||
<body>
|
||||
<style>
|
||||
html, body {
|
||||
font-family: sans-serif;
|
||||
height: 100%;
|
||||
height: 100vh;
|
||||
background: white;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #30d158;
|
||||
}
|
||||
</style>
|
||||
<table width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<img src="https://twigs.wbrawner.com/favicon-96x96.png"/>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<h1>Reset Your Password</h1>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
If you requested a password reset, please <a href="{reset_url}" target="_blank">click here</a> to complete
|
||||
the
|
||||
process. If
|
||||
you didn't make this request,
|
||||
you can ignore this email. Alternatively, you can copy and paste the link below in your browser:
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<pre>{reset_url}</pre>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -1,5 +0,0 @@
|
|||
Reset Your Password
|
||||
|
||||
If you requested a password reset, please open the link below to complete the process. If you didn't make this request, you can ignore this email.
|
||||
|
||||
{reset_url}
|
|
@ -1,597 +0,0 @@
|
|||
openapi: "3.0.3"
|
||||
info:
|
||||
title: "twigs API"
|
||||
description: "twigs API"
|
||||
version: "1.0.0"
|
||||
servers:
|
||||
- url: "https://twigs"
|
||||
paths:
|
||||
/api/recurringtransactions:
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "budgetId"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "array"
|
||||
items:
|
||||
$ref: "#/components/schemas/RecurringTransactionResponse"
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/RecurringTransactionResponse"
|
||||
/api/recurringtransactions/{id}:
|
||||
delete:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
"500":
|
||||
description: "Internal Server Error"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/RecurringTransactionResponse"
|
||||
put:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/RecurringTransactionResponse"
|
||||
/api/categories:
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "budgetIds"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "expense"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "archived"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "array"
|
||||
items:
|
||||
type: "object"
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/CategoryResponse"
|
||||
/api/categories/{id}:
|
||||
delete:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/CategoryResponse"
|
||||
put:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"404":
|
||||
description: "Not Found"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/CategoryResponse"
|
||||
/api/passwordreset:
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
/api/resetpassword:
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"202":
|
||||
description: "Accepted"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
/api/users:
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "query"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "budgetId"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "array"
|
||||
items:
|
||||
type: "object"
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
/api/users/{id}:
|
||||
delete:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
put:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
/api/users/login:
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/SessionResponse"
|
||||
/api/users/register:
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/UserResponse"
|
||||
/api/budgets:
|
||||
get:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "array"
|
||||
items:
|
||||
type: "object"
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/BudgetResponse"
|
||||
/api/budgets/{id}:
|
||||
delete:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/BudgetResponse"
|
||||
put:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/BudgetResponse"
|
||||
/api/transactions:
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "budgetIds"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "categoryIds"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "from"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "to"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "expense"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "array"
|
||||
items:
|
||||
$ref: "#/components/schemas/TransactionResponse"
|
||||
post:
|
||||
description: ""
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/TransactionResponse"
|
||||
/api/transactions/{id}:
|
||||
delete:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"204":
|
||||
description: "No Content"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
"500":
|
||||
description: "Internal Server Error"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
type: "object"
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/TransactionResponse"
|
||||
put:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "id"
|
||||
in: "path"
|
||||
required: true
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/TransactionResponse"
|
||||
/api/transactions/sum:
|
||||
get:
|
||||
description: ""
|
||||
parameters:
|
||||
- name: "categoryId"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "budgetId"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "from"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
- name: "to"
|
||||
in: "query"
|
||||
required: false
|
||||
schema:
|
||||
type: "string"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
'*/*':
|
||||
schema:
|
||||
$ref: "#/components/schemas/BalanceResponse"
|
||||
components:
|
||||
schemas:
|
||||
RecurringTransactionResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
id:
|
||||
type: "string"
|
||||
title:
|
||||
type: "string"
|
||||
description:
|
||||
type: "string"
|
||||
frequency:
|
||||
type: "string"
|
||||
start:
|
||||
type: "string"
|
||||
finish:
|
||||
type: "string"
|
||||
amount:
|
||||
type: "integer"
|
||||
format: "int64"
|
||||
expense:
|
||||
type: "boolean"
|
||||
budgetId:
|
||||
type: "string"
|
||||
categoryId:
|
||||
type: "string"
|
||||
createdBy:
|
||||
type: "string"
|
||||
CategoryResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
id:
|
||||
type: "string"
|
||||
title:
|
||||
type: "string"
|
||||
description:
|
||||
type: "string"
|
||||
amount:
|
||||
type: "integer"
|
||||
format: "int64"
|
||||
budgetId:
|
||||
type: "string"
|
||||
expense:
|
||||
type: "boolean"
|
||||
archived:
|
||||
type: "boolean"
|
||||
UserResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
id:
|
||||
type: "string"
|
||||
username:
|
||||
type: "string"
|
||||
email:
|
||||
type: "string"
|
||||
SessionResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
userId:
|
||||
type: "string"
|
||||
token:
|
||||
type: "string"
|
||||
expiration:
|
||||
type: "string"
|
||||
BudgetResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
id:
|
||||
type: "string"
|
||||
name:
|
||||
type: "string"
|
||||
description:
|
||||
type: "string"
|
||||
TransactionResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
id:
|
||||
type: "string"
|
||||
title:
|
||||
type: "string"
|
||||
description:
|
||||
type: "string"
|
||||
date:
|
||||
type: "string"
|
||||
amount:
|
||||
type: "integer"
|
||||
format: "int64"
|
||||
expense:
|
||||
type: "boolean"
|
||||
budgetId:
|
||||
type: "string"
|
||||
categoryId:
|
||||
type: "string"
|
||||
createdBy:
|
||||
type: "string"
|
||||
BalanceResponse:
|
||||
type: "object"
|
||||
properties:
|
||||
balance:
|
||||
type: "integer"
|
||||
format: "int64"
|
|
@ -1,356 +0,0 @@
|
|||
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.FakeRecurringTransactionRepository
|
||||
import com.wbrawner.twigs.test.helpers.repository.FakeTransactionRepository
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.time.*
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.time.temporal.TemporalUnit
|
||||
import java.util.*
|
||||
|
||||
class RecurringTransactionProcessingJobTest {
|
||||
private lateinit var recurringTransactionRepository: RecurringTransactionRepository
|
||||
private lateinit var transactionRepository: TransactionRepository
|
||||
private lateinit var job: RecurringTransactionProcessingJob
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
recurringTransactionRepository = FakeRecurringTransactionRepository()
|
||||
transactionRepository = FakeTransactionRepository()
|
||||
job = RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are created every day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Daily transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Daily(1, Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 3)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(3, createdTransactions.size)
|
||||
assertEquals("1970-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-01-02T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-01-03T09:00:00Z", createdTransactions[2].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are only created once per day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Daily transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Daily(1, Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 72, ChronoUnit.HOURS)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(3, createdTransactions.size)
|
||||
assertEquals("1970-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-01-02T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-01-03T09:00:00Z", createdTransactions[2].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `daily transactions are created every other day`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Daily transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Daily(2, Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 3)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(2, createdTransactions.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `weekly transactions are created every thursday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Weekly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Weekly(1, setOf(DayOfWeek.THURSDAY), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 28)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-01-08T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-01-15T09:00:00Z", createdTransactions[2].date.toString())
|
||||
assertEquals("1970-01-22T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `weekly transactions are created every third thursday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Weekly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Weekly(3, setOf(DayOfWeek.THURSDAY), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 28)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(2, createdTransactions.size)
|
||||
assertEquals("1970-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-01-22T09:00:00Z", createdTransactions[1].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 1st of month`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(1, DayOfMonth.day(1), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 90)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(3, createdTransactions.size)
|
||||
assertEquals("1970-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-02-01T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-03-01T09:00:00Z", createdTransactions[2].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every last day of month when greater than max days in month`() =
|
||||
runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(1, DayOfMonth.day(31), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 120)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-01-31T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-02-28T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-03-31T09:00:00Z", createdTransactions[2].date.toString())
|
||||
assertEquals("1970-04-30T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 6 months`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(6, DayOfMonth.day(15), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 197)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(2, createdTransactions.size)
|
||||
assertEquals("1970-01-15T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-07-15T09:00:00Z", createdTransactions[1].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every 2nd tuesday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(
|
||||
1,
|
||||
DayOfMonth.positionalDayOfWeek(Position.SECOND, DayOfWeek.TUESDAY),
|
||||
Time(9, 0, 0)
|
||||
),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 120)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-01-13T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-02-10T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-03-10T09:00:00Z", createdTransactions[2].date.toString())
|
||||
assertEquals("1970-04-14T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created every last friday`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(
|
||||
1,
|
||||
DayOfMonth.positionalDayOfWeek(Position.LAST, DayOfWeek.FRIDAY),
|
||||
Time(9, 0, 0)
|
||||
),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 120)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-01-30T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1970-02-27T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1970-03-27T09:00:00Z", createdTransactions[2].date.toString())
|
||||
assertEquals("1970-04-24T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `monthly transactions are created in the new year`() = runTest {
|
||||
val start = Instant.parse("1971-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Monthly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Monthly(
|
||||
1,
|
||||
DayOfMonth.day(1),
|
||||
Time(9, 0, 0)
|
||||
),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId",
|
||||
lastRun = Instant.parse("1970-12-01T09:00:00Z")
|
||||
)
|
||||
)
|
||||
loopFor(start, 1)
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(1, createdTransactions.size)
|
||||
assertEquals("1971-01-01T09:00:00Z", createdTransactions[0].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every march 31st`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Yearly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Yearly(1, MonthDay.of(3, 31), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 1460) // 4 years from Jan 1, 1970
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-03-31T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1971-03-31T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1972-03-31T09:00:00Z", createdTransactions[2].date.toString()) // 1972 was a leap year
|
||||
assertEquals("1973-03-31T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every other march 31st`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Yearly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Yearly(2, MonthDay.of(3, 31), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 1460) // 4 years from Jan 1, 1970
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(2, createdTransactions.size)
|
||||
assertEquals("1970-03-31T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1972-03-31T09:00:00Z", createdTransactions[1].date.toString()) // 1972 was a leap year
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `yearly transactions are created every february 29th`() = runTest {
|
||||
val start = Instant.parse("1970-01-01T00:00:00Z")
|
||||
recurringTransactionRepository.save(
|
||||
RecurringTransaction(
|
||||
title = "Yearly transaction",
|
||||
amount = 123,
|
||||
frequency = Frequency.Yearly(1, MonthDay.of(2, 29), Time(9, 0, 0)),
|
||||
expense = true,
|
||||
start = start,
|
||||
createdBy = "tester",
|
||||
budgetId = "budgetId"
|
||||
)
|
||||
)
|
||||
loopFor(start, 1460) // 4 years from Jan 1, 1970
|
||||
val createdTransactions = transactionRepository.findAll()
|
||||
assertEquals(4, createdTransactions.size)
|
||||
assertEquals("1970-02-28T09:00:00Z", createdTransactions[0].date.toString())
|
||||
assertEquals("1971-02-28T09:00:00Z", createdTransactions[1].date.toString())
|
||||
assertEquals("1972-02-29T09:00:00Z", createdTransactions[2].date.toString()) // 1972 was a leap year
|
||||
assertEquals("1973-02-28T09:00:00Z", createdTransactions[3].date.toString())
|
||||
}
|
||||
|
||||
private suspend fun loopFor(start: Instant, count: Int, timeUnit: TemporalUnit = ChronoUnit.DAYS) {
|
||||
if (count == 0) return
|
||||
val maxDays = GregorianCalendar.from(ZonedDateTime.ofInstant(start, ZoneId.of("UTC")))
|
||||
.getActualMaximum(Calendar.DAY_OF_MONTH)
|
||||
job.createTransactions(start, maxDays)
|
||||
loopFor(start.plus(1, timeUnit), count - 1, timeUnit)
|
||||
}
|
||||
}
|
|
@ -1,82 +0,0 @@
|
|||
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)
|
||||
}
|
||||
}
|
|
@ -1,419 +0,0 @@
|
|||
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)
|
||||
}
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
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()
|
||||
}
|
|
@ -1,249 +0,0 @@
|
|||
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)
|
||||
}
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
import java.net.URI
|
||||
|
||||
buildscript {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath(libs.kotlin.gradle)
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
java
|
||||
alias(libs.plugins.kotlin.jvm)
|
||||
alias(libs.plugins.kotlin.serialization) apply false
|
||||
}
|
||||
|
||||
val javaVersion = JavaVersion.VERSION_17
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
mavenLocal()
|
||||
mavenCentral()
|
||||
maven {
|
||||
url = URI("https://repo.maven.apache.org/maven2")
|
||||
}
|
||||
}
|
||||
group = "com.wbrawner"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
tasks.withType<JavaCompile> {
|
||||
sourceCompatibility = javaVersion.majorVersion
|
||||
targetCompatibility = javaVersion.majorVersion
|
||||
}
|
||||
tasks.withType<KotlinCompile> {
|
||||
kotlinOptions.jvmTarget = javaVersion.majorVersion
|
||||
}
|
||||
}
|
1
core/.gitignore
vendored
1
core/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,15 +0,0 @@
|
|||
plugins {
|
||||
`java-library`
|
||||
kotlin("jvm")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(libs.ktor.server.auth)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
|
||||
interface EmailService {
|
||||
fun sendPasswordResetEmail(token: PasswordResetToken, to: String)
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
interface Identifiable {
|
||||
val id: String
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
interface Logger {
|
||||
fun log(message: String)
|
||||
}
|
|
@ -1,62 +0,0 @@
|
|||
package com.wbrawner.twigs
|
||||
|
||||
import com.wbrawner.twigs.model.Frequency
|
||||
import java.time.Instant
|
||||
import java.time.format.DateTimeParseException
|
||||
import java.util.*
|
||||
|
||||
private val CALENDAR_FIELDS = intArrayOf(
|
||||
Calendar.MILLISECOND,
|
||||
Calendar.SECOND,
|
||||
Calendar.MINUTE,
|
||||
Calendar.HOUR_OF_DAY,
|
||||
Calendar.DATE
|
||||
)
|
||||
|
||||
val firstOfMonth: Instant
|
||||
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||
for (calField in CALENDAR_FIELDS) {
|
||||
set(calField, getActualMinimum(calField))
|
||||
}
|
||||
toInstant()
|
||||
}
|
||||
|
||||
val endOfMonth: Instant
|
||||
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||
for (calField in CALENDAR_FIELDS) {
|
||||
set(calField, getActualMaximum(calField))
|
||||
}
|
||||
toInstant()
|
||||
}
|
||||
|
||||
val twoWeeksFromNow: Instant
|
||||
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||
add(Calendar.DATE, 14)
|
||||
toInstant()
|
||||
}
|
||||
|
||||
val tomorrow: Instant
|
||||
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||
add(Calendar.DATE, 1)
|
||||
toInstant()
|
||||
}
|
||||
|
||||
private const val CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
||||
|
||||
fun randomString(length: Int = 32): String {
|
||||
val id = StringBuilder()
|
||||
for (i in 0 until length) {
|
||||
id.append(CHARACTERS.random())
|
||||
}
|
||||
return id.toString()
|
||||
}
|
||||
|
||||
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)
|
|
@ -1,11 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
|
||||
data class Budget(
|
||||
override val id: String = randomString(),
|
||||
var name: String? = null,
|
||||
var description: String? = null,
|
||||
var currencyCode: String? = "USD",
|
||||
) : Identifiable
|
|
@ -1,14 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
|
||||
data class Category(
|
||||
override val id: String = randomString(),
|
||||
val title: String,
|
||||
val amount: Long,
|
||||
val budgetId: String,
|
||||
val description: String? = null,
|
||||
val expense: Boolean = true,
|
||||
val archived: Boolean = false
|
||||
) : Identifiable
|
|
@ -1,12 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
import com.wbrawner.twigs.tomorrow
|
||||
import java.time.Instant
|
||||
|
||||
data class PasswordResetToken(
|
||||
override val id: String = randomString(),
|
||||
val userId: String = "",
|
||||
var expiration: Instant = tomorrow
|
||||
) : Identifiable
|
|
@ -1,197 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
import java.time.DayOfWeek
|
||||
import java.time.Instant
|
||||
import java.time.MonthDay
|
||||
|
||||
data class RecurringTransaction(
|
||||
override val id: String = randomString(),
|
||||
val title: String,
|
||||
val description: String? = null,
|
||||
val frequency: Frequency,
|
||||
val start: Instant,
|
||||
val finish: Instant? = null,
|
||||
val amount: Long,
|
||||
val expense: Boolean,
|
||||
val createdBy: String,
|
||||
val categoryId: String? = null,
|
||||
val budgetId: String,
|
||||
val lastRun: Instant? = null
|
||||
) : Identifiable {
|
||||
fun toTransaction(now: Instant = Instant.now()): Transaction = Transaction(
|
||||
title = title,
|
||||
description = description,
|
||||
date = frequency.instant(now),
|
||||
amount = amount,
|
||||
expense = expense,
|
||||
createdBy = createdBy,
|
||||
categoryId = categoryId,
|
||||
budgetId = budgetId
|
||||
)
|
||||
}
|
||||
|
||||
sealed class Frequency {
|
||||
abstract val count: Int
|
||||
abstract val time: Time
|
||||
|
||||
data class Daily(override val count: Int, override val time: Time) : Frequency() {
|
||||
override fun toString(): String = "D;$count;$time"
|
||||
|
||||
companion object {
|
||||
fun parse(s: String): Daily {
|
||||
require(s[0] == 'D') { "Invalid format for Daily: $s" }
|
||||
return with(s.split(';')) {
|
||||
Daily(
|
||||
get(1).toInt(),
|
||||
Time.parse(get(2))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Weekly(override val count: Int, val daysOfWeek: Set<DayOfWeek>, override val time: Time) : Frequency() {
|
||||
override fun toString(): String = "W;$count;${daysOfWeek.joinToString(",")};$time"
|
||||
companion object {
|
||||
fun parse(s: String): Weekly {
|
||||
require(s[0] == 'W') { "Invalid format for Weekly: $s" }
|
||||
return with(s.split(';')) {
|
||||
Weekly(
|
||||
get(1).toInt(),
|
||||
get(2).split(',').map { DayOfWeek.valueOf(it) }.toSet(),
|
||||
Time.parse(get(3))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Monthly(
|
||||
override val count: Int,
|
||||
val dayOfMonth: DayOfMonth,
|
||||
override val time: Time
|
||||
) : Frequency() {
|
||||
override fun toString(): String = "M;$count;$dayOfMonth;$time"
|
||||
companion object {
|
||||
fun parse(s: String): Monthly {
|
||||
require(s[0] == 'M') { "Invalid format for Monthly: $s" }
|
||||
return with(s.split(';')) {
|
||||
Monthly(
|
||||
get(1).toInt(),
|
||||
DayOfMonth.parse(get(2)),
|
||||
Time.parse(get(3))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Yearly(override val count: Int, val dayOfYear: MonthDay, override val time: Time) : Frequency() {
|
||||
override fun toString(): String = "Y;$count;%02d-%02d;$time".format(dayOfYear.monthValue, dayOfYear.dayOfMonth)
|
||||
companion object {
|
||||
fun parse(s: String): Yearly {
|
||||
require(s[0] == 'Y') { "Invalid format for Yearly: $s" }
|
||||
return with(s.split(';')) {
|
||||
Yearly(
|
||||
get(1).toInt(),
|
||||
with(get(2).split("-")) {
|
||||
MonthDay.of(get(0).toInt(), get(1).toInt())
|
||||
},
|
||||
Time.parse(get(3))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun instant(now: Instant): Instant = Instant.parse(now.toString().split("T")[0] + "T" + time.toString() + "Z")
|
||||
|
||||
companion object {
|
||||
fun parse(s: String): Frequency = when (s[0]) {
|
||||
'D' -> Daily.parse(s)
|
||||
'W' -> Weekly.parse(s)
|
||||
'M' -> Monthly.parse(s)
|
||||
'Y' -> Yearly.parse(s)
|
||||
else -> throw IllegalArgumentException("Invalid frequency format: $s")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class Time(val hours: Int, val minutes: Int, val seconds: Int) {
|
||||
override fun toString(): String {
|
||||
val s = StringBuilder()
|
||||
if (hours < 10) {
|
||||
s.append("0")
|
||||
}
|
||||
s.append(hours)
|
||||
s.append(":")
|
||||
if (minutes < 10) {
|
||||
s.append("0")
|
||||
}
|
||||
s.append(minutes)
|
||||
s.append(":")
|
||||
if (seconds < 10) {
|
||||
s.append("0")
|
||||
}
|
||||
s.append(seconds)
|
||||
return s.toString()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun parse(s: String): Time {
|
||||
require(s.length < 9) { "Invalid time format: $s. Time should be formatted as HH:mm:ss" }
|
||||
require(s[2] == ':') { "Invalid time format: $s. Time should be formatted as HH:mm:ss" }
|
||||
require(s[5] == ':') { "Invalid time format: $s. Time should be formatted as HH:mm:ss" }
|
||||
return Time(
|
||||
s.substring(0, 2).toInt(),
|
||||
s.substring(3, 5).toInt(),
|
||||
s.substring(7).toInt(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DayOfMonth private constructor(
|
||||
val day: Int? = null,
|
||||
val positionalDayOfWeek: PositionalDayOfWeek? = null
|
||||
) {
|
||||
override fun toString() = day?.let { "DAY-${it}" } ?: positionalDayOfWeek!!.toString()
|
||||
|
||||
companion object {
|
||||
fun day(day: Int): DayOfMonth {
|
||||
require(day in 1..31) { "Day out of range: $day" }
|
||||
return DayOfMonth(day = day)
|
||||
}
|
||||
|
||||
fun positionalDayOfWeek(position: Position, dayOfWeek: DayOfWeek): DayOfMonth {
|
||||
return DayOfMonth(positionalDayOfWeek = PositionalDayOfWeek(position, dayOfWeek))
|
||||
}
|
||||
|
||||
fun parse(s: String): DayOfMonth = with(s.split("-")) {
|
||||
when (size) {
|
||||
2 -> when (first()) {
|
||||
"DAY" -> day(get(1).toInt())
|
||||
else -> positionalDayOfWeek(
|
||||
Position.valueOf(first()),
|
||||
DayOfWeek.valueOf(get(1))
|
||||
)
|
||||
}
|
||||
else -> throw IllegalArgumentException("Failed to parse string $s")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class PositionalDayOfWeek(val position: Position, val dayOfWeek: DayOfWeek) {
|
||||
override fun toString(): String = "${position.name}-${dayOfWeek.name}"
|
||||
}
|
||||
}
|
||||
|
||||
enum class Position {
|
||||
FIRST,
|
||||
SECOND,
|
||||
THIRD,
|
||||
FOURTH,
|
||||
LAST
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
import com.wbrawner.twigs.twoWeeksFromNow
|
||||
import io.ktor.server.auth.*
|
||||
import java.time.Instant
|
||||
|
||||
open class Session(
|
||||
override val id: String = randomString(),
|
||||
val userId: String = "",
|
||||
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)
|
|
@ -1,17 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
import java.time.Instant
|
||||
|
||||
data class Transaction(
|
||||
override val id: String = randomString(),
|
||||
val title: String,
|
||||
val description: String? = null,
|
||||
val date: Instant,
|
||||
val amount: Long,
|
||||
val expense: Boolean,
|
||||
val createdBy: String,
|
||||
val categoryId: String? = null,
|
||||
val budgetId: String
|
||||
) : Identifiable
|
|
@ -1,44 +0,0 @@
|
|||
package com.wbrawner.twigs.model
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.randomString
|
||||
import io.ktor.server.auth.*
|
||||
|
||||
data class User(
|
||||
override val id: String = randomString(),
|
||||
val name: String = "",
|
||||
val password: String = "",
|
||||
val email: String? = null
|
||||
) : Principal, Identifiable
|
||||
|
||||
enum class Permission {
|
||||
/**
|
||||
* The user can read the content but cannot make any modifications.
|
||||
*/
|
||||
READ,
|
||||
|
||||
/**
|
||||
* The user can read and write the content but cannot make any modifications to the container of the content.
|
||||
*/
|
||||
WRITE,
|
||||
|
||||
/**
|
||||
* The user can read and write the content, and make modifications to the container of the content including things like name, description, and other users' permissions (with the exception of the owner user, whose role can never be removed by a user with only MANAGE permissions).
|
||||
*/
|
||||
MANAGE,
|
||||
|
||||
/**
|
||||
* The user has complete control over the resource. There can only be a single owner user at any given time.
|
||||
*/
|
||||
OWNER;
|
||||
|
||||
fun isAtLeast(wanted: Permission): Boolean {
|
||||
return ordinal >= wanted.ordinal
|
||||
}
|
||||
}
|
||||
|
||||
data class UserPermission(
|
||||
val budgetId: String,
|
||||
val userId: String,
|
||||
val permission: Permission = Permission.READ
|
||||
)
|
1
db/.gitignore
vendored
1
db/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,21 +0,0 @@
|
|||
plugins {
|
||||
kotlin("jvm")
|
||||
`java-library`
|
||||
}
|
||||
|
||||
val ktorVersion: String by rootProject.extra
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(project(":storage"))
|
||||
runtimeOnly(libs.postgres)
|
||||
runtimeOnly(libs.sqlite)
|
||||
api(libs.hikari)
|
||||
implementation(libs.logback)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
data class DatabaseMetadata(
|
||||
val version: Int = 0,
|
||||
val salt: String = ""
|
||||
)
|
|
@ -1,31 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
import java.sql.ResultSet
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcBudgetRepository(dataSource: DataSource) : JdbcRepository<Budget, JdbcBudgetRepository.Fields>(dataSource),
|
||||
BudgetRepository {
|
||||
override val tableName: String = TABLE_BUDGET
|
||||
override val fields: Map<Fields, (Budget) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun ResultSet.toEntity(): Budget = Budget(
|
||||
id = getString(ID),
|
||||
name = getString(Fields.NAME.name.lowercase()),
|
||||
description = getString(Fields.DESCRIPTION.name.lowercase()),
|
||||
currencyCode = getString(Fields.CURRENCY_CODE.name.lowercase())
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (Budget) -> Any?) {
|
||||
NAME({ it.name }),
|
||||
DESCRIPTION({ it.description }),
|
||||
CURRENCY_CODE({ it.currencyCode })
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_BUDGET = "budgets"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import com.wbrawner.twigs.storage.CategoryRepository
|
||||
import java.sql.ResultSet
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcCategoryRepository(dataSource: DataSource) :
|
||||
JdbcRepository<Category, JdbcCategoryRepository.Fields>(dataSource), CategoryRepository {
|
||||
override val tableName: String = TABLE_CATEGORY
|
||||
override val fields: Map<Fields, (Category) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun findAll(
|
||||
budgetIds: List<String>,
|
||||
ids: List<String>?,
|
||||
expense: Boolean?,
|
||||
archived: Boolean?
|
||||
): List<Category> = dataSource.connection.use { conn ->
|
||||
if (budgetIds.isEmpty()) {
|
||||
throw Error("budgetIds cannot be empty")
|
||||
}
|
||||
val sql =
|
||||
StringBuilder("SELECT * FROM $tableName WHERE ${Fields.BUDGET_ID.name.lowercase()} in (${budgetIds.questionMarks()})")
|
||||
val params = mutableListOf<Any?>()
|
||||
params.addAll(budgetIds)
|
||||
ids?.let {
|
||||
sql.append(" AND $ID IN (${it.questionMarks()})")
|
||||
params.addAll(it)
|
||||
}
|
||||
expense?.let {
|
||||
sql.append(" AND ${Fields.EXPENSE.name.lowercase()} = ?")
|
||||
params.add(it)
|
||||
}
|
||||
archived?.let {
|
||||
sql.append(" AND ${Fields.ARCHIVED.name.lowercase()} = ?")
|
||||
params.add(it)
|
||||
}
|
||||
sql.append(" ORDER BY ${Fields.TITLE.name.lowercase()} ASC")
|
||||
conn.executeQuery(sql.toString(), params)
|
||||
}
|
||||
|
||||
override fun ResultSet.toEntity(): Category = Category(
|
||||
id = getString(ID),
|
||||
title = getString(Fields.TITLE.name.lowercase()),
|
||||
description = getString(Fields.DESCRIPTION.name.lowercase()),
|
||||
amount = getLong(Fields.AMOUNT.name.lowercase()),
|
||||
expense = getBoolean(Fields.EXPENSE.name.lowercase()),
|
||||
archived = getBoolean(Fields.ARCHIVED.name.lowercase()),
|
||||
budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (Category) -> Any?) {
|
||||
TITLE({ it.title }),
|
||||
DESCRIPTION({ it.description }),
|
||||
AMOUNT({ it.amount }),
|
||||
EXPENSE({ it.expense }),
|
||||
ARCHIVED({ it.archived }),
|
||||
BUDGET_ID({ it.budgetId }),
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_CATEGORY = "categories"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.storage.PasswordResetRepository
|
||||
import java.sql.ResultSet
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcPasswordResetRepository(dataSource: DataSource) :
|
||||
JdbcRepository<PasswordResetToken, JdbcPasswordResetRepository.Fields>(dataSource),
|
||||
PasswordResetRepository {
|
||||
override val tableName: String = TABLE_USER
|
||||
override val fields: Map<Fields, (PasswordResetToken) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun ResultSet.toEntity(): PasswordResetToken = PasswordResetToken(
|
||||
id = getString(ID),
|
||||
userId = getString(Fields.USER_ID.name.lowercase()),
|
||||
expiration = getInstant(Fields.EXPIRATION.name.lowercase())!!
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (PasswordResetToken) -> Any?) {
|
||||
USER_ID({ it.userId }),
|
||||
EXPIRATION({ it.expiration })
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_USER = "password_reset_tokens"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
import com.wbrawner.twigs.storage.PermissionRepository
|
||||
import java.sql.ResultSet
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcPermissionRepository(dataSource: DataSource) :
|
||||
JdbcRepository<UserPermission, JdbcPermissionRepository.Fields>(dataSource), PermissionRepository {
|
||||
override val tableName: String = TABLE_PERMISSIONS
|
||||
override val fields: Map<Fields, (UserPermission) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> =
|
||||
listOf(Fields.USER_ID.name.lowercase(), Fields.BUDGET_ID.name.lowercase())
|
||||
|
||||
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")
|
||||
}
|
||||
val sql = StringBuilder("SELECT * FROM $tableName")
|
||||
val params = mutableListOf<String>()
|
||||
budgetIds?.let {
|
||||
sql.append(" WHERE ${Fields.BUDGET_ID.name.lowercase()} IN (${it.questionMarks()})")
|
||||
params.addAll(it)
|
||||
}
|
||||
userId?.let {
|
||||
sql.append(if (params.isEmpty()) " WHERE " else " AND ")
|
||||
sql.append("${Fields.USER_ID.name.lowercase()} = ?")
|
||||
params.add(it)
|
||||
}
|
||||
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()),
|
||||
permission = Permission.valueOf(getString(Fields.PERMISSION.name.lowercase()))
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (UserPermission) -> Any?) {
|
||||
BUDGET_ID(
|
||||
{ it.budgetId }),
|
||||
USER_ID(
|
||||
{ it.userId }),
|
||||
PERMISSION(
|
||||
{ it.permission })
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_PERMISSIONS = "user_permissions"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.asFrequency
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import com.wbrawner.twigs.storage.RecurringTransactionRepository
|
||||
import java.sql.ResultSet
|
||||
import java.time.Instant
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcRecurringTransactionRepository(dataSource: DataSource) :
|
||||
JdbcRepository<RecurringTransaction, JdbcRecurringTransactionRepository.Fields>(dataSource),
|
||||
RecurringTransactionRepository {
|
||||
override val tableName: String = TABLE_RECURRING_TRANSACTION
|
||||
override val fields: Map<Fields, (RecurringTransaction) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override suspend fun findAll(now: Instant): List<RecurringTransaction> = dataSource.connection.use { conn ->
|
||||
conn.executeQuery("SELECT * FROM $tableName WHERE ${Fields.START.name.lowercase()} < ? AND (${Fields.FINISH.name.lowercase()} IS NULL OR ${Fields.FINISH.name.lowercase()} > ?)", listOf(now, now))
|
||||
}
|
||||
|
||||
override suspend fun findAll(budgetId: String): List<RecurringTransaction> = dataSource.connection.use { conn ->
|
||||
if (budgetId.isBlank()) throw IllegalArgumentException("budgetId cannot be null")
|
||||
conn.executeQuery("SELECT * FROM $tableName WHERE ${Fields.BUDGET_ID.name.lowercase()} = ?", listOf(budgetId))
|
||||
}
|
||||
|
||||
override fun ResultSet.toEntity(): RecurringTransaction = RecurringTransaction(
|
||||
id = getString(ID),
|
||||
title = getString(Fields.TITLE.name.lowercase()),
|
||||
description = getString(Fields.DESCRIPTION.name.lowercase()),
|
||||
frequency = getString(Fields.FREQUENCY.name.lowercase()).asFrequency(),
|
||||
start = getInstant(Fields.START.name.lowercase())!!,
|
||||
finish = getInstant(Fields.FINISH.name.lowercase()),
|
||||
lastRun = getInstant(Fields.LAST_RUN.name.lowercase()),
|
||||
amount = getLong(Fields.AMOUNT.name.lowercase()),
|
||||
expense = getBoolean(Fields.EXPENSE.name.lowercase()),
|
||||
createdBy = getString(Fields.CREATED_BY.name.lowercase()),
|
||||
categoryId = getString(Fields.CATEGORY_ID.name.lowercase()),
|
||||
budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (RecurringTransaction) -> Any?) {
|
||||
TITLE({ it.title }),
|
||||
DESCRIPTION({ it.description }),
|
||||
FREQUENCY({ it.frequency }),
|
||||
START({ it.start }),
|
||||
FINISH({ it.finish }),
|
||||
LAST_RUN({ it.lastRun }),
|
||||
AMOUNT({ it.amount }),
|
||||
EXPENSE({ it.expense }),
|
||||
CREATED_BY({ it.createdBy }),
|
||||
CATEGORY_ID({ it.categoryId }),
|
||||
BUDGET_ID({ it.budgetId }),
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_RECURRING_TRANSACTION = "recurring_transactions"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,122 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.Identifiable
|
||||
import com.wbrawner.twigs.model.Frequency
|
||||
import com.wbrawner.twigs.storage.Repository
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.sql.Connection
|
||||
import java.sql.PreparedStatement
|
||||
import java.sql.ResultSet
|
||||
import java.sql.Types.NULL
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatterBuilder
|
||||
import java.time.temporal.ChronoField
|
||||
import javax.sql.DataSource
|
||||
|
||||
const val ID = "id"
|
||||
|
||||
abstract class JdbcRepository<Entity, Fields : Enum<Fields>>(protected val dataSource: DataSource) :
|
||||
Repository<Entity> {
|
||||
abstract val tableName: String
|
||||
abstract val fields: Map<Fields, (Entity) -> Any?>
|
||||
abstract val conflictFields: Collection<String>
|
||||
val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<Entity> = dataSource.connection.use { conn ->
|
||||
val sql = if (!ids.isNullOrEmpty()) {
|
||||
"SELECT * FROM $tableName WHERE $ID in (${ids.questionMarks()})"
|
||||
} else {
|
||||
"SELECT * FROM $tableName"
|
||||
}
|
||||
conn.executeQuery(sql, ids ?: emptyList())
|
||||
}
|
||||
|
||||
override suspend fun save(item: Entity): Entity = dataSource.connection.use { conn ->
|
||||
val sql = StringBuilder("INSERT INTO $tableName (")
|
||||
val params = mutableListOf<Any?>()
|
||||
if (item is Identifiable) {
|
||||
sql.append("$ID, ")
|
||||
params.add(item.id)
|
||||
}
|
||||
params.addAll(fields.values.map { it(item) })
|
||||
sql.append(fields.keys.joinToString(", ") { it.name.lowercase() })
|
||||
sql.append(") VALUES (")
|
||||
sql.append(params.questionMarks())
|
||||
sql.append(")")
|
||||
if (conflictFields.isNotEmpty()) {
|
||||
sql.append(" ON CONFLICT (")
|
||||
sql.append(conflictFields.joinToString(","))
|
||||
sql.append(") DO UPDATE SET ")
|
||||
sql.append(fields.keys.joinToString(", ") {
|
||||
"${it.name.lowercase()} = EXCLUDED.${it.name.lowercase()}"
|
||||
})
|
||||
}
|
||||
return if (conn.executeUpdate(sql.toString(), params) == 1) {
|
||||
item
|
||||
} else {
|
||||
throw Error("Failed to save entity $item")
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun delete(item: Entity): Boolean = dataSource.connection.use { conn ->
|
||||
if (item !is Identifiable) {
|
||||
throw Error("No suitable delete operation implemented for ${item!!::class.simpleName}")
|
||||
}
|
||||
val statement = conn.prepareStatement("DELETE FROM $tableName WHERE $ID=?")
|
||||
statement.setString(1, item.id)
|
||||
statement.executeUpdate() == 1
|
||||
}
|
||||
|
||||
private fun ResultSet.toEntityList(): List<Entity> {
|
||||
val entities = mutableListOf<Entity>()
|
||||
while (next()) {
|
||||
entities.add(toEntity())
|
||||
}
|
||||
return entities
|
||||
}
|
||||
|
||||
abstract fun ResultSet.toEntity(): Entity
|
||||
|
||||
protected fun Connection.executeQuery(sql: String, params: List<Any?>) = prepareStatement(sql)
|
||||
.apply {
|
||||
logger.debug("QUERY: $sql\nPARAMS: ${params.joinToString(", ")}")
|
||||
}
|
||||
.setParameters(params)
|
||||
.executeQuery()
|
||||
.toEntityList()
|
||||
|
||||
protected fun Connection.executeUpdate(sql: String, params: List<Any?> = emptyList()) = prepareStatement(sql)
|
||||
.apply {
|
||||
logger.debug("QUERY: $sql\nPARAMS: ${params.joinToString(", ")}")
|
||||
}
|
||||
.setParameters(params)
|
||||
.executeUpdate()
|
||||
|
||||
fun PreparedStatement.setParameters(params: Iterable<Any?>): PreparedStatement = apply {
|
||||
params.forEachIndexed { index, param ->
|
||||
when (param) {
|
||||
is Boolean -> setBoolean(index + 1, param)
|
||||
is Instant -> setString(index + 1, dateFormatter.format(param))
|
||||
is Int -> setInt(index + 1, param)
|
||||
is Long -> setLong(index + 1, param)
|
||||
is String -> setString(index + 1, param)
|
||||
is Enum<*> -> setString(index + 1, param.name)
|
||||
is Frequency -> setString(index + 1, param.toString())
|
||||
null -> setNull(index + 1, NULL)
|
||||
else -> throw Error("Unhandled parameter type: ${param.javaClass.name}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun <T> Collection<T>.questionMarks(): String = List(this.size) { "?" }.joinToString(", ")
|
||||
|
||||
|
||||
private val dateFormatter = DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.appendFraction(ChronoField.MILLI_OF_SECOND, 0, 3, true)
|
||||
.toFormatter()
|
||||
.withZone(ZoneId.of("UTC"))
|
||||
|
||||
fun ResultSet.getInstant(column: String): Instant? = getString(column)?.let { dateFormatter.parse(it, Instant::from) }
|
|
@ -1,47 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.storage.SessionRepository
|
||||
import java.sql.ResultSet
|
||||
import java.time.Instant
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcSessionRepository(dataSource: DataSource) : JdbcRepository<Session, JdbcSessionRepository.Fields>(dataSource),
|
||||
SessionRepository {
|
||||
override val tableName: String = TABLE_SESSION
|
||||
override val fields: Map<Fields, (Session) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun findAll(token: String): List<Session> = dataSource.connection.use { conn ->
|
||||
val sql = "SELECT * FROM $tableName WHERE ${Fields.TOKEN.name.lowercase()} = ?"
|
||||
val params = mutableListOf(token)
|
||||
conn.executeQuery(sql, params)
|
||||
}
|
||||
|
||||
override fun deleteExpired() {
|
||||
dataSource.connection.use { conn ->
|
||||
val sql = "DELETE FROM $tableName WHERE ${Fields.TOKEN.name.lowercase()} < ?"
|
||||
val params = mutableListOf(Instant.now())
|
||||
conn.executeUpdate(sql, params)
|
||||
}
|
||||
}
|
||||
|
||||
override fun ResultSet.toEntity(): Session = Session(
|
||||
id = getString(ID),
|
||||
userId = getString(Fields.USER_ID.name.lowercase()),
|
||||
token = getString(Fields.TOKEN.name.lowercase()),
|
||||
expiration = getInstant(Fields.EXPIRATION.name.lowercase())!!,
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (Session) -> Any?) {
|
||||
USER_ID({ it.userId }),
|
||||
TOKEN({ it.token }),
|
||||
EXPIRATION({ it.expiration }),
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_SESSION = "sessions"
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,111 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import com.wbrawner.twigs.storage.TransactionRepository
|
||||
import java.sql.ResultSet
|
||||
import java.time.Instant
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcTransactionRepository(dataSource: DataSource) :
|
||||
JdbcRepository<Transaction, JdbcTransactionRepository.Fields>(dataSource), TransactionRepository {
|
||||
override val tableName: String = TABLE_TRANSACTION
|
||||
override val fields: Map<Fields, (Transaction) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun findAll(
|
||||
ids: List<String>?,
|
||||
budgetIds: List<String>?,
|
||||
categoryIds: List<String>?,
|
||||
expense: Boolean?,
|
||||
from: Instant?,
|
||||
to: Instant?
|
||||
): List<Transaction> = dataSource.connection.use { conn ->
|
||||
val sql = StringBuilder("SELECT * FROM $tableName")
|
||||
val params = mutableListOf<Any?>()
|
||||
fun queryWord(): String = if (params.isEmpty()) " WHERE" else " AND"
|
||||
ids?.let {
|
||||
sql.append("${queryWord()} $ID IN (${it.questionMarks()})")
|
||||
params.addAll(it)
|
||||
}
|
||||
budgetIds?.let {
|
||||
sql.append("${queryWord()} ${Fields.BUDGET_ID.name.lowercase()} IN (${it.questionMarks()})")
|
||||
params.addAll(it)
|
||||
}
|
||||
categoryIds?.let {
|
||||
sql.append("${queryWord()} ${Fields.CATEGORY_ID.name.lowercase()} IN (${it.questionMarks()})")
|
||||
params.addAll(it)
|
||||
}
|
||||
expense?.let {
|
||||
sql.append("${queryWord()} ${Fields.EXPENSE.name.lowercase()} = ?")
|
||||
params.add(it)
|
||||
}
|
||||
from?.let {
|
||||
sql.append("${queryWord()} ${Fields.DATE.name.lowercase()} >= ?")
|
||||
params.add(it)
|
||||
}
|
||||
to?.let {
|
||||
sql.append("${queryWord()} ${Fields.DATE.name.lowercase()} <= ?")
|
||||
params.add(it)
|
||||
}
|
||||
sql.append(" ORDER BY ${Fields.DATE.name.lowercase()} DESC")
|
||||
conn.executeQuery(sql.toString(), params)
|
||||
}
|
||||
|
||||
override fun sumByBudget(budgetId: String, from: Instant, to: Instant): Long =
|
||||
querySum(Fields.BUDGET_ID, budgetId, from, to)
|
||||
|
||||
override fun sumByCategory(categoryId: String, from: Instant, to: Instant): Long =
|
||||
querySum(Fields.CATEGORY_ID, categoryId, from, to)
|
||||
|
||||
private fun querySum(field: Fields, id: String, from: Instant?, to: Instant?): Long =
|
||||
dataSource.connection.use { conn ->
|
||||
val sql =
|
||||
StringBuilder("SELECT SUM(${Fields.AMOUNT.name.lowercase()}) FROM $tableName WHERE ${field.name.lowercase()} = ?")
|
||||
val params = mutableListOf<Any?>(id)
|
||||
from?.let {
|
||||
sql.append(" AND ${Fields.DATE.name.lowercase()} >= ?")
|
||||
params.add(it)
|
||||
}
|
||||
to?.let {
|
||||
sql.append(" AND ${Fields.DATE.name.lowercase()} <= ?")
|
||||
params.add(it)
|
||||
}
|
||||
sql.append(" AND ${Fields.EXPENSE.name.lowercase()} = ?")
|
||||
conn.prepareStatement("SELECT (${sql.toString().coalesce()}) - (${sql.toString().coalesce()})")
|
||||
.setParameters(params + false + params + true)
|
||||
.executeQuery()
|
||||
.run {
|
||||
next()
|
||||
getLong(1)
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.coalesce(): String = "COALESCE(($this), 0)"
|
||||
|
||||
override fun ResultSet.toEntity(): Transaction = Transaction(
|
||||
id = getString(ID),
|
||||
title = getString(Fields.TITLE.name.lowercase()),
|
||||
description = getString(Fields.DESCRIPTION.name.lowercase()),
|
||||
date = getInstant(Fields.DATE.name.lowercase())!!,
|
||||
amount = getLong(Fields.AMOUNT.name.lowercase()),
|
||||
expense = getBoolean(Fields.EXPENSE.name.lowercase()),
|
||||
createdBy = getString(Fields.CREATED_BY.name.lowercase()),
|
||||
categoryId = getString(Fields.CATEGORY_ID.name.lowercase()),
|
||||
budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (Transaction) -> Any?) {
|
||||
TITLE({ it.title }),
|
||||
DESCRIPTION({ it.description }),
|
||||
DATE({ it.date }),
|
||||
AMOUNT({ it.amount }),
|
||||
EXPENSE({ it.expense }),
|
||||
CREATED_BY({ it.createdBy }),
|
||||
CATEGORY_ID({ it.categoryId }),
|
||||
BUDGET_ID({ it.budgetId }),
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_TRANSACTION = "transactions"
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.model.User
|
||||
import com.wbrawner.twigs.storage.UserRepository
|
||||
import java.sql.ResultSet
|
||||
import javax.sql.DataSource
|
||||
|
||||
class JdbcUserRepository(dataSource: DataSource) : JdbcRepository<User, JdbcUserRepository.Fields>(dataSource),
|
||||
UserRepository {
|
||||
override val tableName: String = TABLE_USER
|
||||
override val fields: Map<Fields, (User) -> Any?> = Fields.values().associateWith { it.entityField }
|
||||
override val conflictFields: Collection<String> = listOf(ID)
|
||||
|
||||
override fun ResultSet.toEntity(): User = User(
|
||||
id = getString(ID),
|
||||
name = getString(Fields.USERNAME.name.lowercase()),
|
||||
password = getString(Fields.PASSWORD.name.lowercase()),
|
||||
email = getString(Fields.EMAIL.name.lowercase())
|
||||
)
|
||||
|
||||
override fun findAll(nameLike: String): List<User> = dataSource.connection.use { conn ->
|
||||
conn.executeQuery(
|
||||
"SELECT * FROM $tableName WHERE ${Fields.USERNAME.name.lowercase()} LIKE ? || '%'",
|
||||
listOf(nameLike)
|
||||
)
|
||||
}
|
||||
|
||||
override fun findAll(nameOrEmail: String, password: String?): List<User> = dataSource.connection.use { conn ->
|
||||
var sql =
|
||||
"SELECT * FROM $tableName WHERE (${Fields.USERNAME.name.lowercase()} = ? OR ${Fields.EMAIL.name.lowercase()} = ?)"
|
||||
val params = mutableListOf(nameOrEmail, nameOrEmail)
|
||||
password?.let {
|
||||
sql += " AND ${Fields.PASSWORD.name.lowercase()} = ?"
|
||||
params.add(it)
|
||||
}
|
||||
conn.executeQuery(sql, params)
|
||||
}
|
||||
|
||||
enum class Fields(val entityField: (User) -> Any?) {
|
||||
USERNAME({ it.name }),
|
||||
PASSWORD({ it.password }),
|
||||
EMAIL({ it.email })
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_USER = "users"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
package com.wbrawner.twigs.db
|
||||
|
||||
import com.wbrawner.twigs.storage.Repository
|
||||
import java.sql.ResultSet
|
||||
import java.sql.SQLException
|
||||
import javax.sql.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()
|
||||
|
||||
override fun runMigration(toVersion: Int) {
|
||||
val queries = MetadataRepository::class.java
|
||||
.getResource("/sql/$toVersion.sql")
|
||||
?.readText()
|
||||
?.split(";")
|
||||
?.filterNot { it.isBlank() }
|
||||
?: throw Error("No migration found for version $toVersion")
|
||||
dataSource.connection.use { conn ->
|
||||
queries.forEach { query ->
|
||||
conn.executeUpdate(query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun delete(item: DatabaseMetadata): Boolean = throw Error("DatabaseMetadata cannot be deleted")
|
||||
|
||||
override suspend fun findAll(ids: List<String>?): List<DatabaseMetadata> = try {
|
||||
super.findAll(null)
|
||||
} catch (e: SQLException) {
|
||||
emptyList()
|
||||
}
|
||||
|
||||
override suspend fun save(item: DatabaseMetadata): DatabaseMetadata = dataSource.connection.use { conn ->
|
||||
conn.executeUpdate("DELETE FROM $tableName", emptyList())
|
||||
super.save(item)
|
||||
}
|
||||
|
||||
override fun ResultSet.toEntity(): DatabaseMetadata = DatabaseMetadata(
|
||||
version = getInt(Fields.VERSION.name.lowercase()),
|
||||
salt = getString(Fields.SALT.name.lowercase())
|
||||
)
|
||||
|
||||
enum class Fields(val entityField: (DatabaseMetadata) -> Any?) {
|
||||
VERSION({ it.version }),
|
||||
SALT({ it.salt }),
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TABLE_METADATA = "twigs_metadata"
|
||||
}
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS budgets (id TEXT PRIMARY KEY, name TEXT NOT NULL, description TEXT DEFAULT NULL, currency_code TEXT DEFAULT NULL);
|
||||
CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL, email TEXT DEFAULT NULL UNIQUE);
|
||||
CREATE TABLE IF NOT EXISTS categories (id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT DEFAULT NULL, amount INTEGER NOT NULL, expense BOOLEAN NOT NULL, archived BOOLEAN NOT NULL, budget_id TEXT NOT NULL, CONSTRAINT fk_budgets FOREIGN KEY (budget_id) REFERENCES budgets (id) ON DELETE CASCADE);
|
||||
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, token TEXT NOT NULL, expiration TIMESTAMP NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS user_permissions ( budget_id TEXT NOT NULL, user_id TEXT NOT NULL, permission TEXT NOT NULL, PRIMARY KEY (budget_id, user_id), CONSTRAINT fk_budgets FOREIGN KEY (budget_id) REFERENCES budgets (id) ON DELETE CASCADE, CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE);
|
||||
CREATE TABLE IF NOT EXISTS transactions (id TEXT PRIMARY KEY, title TEXT NOT NULL, description TEXT DEFAULT NULL, amount INTEGER NOT NULL, date TIMESTAMP NOT NULL, expense BOOLEAN NOT NULL, created_by TEXT NOT NULL, category_id TEXT DEFAULT NULL, budget_id TEXT NOT NULL, CONSTRAINT fk_users FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE CASCADE, CONSTRAINT fk_categories FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE, CONSTRAINT fk_budgets FOREIGN KEY (budget_id) REFERENCES budgets (id) ON DELETE CASCADE);
|
||||
CREATE TABLE IF NOT EXISTS twigs_metadata (version INTEGER NOT NULL, salt VARCHAR(16) NOT NULL);
|
|
@ -1,17 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS recurring_transactions (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT DEFAULT NULL,
|
||||
amount INTEGER NOT NULL,
|
||||
frequency TEXT NOT NULL,
|
||||
start TIMESTAMP NOT NULL,
|
||||
finish TIMESTAMP,
|
||||
last_run TIMESTAMP,
|
||||
expense BOOLEAN NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
category_id TEXT DEFAULT NULL,
|
||||
budget_id TEXT NOT NULL,
|
||||
CONSTRAINT fk_users FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_categories FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_budgets FOREIGN KEY (budget_id) REFERENCES budgets (id) ON DELETE CASCADE
|
||||
);
|
|
@ -1,25 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS password_reset_tokens
|
||||
(
|
||||
id
|
||||
TEXT
|
||||
PRIMARY
|
||||
KEY,
|
||||
user_id
|
||||
TEXT
|
||||
NOT
|
||||
NULL,
|
||||
expiration
|
||||
TIMESTAMP
|
||||
NOT
|
||||
NULL,
|
||||
CONSTRAINT
|
||||
fk_users
|
||||
FOREIGN
|
||||
KEY
|
||||
(
|
||||
user_id
|
||||
) REFERENCES users
|
||||
(
|
||||
id
|
||||
) ON DELETE CASCADE
|
||||
);
|
|
@ -9,12 +9,11 @@ services:
|
|||
- db
|
||||
environment:
|
||||
TWIGS_DB_HOST: db
|
||||
TWIGS_DB_TYPE: postgresql
|
||||
networks:
|
||||
- twigs
|
||||
|
||||
db:
|
||||
image: postgres:17
|
||||
image: postgres:13
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
|
|
|
@ -1,55 +0,0 @@
|
|||
[versions]
|
||||
bcrypt = "0.10.2"
|
||||
hikari = "6.2.1"
|
||||
junit = "5.11.4"
|
||||
kotlin = "2.1.0"
|
||||
kotlinx-coroutines = "1.9.0"
|
||||
ktor = "2.3.13"
|
||||
logback = "1.5.12"
|
||||
mail = "1.6.2"
|
||||
postgres = "42.7.4"
|
||||
shadow = "8.1.1"
|
||||
sqlite = "3.47.1.0"
|
||||
|
||||
[libraries]
|
||||
bcrypt = { module = "at.favre.lib:bcrypt", version.ref = "bcrypt" }
|
||||
hikari = { module = "com.zaxxer:HikariCP", version.ref = "hikari" }
|
||||
junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit" }
|
||||
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" }
|
||||
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" }
|
||||
sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" }
|
||||
|
||||
[bundles]
|
||||
ktor-server = [
|
||||
"ktor-server-call-logging",
|
||||
"ktor-server-cio",
|
||||
"ktor-server-content-negotiation",
|
||||
"ktor-server-core",
|
||||
"ktor-server-cors",
|
||||
"ktor-server-forwarded-headers",
|
||||
"ktor-server-sessions"
|
||||
]
|
||||
|
||||
[plugins]
|
||||
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
|
||||
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
|
||||
shadow = { id = "com.github.johnrengelman.shadow", version.ref = "shadow" }
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
7
gradle/wrapper/gradle-wrapper.properties
vendored
|
@ -1,7 +0,0 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=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
|
252
gradlew
vendored
252
gradlew
vendored
|
@ -1,252 +0,0 @@
|
|||
#!/bin/sh
|
||||
|
||||
#
|
||||
# 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.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# 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 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
|
||||
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
|
||||
|
||||
# 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
|
||||
|
||||
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 ;; #(
|
||||
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
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
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" && ! "$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
|
||||
|
||||
# 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.
|
||||
|
||||
# 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" "$@"
|
94
gradlew.bat
vendored
94
gradlew.bat
vendored
|
@ -1,94 +0,0 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@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
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
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"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
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
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
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
|
||||
|
||||
: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 %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
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!
|
||||
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
|
||||
|
||||
:omega
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
|
||||
}
|
1
service/.gitignore
vendored
1
service/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,19 +0,0 @@
|
|||
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()
|
||||
}
|
|
@ -1,59 +0,0 @@
|
|||
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())
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
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,34 +0,0 @@
|
|||
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
|
||||
|
||||
@Serializable
|
||||
data class BudgetRequest(
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val users: Set<UserPermissionRequest>? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class BudgetResponse(
|
||||
val id: String,
|
||||
val name: String? = null,
|
||||
val description: String? = null,
|
||||
val users: List<UserPermissionResponse>
|
||||
) {
|
||||
constructor(budget: Budget, users: Iterable<UserPermission>) : this(
|
||||
requireNotNull(budget.id),
|
||||
budget.name,
|
||||
budget.description,
|
||||
users.map { userPermission: UserPermission ->
|
||||
UserPermissionResponse(
|
||||
userPermission.userId,
|
||||
userPermission.permission
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
|
@ -1,130 +0,0 @@
|
|||
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,35 +0,0 @@
|
|||
package com.wbrawner.twigs.service.category
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CategoryRequest(
|
||||
val title: String? = null,
|
||||
val description: String? = null,
|
||||
val amount: Long? = null,
|
||||
val budgetId: String? = null,
|
||||
val expense: Boolean? = null,
|
||||
val archived: Boolean? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CategoryResponse(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val description: String?,
|
||||
val amount: Long,
|
||||
val budgetId: String,
|
||||
val expense: Boolean,
|
||||
val archived: Boolean
|
||||
)
|
||||
|
||||
fun Category.asResponse(): CategoryResponse = CategoryResponse(
|
||||
id,
|
||||
title,
|
||||
description,
|
||||
amount,
|
||||
budgetId,
|
||||
expense,
|
||||
archived
|
||||
)
|
|
@ -1,104 +0,0 @@
|
|||
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,47 +0,0 @@
|
|||
package com.wbrawner.twigs.service.recurringtransaction
|
||||
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
@Serializable
|
||||
data class RecurringTransactionRequest(
|
||||
val title: String? = null,
|
||||
val description: String? = null,
|
||||
val amount: Long? = null,
|
||||
val categoryId: String? = null,
|
||||
val expense: Boolean? = null,
|
||||
val budgetId: String? = null,
|
||||
val frequency: String,
|
||||
val start: String? = null,
|
||||
val finish: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class RecurringTransactionResponse(
|
||||
val id: String,
|
||||
val title: String?,
|
||||
val description: String?,
|
||||
val frequency: String,
|
||||
val start: String,
|
||||
val finish: String?,
|
||||
val amount: Long?,
|
||||
val expense: Boolean?,
|
||||
val budgetId: String,
|
||||
val categoryId: String?,
|
||||
val createdBy: String
|
||||
)
|
||||
|
||||
fun RecurringTransaction.asResponse(): RecurringTransactionResponse = RecurringTransactionResponse(
|
||||
id = id,
|
||||
title = title,
|
||||
description = description,
|
||||
frequency = frequency.toString(),
|
||||
start = start.truncatedTo(ChronoUnit.SECONDS).toString(),
|
||||
finish = finish?.truncatedTo(ChronoUnit.SECONDS)?.toString(),
|
||||
amount = amount,
|
||||
expense = expense,
|
||||
budgetId = budgetId,
|
||||
categoryId = categoryId,
|
||||
createdBy = createdBy
|
||||
)
|
|
@ -1,110 +0,0 @@
|
|||
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,44 +0,0 @@
|
|||
package com.wbrawner.twigs.service.transaction
|
||||
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.time.temporal.ChronoUnit
|
||||
|
||||
@Serializable
|
||||
data class TransactionRequest(
|
||||
val title: String? = null,
|
||||
val description: String? = null,
|
||||
val date: String? = null,
|
||||
val amount: Long? = null,
|
||||
val categoryId: String? = null,
|
||||
val expense: Boolean? = null,
|
||||
val budgetId: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TransactionResponse(
|
||||
val id: String,
|
||||
val title: String?,
|
||||
val description: String?,
|
||||
val date: String,
|
||||
val amount: Long?,
|
||||
val expense: Boolean?,
|
||||
val budgetId: String,
|
||||
val categoryId: String?,
|
||||
val createdBy: String
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class BalanceResponse(val balance: Long)
|
||||
|
||||
fun Transaction.asResponse(): TransactionResponse = TransactionResponse(
|
||||
id = id,
|
||||
title = title,
|
||||
description = description,
|
||||
date = date.truncatedTo(ChronoUnit.SECONDS).toString(),
|
||||
amount = amount,
|
||||
expense = expense,
|
||||
budgetId = budgetId,
|
||||
categoryId = categoryId,
|
||||
createdBy = createdBy
|
||||
)
|
|
@ -1,167 +0,0 @@
|
|||
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,54 +0,0 @@
|
|||
package com.wbrawner.twigs.service.user
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
import com.wbrawner.twigs.model.Permission
|
||||
import com.wbrawner.twigs.model.Session
|
||||
import com.wbrawner.twigs.model.User
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class UserRequest(
|
||||
val username: String? = null,
|
||||
val password: String? = null,
|
||||
val email: String? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(val username: String, val password: String)
|
||||
|
||||
@Serializable
|
||||
data class UserResponse(val id: String, val username: String, val email: String?)
|
||||
|
||||
@Serializable
|
||||
data class UserPermissionRequest(
|
||||
val user: String,
|
||||
val permission: Permission = Permission.READ
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class UserPermissionResponse(val user: String, val permission: Permission?)
|
||||
|
||||
@Serializable
|
||||
data class SessionResponse(val userId: String, val token: String, val expiration: String)
|
||||
|
||||
/**
|
||||
* Used to request the password reset email
|
||||
*/
|
||||
@Serializable
|
||||
data class ResetPasswordRequest(val username: String)
|
||||
|
||||
/**
|
||||
* Used to modify the user's password after receiving the password reset email
|
||||
*/
|
||||
@Serializable
|
||||
data class PasswordResetRequest(val token: String, val password: String)
|
||||
|
||||
@Serializable
|
||||
data class PasswordResetTokenResponse(val userId: String, val id: String, val expiration: String)
|
||||
|
||||
fun User.asResponse(): UserResponse = UserResponse(id, name, email)
|
||||
|
||||
fun Session.asResponse(): SessionResponse = SessionResponse(userId, token, expiration.toString())
|
||||
|
||||
fun PasswordResetToken.asResponse(): PasswordResetTokenResponse =
|
||||
PasswordResetTokenResponse(userId, id, expiration.toString())
|
|
@ -1,178 +0,0 @@
|
|||
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,4 +0,0 @@
|
|||
rootProject.name = "twigs"
|
||||
include("core", "api", "app", "storage", "db", "web")
|
||||
include("testhelpers")
|
||||
include("service")
|
17
src/main.rs
Normal file
17
src/main.rs
Normal file
|
@ -0,0 +1,17 @@
|
|||
use std::env;
|
||||
|
||||
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
|
||||
|
||||
async fn pong() -> impl Responder {
|
||||
HttpResponse::Ok().body("PONG")
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let port: u16 = env::var("PORT").map_or(8080, |p| p.parse::<u16>().unwrap_or(8080));
|
||||
|
||||
HttpServer::new(|| App::new().route("/ping", web::get().to(pong)))
|
||||
.bind(("0.0.0.0", port))?
|
||||
.run()
|
||||
.await
|
||||
}
|
1
storage/.gitignore
vendored
1
storage/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,16 +0,0 @@
|
|||
plugins {
|
||||
kotlin("jvm")
|
||||
`java-library`
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
api(project(":core"))
|
||||
api(libs.kotlinx.coroutines.core)
|
||||
testImplementation(libs.junit.jupiter.api)
|
||||
testRuntimeOnly(libs.junit.jupiter.engine)
|
||||
}
|
||||
|
||||
tasks.getByName<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
|
||||
interface BudgetRepository : Repository<Budget>
|
|
@ -1,12 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.Category
|
||||
|
||||
interface CategoryRepository : Repository<Category> {
|
||||
fun findAll(
|
||||
budgetIds: List<String>,
|
||||
ids: List<String>? = null,
|
||||
expense: Boolean? = null,
|
||||
archived: Boolean? = null
|
||||
): List<Category>
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.PasswordResetToken
|
||||
|
||||
interface PasswordResetRepository : Repository<PasswordResetToken> {}
|
|
@ -1,10 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.UserPermission
|
||||
|
||||
interface PermissionRepository : Repository<UserPermission> {
|
||||
suspend fun findAll(
|
||||
budgetIds: List<String>? = null,
|
||||
userId: String? = null
|
||||
): List<UserPermission>
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.RecurringTransaction
|
||||
import java.time.Instant
|
||||
|
||||
interface RecurringTransactionRepository : Repository<RecurringTransaction> {
|
||||
suspend fun findAll(now: Instant): List<RecurringTransaction>
|
||||
suspend fun findAll(budgetId: String): List<RecurringTransaction>
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
/**
|
||||
* Base interface for an entity repository that provides basic CRUD methods
|
||||
*
|
||||
* @param T The type of the object supported by this repository
|
||||
*/
|
||||
interface Repository<T> {
|
||||
suspend fun findAll(ids: List<String>? = null): List<T>
|
||||
suspend fun save(item: T): T
|
||||
suspend fun delete(item: T): Boolean
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.Session
|
||||
|
||||
interface SessionRepository : Repository<Session> {
|
||||
fun findAll(
|
||||
token: String
|
||||
): List<Session>
|
||||
|
||||
fun deleteExpired()
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.Transaction
|
||||
import java.time.Instant
|
||||
|
||||
interface TransactionRepository : Repository<Transaction> {
|
||||
fun findAll(
|
||||
ids: List<String>? = null,
|
||||
budgetIds: List<String>? = null,
|
||||
categoryIds: List<String>? = null,
|
||||
expense: Boolean? = null,
|
||||
from: Instant? = null,
|
||||
to: Instant? = null,
|
||||
): List<Transaction>
|
||||
|
||||
fun sumByBudget(budgetId: String, from: Instant, to: Instant): Long
|
||||
|
||||
fun sumByCategory(categoryId: String, from: Instant, to: Instant): Long
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
package com.wbrawner.twigs.storage
|
||||
|
||||
import com.wbrawner.twigs.model.User
|
||||
|
||||
interface UserRepository : Repository<User> {
|
||||
fun findAll(
|
||||
nameOrEmail: String,
|
||||
password: String? = null
|
||||
): List<User>
|
||||
|
||||
fun findAll(nameLike: String): List<User>
|
||||
}
|
||||
|
||||
fun interface PasswordHasher {
|
||||
fun hash(password: String): String
|
||||
}
|
1
testhelpers/.gitignore
vendored
1
testhelpers/.gitignore
vendored
|
@ -1 +0,0 @@
|
|||
build/
|
|
@ -1,19 +0,0 @@
|
|||
plugins {
|
||||
kotlin("jvm")
|
||||
java
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(kotlin("stdlib"))
|
||||
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()
|
||||
}
|
||||
}
|
|
@ -1,14 +0,0 @@
|
|||
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)
|
|
@ -1,6 +0,0 @@
|
|||
package com.wbrawner.twigs.test.helpers.repository
|
||||
|
||||
import com.wbrawner.twigs.model.Budget
|
||||
import com.wbrawner.twigs.storage.BudgetRepository
|
||||
|
||||
class FakeBudgetRepository : FakeRepository<Budget>(), BudgetRepository
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue