Compare commits
198 commits
recurring-
...
main
Author | SHA1 | Date | |
---|---|---|---|
eb5c69265c | |||
cedfb503ba | |||
e564ba6301 | |||
ff03e8331d | |||
41748200cc | |||
67944d6017 | |||
9537d8b6bc | |||
8d68d54a31 | |||
1e33bedfff | |||
6020fd647f | |||
a9165e9867 | |||
5918e351c2 | |||
c4fb0b3391 | |||
00afb3f4bf | |||
374b2a79b0 | |||
7175036135 | |||
5ae22d6d36 | |||
d04dfa1bd5 | |||
a5039c27b1 | |||
a5600fee0a | |||
ea188430d0 | |||
cbfe0b2131 | |||
58bcd48ea7 | |||
9843046db7 | |||
a737f40398 | |||
84ad21011a | |||
3bb586bf14 | |||
b58cbfc388 | |||
92bb5a4827 | |||
287576f3c2 | |||
14861078c0 | |||
6ab4f20137 | |||
4f2c1f067a | |||
134814c515 | |||
b9e212c2c0 | |||
3434bf099c | |||
5aef4630a6 | |||
d13b784826 | |||
3d5bf4af1f | |||
d1ef0bfb1c | |||
fbc936e2bb | |||
b761256862 | |||
02b60757bb | |||
0ecc077b9d | |||
2d3c987be0 | |||
4b5827b315 | |||
6c96c6f2c2 | |||
0b26bf9240 | |||
a66c934d79 | |||
d5a449c719 | |||
d1d3814839 | |||
d062fa056e | |||
21cc7ff0ce | |||
d391c60f91 | |||
|
2dc415553d | ||
|
960723c6e4 | ||
|
cb8e9ecf7a | ||
|
426a522683 | ||
|
b6dc6693e2 | ||
|
488193bba8 | ||
|
96f563af56 | ||
c60eff2cbb | |||
e92ffd376a | |||
22061e3f4a | |||
955ee0f126 | |||
197fee1033 | |||
f1dc6bbca3 | |||
c4fea5a06f | |||
b1267dd4cf | |||
d8b89bc8d2 | |||
689dbc39e2 | |||
ef1deaf19b | |||
59aa48817a | |||
64e7cb9d52 | |||
5a9b988c63 | |||
961c60a183 | |||
fed06cd155 | |||
e8d3719adc | |||
978de59d36 | |||
7e49dbeb31 | |||
a2579dbd6d | |||
7a8c9c1035 | |||
1e14057dfa | |||
|
040af1ba36 | ||
|
3c4fc35daa | ||
|
e537b1b32a | ||
|
9877d9288b | ||
dfe81b7a2f | |||
76237b331a | |||
5e8337da29 | |||
9a01fb39ec | |||
a460421497 | |||
2b66ea916b | |||
94a373f779 | |||
e4e77c4df7 | |||
bd9c0e5857 | |||
|
f3b1976a0b | ||
|
f90c68ca06 | ||
|
2fc1aebaac | ||
|
be58b72e04 | ||
|
d80d0273bc | ||
|
3c14ebd2bf | ||
|
9a148b8984 | ||
|
16845b3129 | ||
e7d0093ede | |||
|
d480ebc63c | ||
|
45dfa9a681 | ||
b5ee8fffd1 | |||
d3fb723611 | |||
e934ebf4e4 | |||
8a128a1104 | |||
0fe4072a6e | |||
6b9c34d5d1 | |||
4ae19c09c2 | |||
aa96cbbf3a | |||
1060e35019 | |||
4cc3a6c070 | |||
0a99788a2f | |||
589bc18069 | |||
c3a4e94bd4 | |||
f9bf4eed65 | |||
619c243b8f | |||
fcf9bc6cd3 | |||
d02f472e48 | |||
2ae81f7f82 | |||
f9dfbe719d | |||
e86427e152 | |||
a1f4f3a693 | |||
9d42cee5e3 | |||
e10ed36838 | |||
d36b166416 | |||
2f29f5d34a | |||
|
ff7b80a273 | ||
4deccdbd0b | |||
47d7e79d5d | |||
b6b88afdb2 | |||
96b833cb52 | |||
fb2e04f90e | |||
694743e3f2 | |||
1eab86489b | |||
13c4096fe8 | |||
1fa28fb2e1 | |||
615e4640c6 | |||
1d15b116c2 | |||
747aec51ef | |||
225bfc6b00 | |||
b170d632e4 | |||
698051fab1 | |||
909b667c62 | |||
58c6508d0a | |||
cee28c0e1e | |||
3d7a4d9772 | |||
c3df8a252e | |||
1ba8565909 | |||
2a7d674204 | |||
f8c970eb68 | |||
97a6807b84 | |||
d3de43dcd9 | |||
04842b6dba | |||
b6ccae2abe | |||
6b606b86a9 | |||
ab8d213431 | |||
8969a7f2d2 | |||
82939020f7 | |||
1fe62dc410 | |||
4bdcc90746 | |||
58f1b1d373 | |||
3ab7d28741 | |||
f85f2057c6 | |||
6bea66e7a5 | |||
fe65921ac0 | |||
7754bfaae5 | |||
62eb6b0976 | |||
722805f732 | |||
9446b52e3d | |||
a9611eee23 | |||
1ab9af9d17 | |||
5d26ee9af3 | |||
ca28d32aa9 | |||
f2700f7148 | |||
ff70db9280 | |||
2900915842 | |||
4ef2fed502 | |||
9fc3d1ac1c | |||
f6e0157560 | |||
4de09a8f1c | |||
ed1dde49bf | |||
b882d8b089 | |||
c38cdb2621 | |||
7020cc15a5 | |||
6f94dedbe3 | |||
3e33f84416 | |||
bcb58d47d7 | |||
00ffbbe303 | |||
ab73dfcc76 | |||
d7a3398655 | |||
8e6454cb72 | |||
9b3b4fac17 |
220 changed files with 9367 additions and 3409 deletions
47
.forgejo/workflows/docker-image.yml
Normal file
47
.forgejo/workflows/docker-image.yml
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
name: Publish Docker image
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
push_to_registry:
|
||||||
|
name: Push Docker image to Forgejo Packages
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out the repo
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Docker meta
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: |
|
||||||
|
git.wbrawner.com/wbrawner/twigs
|
||||||
|
tags: |
|
||||||
|
type=schedule
|
||||||
|
type=ref,event=branch
|
||||||
|
type=ref,event=pr
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=semver,pattern={{major}}
|
||||||
|
type=sha
|
||||||
|
- name: Set up Docker context
|
||||||
|
run: docker context create builders
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
endpoint: builders
|
||||||
|
- name: Login to Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: git.wbrawner.com
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.FORGEJO_TOKEN }}
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
26
.forgejo/workflows/pull-request.yml
Normal file
26
.forgejo/workflows/pull-request.yml
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
name: Pull request workflow
|
||||||
|
on: pull_request
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Build and Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: https://git.wbrawner.com/actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 17
|
||||||
|
- name: Validate Gradle Wrapper
|
||||||
|
uses: https://git.wbrawner.com/gradle/actions/wrapper-validation@v3
|
||||||
|
- name: Build with Gradle
|
||||||
|
uses: https://git.wbrawner.com/gradle/actions/setup-gradle@v3
|
||||||
|
with:
|
||||||
|
arguments: --stacktrace check
|
||||||
|
- name: Publish JUnit Results
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: Unit Test Results
|
||||||
|
path: "*/build/test-results/test/*.xml"
|
||||||
|
if-no-files-found: error
|
41
.github/workflows/docker-image.yml
vendored
41
.github/workflows/docker-image.yml
vendored
|
@ -1,9 +1,8 @@
|
||||||
name: Publish Docker image
|
name: Publish Docker image
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: main
|
branches:
|
||||||
tags:
|
- main
|
||||||
- '*'
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
push_to_registry:
|
push_to_registry:
|
||||||
|
@ -11,12 +10,36 @@ jobs:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Check out the repo
|
- name: Check out the repo
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
- name: Push to GitHub Packages
|
- name: Docker meta
|
||||||
uses: docker/build-push-action@v1
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
with:
|
with:
|
||||||
|
images: |
|
||||||
|
ghcr.io/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 QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
repository: ${{ github.repository }}/${{ github.event.repository.name }}
|
- name: Build and push
|
||||||
registry: docker.pkg.github.com
|
uses: docker/build-push-action@v6
|
||||||
tag_with_ref: true
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
|
31
.github/workflows/pull-request.yml
vendored
Normal file
31
.github/workflows/pull-request.yml
vendored
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
name: Pull request workflow
|
||||||
|
on: pull_request
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
statuses: write
|
||||||
|
checks: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Build and Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 17
|
||||||
|
- name: Validate Gradle Wrapper
|
||||||
|
uses: gradle/wrapper-validation-action@v3
|
||||||
|
- name: Build with Gradle
|
||||||
|
uses: gradle/gradle-build-action@v3
|
||||||
|
with:
|
||||||
|
arguments: --stacktrace build
|
||||||
|
- name: Publish JUnit Results
|
||||||
|
uses: dorny/test-reporter@v1
|
||||||
|
if: always()
|
||||||
|
with:
|
||||||
|
name: Unit Tests
|
||||||
|
path: "*/build/test-results/test/*.xml"
|
||||||
|
reporter: java-junit
|
||||||
|
fail-on-error: true
|
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -29,3 +29,5 @@ HELP.md
|
||||||
.vscode/
|
.vscode/
|
||||||
.gradle
|
.gradle
|
||||||
*.sql
|
*.sql
|
||||||
|
|
||||||
|
twigs.db
|
661
COPYING
Normal file
661
COPYING
Normal file
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
14
Dockerfile
14
Dockerfile
|
@ -1,4 +1,4 @@
|
||||||
FROM openjdk:14-jdk as builder
|
FROM ibm-semeru-runtimes:open-21-jdk as builder
|
||||||
MAINTAINER William Brawner <me@wbrawner.com>
|
MAINTAINER William Brawner <me@wbrawner.com>
|
||||||
|
|
||||||
RUN groupadd --system --gid 1000 gradle \
|
RUN groupadd --system --gid 1000 gradle \
|
||||||
|
@ -6,10 +6,12 @@ RUN groupadd --system --gid 1000 gradle \
|
||||||
|
|
||||||
COPY --chown=gradle:gradle . /home/gradle/src
|
COPY --chown=gradle:gradle . /home/gradle/src
|
||||||
WORKDIR /home/gradle/src
|
WORKDIR /home/gradle/src
|
||||||
RUN /home/gradle/src/gradlew --console=plain --no-daemon bootJar
|
RUN /home/gradle/src/gradlew --console=plain --no-daemon shadowJar
|
||||||
|
|
||||||
FROM openjdk:14-jdk-slim
|
FROM ibm-semeru-runtimes:open-21-jre
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
COPY --from=builder /home/gradle/src/api/build/libs/api.jar twigs-api.jar
|
RUN groupadd --system --gid 1000 twigs \
|
||||||
CMD /usr/local/openjdk-14/bin/java $JVM_ARGS -jar /twigs-api.jar
|
&& 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
|
||||||
|
|
661
LICENSE
661
LICENSE
|
@ -1,8 +1,661 @@
|
||||||
Copyright 2019 William Patrick Brawner
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
Preamble
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
46
README.md
46
README.md
|
@ -1,24 +1,54 @@
|
||||||
# Twigs Server
|
# Twigs
|
||||||
|
|
||||||
This is the backend application that powers the [Android](https://github.com/wbrawner/twigs-android), [iOS](https://github.com/wbrawner/twigs-ios), and [web](https://github.com/wbrawner/twigs-web) applications for Twigs, a personal finance/budgeting app.
|
Twigs is a personal finance application tailored to individuals and small groups that want robust budgeting features
|
||||||
|
without needing to pay a monthly subscription.
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
- JDK 14 or newer
|
- JDK 17 or newer
|
||||||
- MySQL 5.7 or newer
|
- PostgreSQL 13 or newer
|
||||||
- (optional) Docker
|
- (optional) Docker
|
||||||
|
|
||||||
## Running
|
## Running
|
||||||
|
|
||||||
Prior to running the app, make sure you have a MySQL server running, with a database and user ready to go. To avoid the hassle of figuring out how to get it installed locally, using Docker is recommended, and a sample `docker-compose.yml` file is included in the root of the repository. If you already have a MySQL server running, you can run the app from the command line with gradle:
|
Prior to running the app, make sure you have a PostgreSQL server running, with a database and user ready to go. To avoid
|
||||||
|
the hassle of figuring out how to get it installed locally, using Docker is recommended, and a
|
||||||
|
sample `docker-compose.yml` file is included in the root of the repository. If you already have a PostgreSQL server
|
||||||
|
running, you can run the app from the command line with gradle:
|
||||||
|
|
||||||
./gradlew bootRun
|
./gradlew run
|
||||||
|
|
||||||
By default, twigs will try to connect to the `budget` database on `localhost`, using `budget` as the user and password. To change these values, you can modify the `api/src/main/resources/application.properties` file (but don't commit it!), or better yet, set the appropriate environment variables using the uppercase names and replacing the `.`s with `_`s. For example, to change the `spring.datasource.username` property (the database username), you could set the value in an environment variable called `SPRING_DATASOURCE_USERNAME`.
|
## Configuration
|
||||||
|
|
||||||
|
Some parameters of Twigs can be configured via environment variables:
|
||||||
|
|
||||||
|
| Environment Variable | Default Value | Note |
|
||||||
|
|:--------------------:|:-------------:|:--------------------------------------------------------|
|
||||||
|
| `TWIGS_PORT` | `8080` | Port for web server to listen on |
|
||||||
|
| `TWIGS_DB_HOST` | `localhost` | PostgreSQL server host |
|
||||||
|
| `TWIGS_DB_PORT` | `5432` | PostgreSQL server port |
|
||||||
|
| `TWIGS_DB_NAME` | `twigs` | PostgreSQL database name |
|
||||||
|
| `TWIGS_DB_USER` | `twigs` | PostgreSQL database user |
|
||||||
|
| `TWIGS_DB_PASS` | `twigs` | PostgreSQL database password |
|
||||||
|
| `TWIGS_PW_SALT` | | Salt to use for password, generated if empty or null |
|
||||||
|
| `TWIGS_SMTP_FROM` | | From email address for automated emails sent from Twigs |
|
||||||
|
| `TWIGS_SMTP_HOST` | | SMTP server host for sending emails |
|
||||||
|
| `TWIGS_SMTP_PORT` | | SMTP server port for sending emails |
|
||||||
|
| `TWIGS_SMTP_USER` | | SMTP server username for sending emails |
|
||||||
|
| `TWIGS_SMTP_PASS` | | SMTP server password for sending emails |
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
Building the app is also handled with gradle:
|
Building the app is also handled with gradle:
|
||||||
|
|
||||||
./gradlew bootJar
|
./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,31 +0,0 @@
|
||||||
apply plugin: 'java'
|
|
||||||
apply plugin: 'application'
|
|
||||||
apply plugin: "io.spring.dependency-management"
|
|
||||||
apply plugin: "org.springframework.boot"
|
|
||||||
|
|
||||||
repositories {
|
|
||||||
mavenLocal()
|
|
||||||
mavenCentral()
|
|
||||||
maven {
|
|
||||||
url = "http://repo.maven.apache.org/maven2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
implementation "org.springframework.boot:spring-boot-starter-data-jpa"
|
|
||||||
implementation "org.springframework.boot:spring-boot-starter-security"
|
|
||||||
implementation "org.springframework.session:spring-session-jdbc"
|
|
||||||
implementation "org.springframework.boot:spring-boot-starter-web"
|
|
||||||
runtimeOnly "mysql:mysql-connector-java:8.0.15"
|
|
||||||
testImplementation "org.springframework.boot:spring-boot-starter-test"
|
|
||||||
testImplementation "org.springframework.security:spring-security-test:5.1.5.RELEASE"
|
|
||||||
}
|
|
||||||
|
|
||||||
jar {
|
|
||||||
description = "twigs-server"
|
|
||||||
}
|
|
||||||
|
|
||||||
mainClassName = "com.wbrawner.budgetserver.TwigsServerApplication"
|
|
||||||
|
|
||||||
sourceCompatibility = 14
|
|
||||||
targetCompatibility = 14
|
|
18
api/build.gradle.kts
Normal file
18
api/build.gradle.kts
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
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,13 +0,0 @@
|
||||||
package com.wbrawner.budgetserver;
|
|
||||||
|
|
||||||
public class ErrorResponse {
|
|
||||||
private final String message;
|
|
||||||
|
|
||||||
public ErrorResponse(String message) {
|
|
||||||
this.message = message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getMessage() {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
package com.wbrawner.budgetserver;
|
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
|
||||||
@EnableScheduling
|
|
||||||
public class TwigsServerApplication {
|
|
||||||
public static void main(String[] args) {
|
|
||||||
SpringApplication.run(TwigsServerApplication.class, args);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,66 +0,0 @@
|
||||||
package com.wbrawner.budgetserver;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
|
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.GregorianCalendar;
|
|
||||||
import java.util.Random;
|
|
||||||
|
|
||||||
public final class Utils {
|
|
||||||
private static final int[] CALENDAR_FIELDS = new int[]{
|
|
||||||
Calendar.MILLISECOND,
|
|
||||||
Calendar.SECOND,
|
|
||||||
Calendar.MINUTE,
|
|
||||||
Calendar.HOUR_OF_DAY,
|
|
||||||
Calendar.DATE
|
|
||||||
};
|
|
||||||
|
|
||||||
public static Date getFirstOfMonth() {
|
|
||||||
GregorianCalendar calendar = new GregorianCalendar();
|
|
||||||
for (int field : CALENDAR_FIELDS) {
|
|
||||||
calendar.set(field, calendar.getActualMinimum(field));
|
|
||||||
}
|
|
||||||
return calendar.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Date getEndOfMonth() {
|
|
||||||
GregorianCalendar calendar = new GregorianCalendar();
|
|
||||||
for (int field : CALENDAR_FIELDS) {
|
|
||||||
calendar.set(field, calendar.getActualMaximum(field));
|
|
||||||
}
|
|
||||||
return calendar.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Date twoWeeksFromNow() {
|
|
||||||
GregorianCalendar calendar = new GregorianCalendar();
|
|
||||||
calendar.add(Calendar.DATE, 14);
|
|
||||||
return calendar.getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static User getCurrentUser() {
|
|
||||||
Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
|
||||||
if (user instanceof User) {
|
|
||||||
return (User) user;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
||||||
private static final Random random = new SecureRandom();
|
|
||||||
|
|
||||||
public static String randomString(int length) {
|
|
||||||
StringBuilder id = new StringBuilder();
|
|
||||||
for (int i = 0; i < length; i++) {
|
|
||||||
id.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));
|
|
||||||
}
|
|
||||||
return id.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String randomId() {
|
|
||||||
return randomString(32);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,82 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import com.wbrawner.budgetserver.transaction.Transaction;
|
|
||||||
|
|
||||||
import javax.persistence.*;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.TreeSet;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class Budget {
|
|
||||||
@Id
|
|
||||||
private String id = randomId();
|
|
||||||
private String name;
|
|
||||||
private String description;
|
|
||||||
private String currencyCode;
|
|
||||||
@OneToMany(mappedBy = "budget")
|
|
||||||
private final Set<Transaction> transactions = new TreeSet<>();
|
|
||||||
@OneToMany(mappedBy = "budget")
|
|
||||||
private final Set<Category> categories = new TreeSet<>();
|
|
||||||
@OneToMany(mappedBy = "budget")
|
|
||||||
private final Set<Transaction> users = new HashSet<>();
|
|
||||||
|
|
||||||
public Budget() {}
|
|
||||||
|
|
||||||
public Budget(String name, String description) {
|
|
||||||
this(name, description, "USD");
|
|
||||||
}
|
|
||||||
|
|
||||||
public Budget(String name, String description, String currencyCode) {
|
|
||||||
this.name = name;
|
|
||||||
this.description = description;
|
|
||||||
this.currencyCode = currencyCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(String id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCurrencyCode() {
|
|
||||||
return currencyCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCurrencyCode(String currencyCode) {
|
|
||||||
this.currencyCode = currencyCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<Transaction> getTransactions() {
|
|
||||||
return transactions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<Category> getCategories() {
|
|
||||||
return categories;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<Transaction> getUsers() {
|
|
||||||
return users;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,11 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
public class BudgetBalanceResponse {
|
|
||||||
public final String id;
|
|
||||||
public final long balance;
|
|
||||||
|
|
||||||
public BudgetBalanceResponse(String id, long balance) {
|
|
||||||
this.id = id;
|
|
||||||
this.balance = balance;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,206 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.permission.Permission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRepository;
|
|
||||||
import com.wbrawner.budgetserver.transaction.TransactionRepository;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
import com.wbrawner.budgetserver.user.UserRepository;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Function;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.getCurrentUser;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping(value = "/budgets")
|
|
||||||
@Transactional
|
|
||||||
public class BudgetController {
|
|
||||||
private final BudgetRepository budgetRepository;
|
|
||||||
private final TransactionRepository transactionRepository;
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
private final UserPermissionRepository userPermissionsRepository;
|
|
||||||
private final Logger logger = LoggerFactory.getLogger(BudgetController.class);
|
|
||||||
|
|
||||||
public BudgetController(
|
|
||||||
BudgetRepository budgetRepository,
|
|
||||||
TransactionRepository transactionRepository,
|
|
||||||
UserRepository userRepository,
|
|
||||||
UserPermissionRepository userPermissionsRepository
|
|
||||||
) {
|
|
||||||
this.budgetRepository = budgetRepository;
|
|
||||||
this.transactionRepository = transactionRepository;
|
|
||||||
this.userRepository = userRepository;
|
|
||||||
this.userPermissionsRepository = userPermissionsRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(value = "", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<List<BudgetResponse>> getBudgets(Integer page, Integer count) {
|
|
||||||
User user = getCurrentUser();
|
|
||||||
if (user == null) {
|
|
||||||
return ResponseEntity.status(401).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
List<BudgetResponse> budgets = userPermissionsRepository.findAllByUser(
|
|
||||||
getCurrentUser(),
|
|
||||||
PageRequest.of(
|
|
||||||
page != null ? page : 0,
|
|
||||||
count != null ? count : 1000
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.stream()
|
|
||||||
.map(userPermission -> {
|
|
||||||
Budget budget = userPermission.getBudget();
|
|
||||||
if (budget == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
// Hibernate.initialize(budget);
|
|
||||||
return new BudgetResponse(budget, userPermissionsRepository.findAllByBudget(budget, null));
|
|
||||||
})
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
return ResponseEntity.ok(budgets);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(value = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<BudgetResponse> getBudget(@PathVariable String id) {
|
|
||||||
return getBudgetWithPermission(id, Permission.READ, (budget) ->
|
|
||||||
ResponseEntity.ok(new BudgetResponse(budget, userPermissionsRepository.findAllByBudget(budget, null)))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(value = "/{id}/balance", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<BudgetBalanceResponse> getBudgetBalance(
|
|
||||||
@PathVariable String id,
|
|
||||||
@RequestParam(value = "from", required = false) String from,
|
|
||||||
@RequestParam(value = "to", required = false) String to
|
|
||||||
) {
|
|
||||||
return getBudgetWithPermission(id, Permission.READ, (budget) -> {
|
|
||||||
Instant fromInstant;
|
|
||||||
try {
|
|
||||||
fromInstant = Instant.parse(from);
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (!(e instanceof NullPointerException))
|
|
||||||
logger.error("Failed to parse '" + from + "' to Instant for 'from' parameter", e);
|
|
||||||
fromInstant = Instant.ofEpochSecond(0);
|
|
||||||
}
|
|
||||||
Instant toInstant;
|
|
||||||
try {
|
|
||||||
toInstant = Instant.parse(to);
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (!(e instanceof NullPointerException))
|
|
||||||
logger.error("Failed to parse '" + to + "' to Instant for 'to' parameter", e);
|
|
||||||
toInstant = Instant.now();
|
|
||||||
}
|
|
||||||
var balance = transactionRepository.sumBalanceByBudgetId(budget.getId(), fromInstant, toInstant);
|
|
||||||
return ResponseEntity.ok(new BudgetBalanceResponse(budget.getId(), balance));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(value = "", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<BudgetResponse> newBudget(@RequestBody BudgetRequest request) {
|
|
||||||
final var budget = budgetRepository.save(new Budget(request.name, request.description));
|
|
||||||
var users = request.getUsers()
|
|
||||||
.stream()
|
|
||||||
.map(userPermissionRequest -> {
|
|
||||||
var user = userRepository.findById(userPermissionRequest.getUser()).orElse(null);
|
|
||||||
if (user == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return userPermissionsRepository.save(
|
|
||||||
new UserPermission(budget, user, userPermissionRequest.getPermission())
|
|
||||||
);
|
|
||||||
})
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
var currentUserIncluded = users.stream().anyMatch(userPermission ->
|
|
||||||
userPermission.getUser().getId().equals(getCurrentUser().getId())
|
|
||||||
);
|
|
||||||
if (!currentUserIncluded) {
|
|
||||||
users.add(
|
|
||||||
userPermissionsRepository.save(
|
|
||||||
new UserPermission(budget, getCurrentUser(), Permission.OWNER)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new BudgetResponse(budget, new ArrayList<>(users)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping(value = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<BudgetResponse> updateBudget(@PathVariable String id, @RequestBody BudgetRequest request) {
|
|
||||||
return getBudgetWithPermission(id, Permission.MANAGE, (budget) -> {
|
|
||||||
if (request.name != null) {
|
|
||||||
budget.setName(request.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (request.description != null) {
|
|
||||||
budget.setDescription(request.description);
|
|
||||||
}
|
|
||||||
|
|
||||||
var users = new ArrayList<UserPermission>();
|
|
||||||
if (!request.getUsers().isEmpty()) {
|
|
||||||
request.getUsers().forEach(userPermissionRequest ->
|
|
||||||
userRepository.findById(userPermissionRequest.getUser()).ifPresent(requestedUser ->
|
|
||||||
users.add(userPermissionsRepository.save(
|
|
||||||
new UserPermission(
|
|
||||||
budget,
|
|
||||||
requestedUser,
|
|
||||||
userPermissionRequest.getPermission()
|
|
||||||
)
|
|
||||||
))
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
users.addAll(userPermissionsRepository.findAllByBudget(budget, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok(new BudgetResponse(budgetRepository.save(budget), users));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping(value = "/{id}", produces = {MediaType.TEXT_PLAIN_VALUE})
|
|
||||||
public ResponseEntity<Void> deleteBudget(@PathVariable String id) {
|
|
||||||
return getBudgetWithPermission(id, Permission.MANAGE, (budget) -> {
|
|
||||||
budgetRepository.delete(budget);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private <T> ResponseEntity<T> getBudgetWithPermission(
|
|
||||||
String budgetId,
|
|
||||||
Permission permission,
|
|
||||||
Function<Budget, ResponseEntity<T>> callback
|
|
||||||
) {
|
|
||||||
var user = getCurrentUser();
|
|
||||||
if (user == null) {
|
|
||||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(user, budgetId).orElse(null);
|
|
||||||
if (userPermission == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(permission)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
var budget = userPermission.getBudget();
|
|
||||||
if (budget == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
return callback.apply(budget);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,6 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
public interface BudgetRepository extends PagingAndSortingRepository<Budget, String> {
|
|
||||||
}
|
|
|
@ -1,28 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRequest;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
public class BudgetRequest {
|
|
||||||
public final String name;
|
|
||||||
public final String description;
|
|
||||||
private final Set<UserPermissionRequest> users = new HashSet<>();
|
|
||||||
|
|
||||||
public BudgetRequest() {
|
|
||||||
// Required empty constructor
|
|
||||||
this("", "", Collections.emptySet());
|
|
||||||
}
|
|
||||||
|
|
||||||
public BudgetRequest(String name, String description, Set<UserPermissionRequest> users) {
|
|
||||||
this.name = name;
|
|
||||||
this.description = description;
|
|
||||||
this.users.addAll(users);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Set<UserPermissionRequest> getUsers() {
|
|
||||||
return Set.copyOf(users);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,38 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.budget;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionResponse;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class BudgetResponse {
|
|
||||||
public final String id;
|
|
||||||
public final String name;
|
|
||||||
public final String description;
|
|
||||||
private final List<UserPermissionResponse> users;
|
|
||||||
|
|
||||||
public BudgetResponse(String id, String name, String description, List<UserPermissionResponse> users) {
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
this.description = description;
|
|
||||||
this.users = users;
|
|
||||||
}
|
|
||||||
|
|
||||||
public BudgetResponse(Budget budget, List<UserPermission> users) {
|
|
||||||
this(
|
|
||||||
Objects.requireNonNull(budget.getId()),
|
|
||||||
budget.getName(),
|
|
||||||
budget.getDescription(),
|
|
||||||
users.stream()
|
|
||||||
.map(UserPermissionResponse::new)
|
|
||||||
.collect(Collectors.toList())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<UserPermissionResponse> getUsers() {
|
|
||||||
return List.copyOf(users);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,98 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
|
|
||||||
import javax.persistence.*;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class Category implements Comparable<Category> {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
private String title;
|
|
||||||
private String description;
|
|
||||||
private long amount;
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
@ManyToOne
|
|
||||||
private Budget budget;
|
|
||||||
private boolean expense;
|
|
||||||
@Column(nullable = false, columnDefinition = "boolean default false")
|
|
||||||
private boolean archived;
|
|
||||||
|
|
||||||
public Category() {
|
|
||||||
this(null, null, 0L, null, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Category(
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
Long amount,
|
|
||||||
Budget budget,
|
|
||||||
boolean expense
|
|
||||||
) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.amount = amount;
|
|
||||||
this.budget = budget;
|
|
||||||
this.expense = expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int compareTo(Category other) {
|
|
||||||
return title.compareTo(other.title);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmount(long amount) {
|
|
||||||
this.amount = amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Budget getBudget() {
|
|
||||||
return budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBudget(Budget budget) {
|
|
||||||
this.budget = budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpense(boolean expense) {
|
|
||||||
this.expense = expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isArchived() {
|
|
||||||
return archived;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setArchived(boolean archived) {
|
|
||||||
this.archived = archived;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
public class CategoryBalanceResponse {
|
|
||||||
private final String id;
|
|
||||||
private final long balance;
|
|
||||||
|
|
||||||
public CategoryBalanceResponse(String id, long balance) {
|
|
||||||
this.id = id;
|
|
||||||
this.balance = balance;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getBalance() {
|
|
||||||
return balance;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,166 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.ErrorResponse;
|
|
||||||
import com.wbrawner.budgetserver.permission.Permission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRepository;
|
|
||||||
import com.wbrawner.budgetserver.transaction.TransactionRepository;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.getCurrentUser;
|
|
||||||
import static com.wbrawner.budgetserver.Utils.getFirstOfMonth;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping(path = "/categories")
|
|
||||||
@Transactional
|
|
||||||
class CategoryController {
|
|
||||||
private final CategoryRepository categoryRepository;
|
|
||||||
private final TransactionRepository transactionRepository;
|
|
||||||
private final UserPermissionRepository userPermissionsRepository;
|
|
||||||
|
|
||||||
CategoryController(CategoryRepository categoryRepository,
|
|
||||||
TransactionRepository transactionRepository,
|
|
||||||
UserPermissionRepository userPermissionsRepository) {
|
|
||||||
this.categoryRepository = categoryRepository;
|
|
||||||
this.transactionRepository = transactionRepository;
|
|
||||||
this.userPermissionsRepository = userPermissionsRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<List<CategoryResponse>> getCategories(
|
|
||||||
@RequestParam(name = "budgetIds", required = false) List<String> budgetIds,
|
|
||||||
@RequestParam(name = "isExpense", required = false) Boolean isExpense,
|
|
||||||
@RequestParam(name = "includeArchived", required = false) Boolean includeArchived,
|
|
||||||
@RequestParam(name = "count", required = false) Integer count,
|
|
||||||
@RequestParam(name = "page", required = false) Integer page,
|
|
||||||
@RequestParam(name = "false", required = false) String sortBy,
|
|
||||||
@RequestParam(name = "sortOrder", required = false) Sort.Direction sortOrder
|
|
||||||
) {
|
|
||||||
List<UserPermission> userPermissions;
|
|
||||||
if (budgetIds != null && !budgetIds.isEmpty()) {
|
|
||||||
userPermissions = userPermissionsRepository.findAllByUserAndBudget_IdIn(
|
|
||||||
getCurrentUser(),
|
|
||||||
budgetIds,
|
|
||||||
PageRequest.of(page != null ? page : 0, count != null ? count : 1000)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
userPermissions = userPermissionsRepository.findAllByUser(getCurrentUser(), null);
|
|
||||||
}
|
|
||||||
var budgets = userPermissions.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
var pageRequest = PageRequest.of(
|
|
||||||
Math.min(0, page != null ? page - 1 : 0),
|
|
||||||
count != null ? count : 1000,
|
|
||||||
sortOrder != null ? sortOrder : Sort.Direction.ASC,
|
|
||||||
sortBy != null ? sortBy : "title"
|
|
||||||
);
|
|
||||||
Boolean archived = includeArchived == null || includeArchived == false ? false : null;
|
|
||||||
List<Category> categories = categoryRepository.findAllByBudgetIn(budgets, isExpense, archived, pageRequest);
|
|
||||||
return ResponseEntity.ok(
|
|
||||||
categories.stream()
|
|
||||||
.map(CategoryResponse::new)
|
|
||||||
.collect(Collectors.toList())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<CategoryResponse> getCategory(@PathVariable String id) {
|
|
||||||
var budgets = userPermissionsRepository.findAllByUser(getCurrentUser(), null)
|
|
||||||
.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
var category = categoryRepository.findByBudgetInAndId(budgets, id).orElse(null);
|
|
||||||
if (category == null) return ResponseEntity.notFound().build();
|
|
||||||
return ResponseEntity.ok(new CategoryResponse(category));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/{id}/balance", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<CategoryBalanceResponse> getCategoryBalance(@PathVariable String id) {
|
|
||||||
var budgets = userPermissionsRepository.findAllByUser(getCurrentUser(), null)
|
|
||||||
.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
var category = categoryRepository.findByBudgetInAndId(budgets, id).orElse(null);
|
|
||||||
if (category == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
var sum = transactionRepository.sumBalanceByCategoryId(category.getId(), getFirstOfMonth());
|
|
||||||
return ResponseEntity.ok(new CategoryBalanceResponse(category.getId(), sum));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(path = "", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<Object> newCategory(@RequestBody NewCategoryRequest request) {
|
|
||||||
var userResponse = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), request.getBudgetId())
|
|
||||||
.orElse(null);
|
|
||||||
if (userResponse == null) {
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Invalid budget ID"));
|
|
||||||
}
|
|
||||||
if (userResponse.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
var budget = userResponse.getBudget();
|
|
||||||
return ResponseEntity.ok(new CategoryResponse(categoryRepository.save(new Category(
|
|
||||||
request.getTitle(),
|
|
||||||
request.getDescription(),
|
|
||||||
request.getAmount(),
|
|
||||||
budget,
|
|
||||||
request.getExpense()
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<CategoryResponse> updateCategory(@PathVariable String id, @RequestBody UpdateCategoryRequest request) {
|
|
||||||
var category = categoryRepository.findById(id).orElse(null);
|
|
||||||
if (category == null) return ResponseEntity.notFound().build();
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), category.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
if (request.getTitle() != null) {
|
|
||||||
category.setTitle(request.getTitle());
|
|
||||||
}
|
|
||||||
if (request.getDescription() != null) {
|
|
||||||
category.setDescription(request.getDescription());
|
|
||||||
}
|
|
||||||
if (request.getAmount() != null) {
|
|
||||||
category.setAmount(request.getAmount());
|
|
||||||
}
|
|
||||||
if (request.getExpense() != null) {
|
|
||||||
category.setExpense(request.getExpense());
|
|
||||||
}
|
|
||||||
if (request.getArchived() != null) {
|
|
||||||
category.setArchived(request.getArchived());
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new CategoryResponse(categoryRepository.save(category)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping(path = "/{id}", produces = {MediaType.TEXT_PLAIN_VALUE})
|
|
||||||
ResponseEntity<Void> deleteCategory(@PathVariable String id) {
|
|
||||||
var category = categoryRepository.findById(id).orElse(null);
|
|
||||||
if (category == null) return ResponseEntity.notFound().build();
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), category.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
transactionRepository.findAllByBudgetAndCategory(userPermission.getBudget(), category)
|
|
||||||
.forEach(transaction -> {
|
|
||||||
transaction.setCategory(null);
|
|
||||||
transactionRepository.save(transaction);
|
|
||||||
});
|
|
||||||
categoryRepository.delete(category);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,23 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.jpa.repository.Query;
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface CategoryRepository extends PagingAndSortingRepository<Category, String> {
|
|
||||||
List<Category> findAllByBudget(Budget budget, Pageable pageable);
|
|
||||||
|
|
||||||
@Query("SELECT c FROM Category c where c.budget IN (:budgets) AND (:expense IS NULL OR c.expense = :expense) AND (:archived IS NULL OR c.archived = :archived)")
|
|
||||||
List<Category> findAllByBudgetIn(List<Budget> budgets, Boolean expense, Boolean archived, Pageable pageable);
|
|
||||||
|
|
||||||
Optional<Category> findByBudgetInAndId(List<Budget> budgets, String id);
|
|
||||||
|
|
||||||
Optional<Category> findByBudgetAndId(Budget budget, String id);
|
|
||||||
|
|
||||||
List<Category> findAllByBudgetInAndIdIn(List<Budget> budgets, List<String> ids, Pageable pageable);
|
|
||||||
}
|
|
|
@ -1,63 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
public class CategoryResponse {
|
|
||||||
private final String id;
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final long amount;
|
|
||||||
private final String budgetId;
|
|
||||||
private final boolean expense;
|
|
||||||
private final boolean archived;
|
|
||||||
|
|
||||||
public CategoryResponse(Category category) {
|
|
||||||
this(
|
|
||||||
Objects.requireNonNull(category.getId()),
|
|
||||||
category.getTitle(),
|
|
||||||
category.getDescription(),
|
|
||||||
category.getAmount(),
|
|
||||||
Objects.requireNonNull(category.getBudget()).getId(),
|
|
||||||
category.isExpense(),
|
|
||||||
category.isArchived()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public CategoryResponse(String id, String title, String description, long amount, String budgetId, boolean expense, boolean archived) {
|
|
||||||
this.id = id;
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.amount = amount;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.expense = expense;
|
|
||||||
this.archived = archived;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isArchived() {
|
|
||||||
return archived;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,41 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
public class NewCategoryRequest {
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final Long amount;
|
|
||||||
private final String budgetId;
|
|
||||||
private final Boolean expense;
|
|
||||||
|
|
||||||
public NewCategoryRequest() {
|
|
||||||
this(null, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public NewCategoryRequest(String title, String description, Long amount, String budgetId, Boolean expense) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.amount = amount;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.expense = expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,41 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.category;
|
|
||||||
|
|
||||||
public class UpdateCategoryRequest {
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final Long amount;
|
|
||||||
private final Boolean expense;
|
|
||||||
private final Boolean archived;
|
|
||||||
|
|
||||||
public UpdateCategoryRequest() {
|
|
||||||
this(null, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UpdateCategoryRequest(String title, String description, Long amount, Boolean expense, Boolean archived) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.amount = amount;
|
|
||||||
this.expense = expense;
|
|
||||||
this.archived = archived;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getArchived() {
|
|
||||||
return archived;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,32 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.user.UserRepository;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class JdbcUserDetailsService implements UserDetailsService {
|
|
||||||
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public JdbcUserDetailsService(UserRepository userRepository) {
|
|
||||||
this.userRepository = userRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
|
||||||
UserDetails userDetails;
|
|
||||||
userDetails = userRepository.findByUsername(username).orElse(null);
|
|
||||||
if (userDetails != null) {
|
|
||||||
return userDetails;
|
|
||||||
}
|
|
||||||
userDetails = userRepository.findByEmail(username).orElse(null);
|
|
||||||
if (userDetails != null) {
|
|
||||||
return userDetails;
|
|
||||||
}
|
|
||||||
throw new UsernameNotFoundException("Unable to find user with username $username");
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,10 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
|
||||||
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
|
||||||
public class MethodSecurity extends GlobalMethodSecurityConfiguration {
|
|
||||||
}
|
|
|
@ -1,118 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.passwordresetrequest.PasswordResetRequestRepository;
|
|
||||||
import com.wbrawner.budgetserver.session.UserSessionRepository;
|
|
||||||
import com.wbrawner.budgetserver.user.UserRepository;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.core.env.Environment;
|
|
||||||
import org.springframework.http.HttpMethod;
|
|
||||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
|
||||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
|
||||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
|
||||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
|
||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
import org.springframework.security.provisioning.JdbcUserDetailsManager;
|
|
||||||
import org.springframework.web.cors.CorsConfiguration;
|
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableWebSecurity
|
|
||||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
|
||||||
|
|
||||||
private final Environment env;
|
|
||||||
private final DataSource datasource;
|
|
||||||
private final UserSessionRepository userSessionRepository;
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
private final PasswordResetRequestRepository passwordResetRequestRepository;
|
|
||||||
private final JdbcUserDetailsService userDetailsService;
|
|
||||||
private final Environment environment;
|
|
||||||
|
|
||||||
public SecurityConfig(Environment env,
|
|
||||||
DataSource datasource,
|
|
||||||
UserSessionRepository userSessionRepository,
|
|
||||||
UserRepository userRepository,
|
|
||||||
PasswordResetRequestRepository passwordResetRequestRepository,
|
|
||||||
JdbcUserDetailsService userDetailsService,
|
|
||||||
Environment environment) {
|
|
||||||
this.env = env;
|
|
||||||
this.datasource = datasource;
|
|
||||||
this.userSessionRepository = userSessionRepository;
|
|
||||||
this.userRepository = userRepository;
|
|
||||||
this.passwordResetRequestRepository = passwordResetRequestRepository;
|
|
||||||
this.userDetailsService = userDetailsService;
|
|
||||||
this.environment = environment;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public JdbcUserDetailsManager getUserDetailsManager() {
|
|
||||||
var userDetailsManager = new JdbcUserDetailsManager();
|
|
||||||
userDetailsManager.setDataSource(datasource);
|
|
||||||
return userDetailsManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public DaoAuthenticationProvider getAuthenticationProvider() {
|
|
||||||
var authProvider = new TokenAuthenticationProvider(userSessionRepository, userRepository);
|
|
||||||
authProvider.setPasswordEncoder(getPasswordEncoder());
|
|
||||||
authProvider.setUserDetailsService(userDetailsService);
|
|
||||||
return authProvider;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean
|
|
||||||
public PasswordEncoder getPasswordEncoder() {
|
|
||||||
return new BCryptPasswordEncoder();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void configure(AuthenticationManagerBuilder auth) {
|
|
||||||
auth.authenticationProvider(getAuthenticationProvider());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void configure(HttpSecurity http) throws Exception {
|
|
||||||
http.authorizeRequests()
|
|
||||||
.antMatchers("/users/new", "/users/login")
|
|
||||||
.permitAll()
|
|
||||||
.anyRequest()
|
|
||||||
.authenticated()
|
|
||||||
.and()
|
|
||||||
.httpBasic()
|
|
||||||
.authenticationEntryPoint(new SilentAuthenticationEntryPoint())
|
|
||||||
.and()
|
|
||||||
.cors()
|
|
||||||
.configurationSource(request -> {
|
|
||||||
var corsConfig = new CorsConfiguration();
|
|
||||||
corsConfig.applyPermitDefaultValues();
|
|
||||||
var corsDomains = environment.getProperty("twigs.cors.domains", "*");
|
|
||||||
corsConfig.setAllowedOrigins(Arrays.asList(corsDomains.split(",")));
|
|
||||||
corsConfig.setAllowedMethods(
|
|
||||||
Stream.of(
|
|
||||||
HttpMethod.GET,
|
|
||||||
HttpMethod.POST,
|
|
||||||
HttpMethod.PUT,
|
|
||||||
HttpMethod.DELETE,
|
|
||||||
HttpMethod.OPTIONS
|
|
||||||
)
|
|
||||||
.map(Enum::name)
|
|
||||||
.collect(Collectors.toList())
|
|
||||||
);
|
|
||||||
corsConfig.setAllowCredentials(true);
|
|
||||||
return corsConfig;
|
|
||||||
})
|
|
||||||
.and()
|
|
||||||
.csrf()
|
|
||||||
.disable()
|
|
||||||
.addFilter(new TokenAuthenticationFilter(authenticationManager()))
|
|
||||||
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,20 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
|
|
||||||
public class SessionAuthenticationToken extends UsernamePasswordAuthenticationToken {
|
|
||||||
/**
|
|
||||||
* Creates a token with the supplied array of authorities.
|
|
||||||
*
|
|
||||||
* @param authorities the collection of <tt>GrantedAuthority</tt>s for the principal
|
|
||||||
* represented by this authentication object.
|
|
||||||
* @param credentials
|
|
||||||
* @param principal
|
|
||||||
*/
|
|
||||||
public SessionAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
|
|
||||||
super(principal, credentials, authorities);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import org.springframework.security.core.AuthenticationException;
|
|
||||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
|
||||||
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Used to avoid browser prompts for authentication
|
|
||||||
*/
|
|
||||||
public class SilentAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
|
||||||
@Override
|
|
||||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
|
|
||||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,32 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
|
||||||
import javax.servlet.ServletException;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Collections;
|
|
||||||
|
|
||||||
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
|
|
||||||
|
|
||||||
public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
|
|
||||||
super(authenticationManager);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
|
|
||||||
var authHeader = request.getHeader("Authorization");
|
|
||||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
|
||||||
chain.doFilter(request, response);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var token = authHeader.substring(7);
|
|
||||||
var authentication = getAuthenticationManager().authenticate(new SessionAuthenticationToken(null, token, Collections.emptyList()));
|
|
||||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
||||||
chain.doFilter(request, response);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,56 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.config;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.session.UserSessionRepository;
|
|
||||||
import com.wbrawner.budgetserver.user.UserRepository;
|
|
||||||
import org.springframework.security.authentication.BadCredentialsException;
|
|
||||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.AuthenticationException;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.twoWeeksFromNow;
|
|
||||||
|
|
||||||
public class TokenAuthenticationProvider extends DaoAuthenticationProvider {
|
|
||||||
private final UserSessionRepository userSessionRepository;
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
|
|
||||||
public TokenAuthenticationProvider(UserSessionRepository userSessionRepository, UserRepository userRepository) {
|
|
||||||
this.userSessionRepository = userSessionRepository;
|
|
||||||
this.userRepository = userRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
|
|
||||||
if (!(authentication instanceof SessionAuthenticationToken)) {
|
|
||||||
// Additional checks aren't needed since they've already been handled
|
|
||||||
super.additionalAuthenticationChecks(userDetails, authentication);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
|
||||||
if (authentication instanceof SessionAuthenticationToken) {
|
|
||||||
var session = userSessionRepository.findByToken((String) authentication.getCredentials());
|
|
||||||
if (session.isEmpty() || session.get().getExpiration().before(new Date())) {
|
|
||||||
throw new BadCredentialsException("Credentials expired");
|
|
||||||
}
|
|
||||||
var user = userRepository.findById(session.get().getUserId());
|
|
||||||
if (user.isEmpty()) {
|
|
||||||
throw new InternalAuthenticationServiceException("Failed to find user for token");
|
|
||||||
}
|
|
||||||
new Thread(() -> {
|
|
||||||
// Update the session on a background thread to avoid holding up the request longer than necessary
|
|
||||||
var updatedSession = session.get();
|
|
||||||
updatedSession.setExpiration(twoWeeksFromNow());
|
|
||||||
userSessionRepository.save(updatedSession);
|
|
||||||
}).start();
|
|
||||||
return new SessionAuthenticationToken(user.get(), authentication.getCredentials(), authentication.getAuthorities());
|
|
||||||
} else {
|
|
||||||
return super.authenticate(authentication);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,38 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.passwordresetrequest;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
|
|
||||||
import javax.persistence.*;
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.GregorianCalendar;
|
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class PasswordResetRequest {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
@ManyToOne
|
|
||||||
private final User user;
|
|
||||||
private final Calendar date;
|
|
||||||
private final String token;
|
|
||||||
|
|
||||||
public PasswordResetRequest() {
|
|
||||||
this(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public PasswordResetRequest(User user) {
|
|
||||||
this(user, new GregorianCalendar(), randomId());
|
|
||||||
}
|
|
||||||
|
|
||||||
public PasswordResetRequest(
|
|
||||||
User user,
|
|
||||||
Calendar date,
|
|
||||||
String token
|
|
||||||
) {
|
|
||||||
this.user = user;
|
|
||||||
this.date = date;
|
|
||||||
this.token = token;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,6 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.passwordresetrequest;
|
|
||||||
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
public interface PasswordResetRequestRepository extends PagingAndSortingRepository<PasswordResetRequest, Long> {
|
|
||||||
}
|
|
|
@ -1,54 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
|
|
||||||
import javax.persistence.*;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class UserPermission {
|
|
||||||
@EmbeddedId
|
|
||||||
private UserPermissionKey id;
|
|
||||||
@ManyToOne
|
|
||||||
@MapsId("budgetId")
|
|
||||||
@JoinColumn(nullable = false, name = "budget_id")
|
|
||||||
private Budget budget;
|
|
||||||
@ManyToOne
|
|
||||||
@MapsId("userId")
|
|
||||||
@JoinColumn(nullable = false, name = "user_id")
|
|
||||||
private User user;
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
@Enumerated(EnumType.STRING)
|
|
||||||
private Permission permission;
|
|
||||||
|
|
||||||
public UserPermission() {
|
|
||||||
this(null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermission(Budget budget, User user, Permission permission) {
|
|
||||||
this(new UserPermissionKey(budget.getId(), user.getId()), budget, user, permission);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermission(UserPermissionKey userPermissionKey, Budget budget, User user, Permission permission) {
|
|
||||||
this.id = userPermissionKey;
|
|
||||||
this.budget = budget;
|
|
||||||
this.user = user;
|
|
||||||
this.permission = permission;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermissionKey getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Budget getBudget() {
|
|
||||||
return budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User getUser() {
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Permission getPermission() {
|
|
||||||
return permission;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
|
||||||
|
|
||||||
import javax.persistence.Embeddable;
|
|
||||||
import java.io.Serializable;
|
|
||||||
|
|
||||||
@Embeddable
|
|
||||||
public class UserPermissionKey implements Serializable {
|
|
||||||
private final String budgetId;
|
|
||||||
private final String userId;
|
|
||||||
|
|
||||||
public UserPermissionKey() {
|
|
||||||
this(null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermissionKey(String budgetId, String userId) {
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.userId = userId;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,21 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface UserPermissionRepository extends PagingAndSortingRepository<UserPermission, UserPermissionKey> {
|
|
||||||
Optional<UserPermission> findByUserAndBudget_Id(User user, String budgetId);
|
|
||||||
|
|
||||||
List<UserPermission> findAllByUser(User user, Pageable pageable);
|
|
||||||
|
|
||||||
List<UserPermission> findAllByBudget(Budget budget, Pageable pageable);
|
|
||||||
|
|
||||||
List<UserPermission> findAllByUserAndBudget(User user, Budget budget, Pageable pageable);
|
|
||||||
|
|
||||||
List<UserPermission> findAllByUserAndBudget_IdIn(User user, List<String> budgetIds, Pageable pageable);
|
|
||||||
}
|
|
|
@ -1,23 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
|
||||||
|
|
||||||
public class UserPermissionRequest {
|
|
||||||
private final String user;
|
|
||||||
private final Permission permission;
|
|
||||||
|
|
||||||
public UserPermissionRequest() {
|
|
||||||
this(null, Permission.READ);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermissionRequest(String user, Permission permission) {
|
|
||||||
this.user = user;
|
|
||||||
this.permission = permission;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUser() {
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Permission getPermission() {
|
|
||||||
return permission;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.user.UserResponse;
|
|
||||||
|
|
||||||
public class UserPermissionResponse {
|
|
||||||
private final UserResponse user;
|
|
||||||
private final Permission permission;
|
|
||||||
|
|
||||||
public UserPermissionResponse(UserPermission userPermission) {
|
|
||||||
this(new UserResponse(userPermission.getUser()), userPermission.getPermission());
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserPermissionResponse(UserResponse userResponse, Permission permission) {
|
|
||||||
this.user = userResponse;
|
|
||||||
this.permission = permission;
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserResponse getUser() {
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Permission getPermission() {
|
|
||||||
return permission;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,184 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
import javax.persistence.JoinColumn;
|
|
||||||
import javax.persistence.ManyToOne;
|
|
||||||
import java.util.TimeZone;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class RecurringTransaction {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
@ManyToOne
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
private final User createdBy;
|
|
||||||
private String title;
|
|
||||||
private String description;
|
|
||||||
private Long amount;
|
|
||||||
@ManyToOne
|
|
||||||
private Category category;
|
|
||||||
private Boolean expense;
|
|
||||||
@ManyToOne
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
private Budget budget;
|
|
||||||
private String timeZone;
|
|
||||||
private int time;
|
|
||||||
private FrequencyUnit frequencyUnit;
|
|
||||||
private int frequencyValue;
|
|
||||||
|
|
||||||
public RecurringTransaction() {
|
|
||||||
this(
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
FrequencyUnit.DAILY,
|
|
||||||
0,
|
|
||||||
null,
|
|
||||||
0,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
null
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public RecurringTransaction(
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
FrequencyUnit frequencyUnit,
|
|
||||||
int frequencyValue,
|
|
||||||
String timeZone,
|
|
||||||
int time,
|
|
||||||
Long amount,
|
|
||||||
Category category,
|
|
||||||
Boolean expense,
|
|
||||||
User createdBy,
|
|
||||||
Budget budget
|
|
||||||
) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.frequencyUnit = frequencyUnit;
|
|
||||||
this.frequencyValue = frequencyValue;
|
|
||||||
setTimeZone(timeZone);
|
|
||||||
this.time = time;
|
|
||||||
this.amount = amount;
|
|
||||||
this.category = category;
|
|
||||||
this.expense = expense;
|
|
||||||
this.createdBy = createdBy;
|
|
||||||
this.budget = budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public FrequencyUnit getFrequencyUnit() {
|
|
||||||
return frequencyUnit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getFrequencyValue() {
|
|
||||||
return frequencyValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setFrequency(FrequencyUnit frequencyUnit, int frequencyValue) {
|
|
||||||
if (frequencyValue < 0) throw new IllegalArgumentException("frequencyValue must be at least 0");
|
|
||||||
if (frequencyValue > frequencyUnit.maxValue) {
|
|
||||||
throw new IllegalArgumentException(String.format(
|
|
||||||
"Invalid frequencyValue. Requested %d for %s but maxValue is %d",
|
|
||||||
frequencyValue,
|
|
||||||
frequencyUnit.name(),
|
|
||||||
frequencyUnit.maxValue
|
|
||||||
));
|
|
||||||
}
|
|
||||||
this.frequencyUnit = frequencyUnit;
|
|
||||||
this.frequencyValue = frequencyValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTimeZone() {
|
|
||||||
return timeZone;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTimeZone(String timeZone) {
|
|
||||||
this.timeZone = TimeZone.getTimeZone(timeZone).getID();
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getTimeOfDayInSeconds() {
|
|
||||||
return time;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTimeOfDayInSeconds(int time) {
|
|
||||||
this.time = time;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmount(Long amount) {
|
|
||||||
this.amount = amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Category getCategory() {
|
|
||||||
return category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategory(Category category) {
|
|
||||||
this.category = category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean isExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpense(Boolean expense) {
|
|
||||||
this.expense = expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User getCreatedBy() {
|
|
||||||
return createdBy;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Budget getBudget() {
|
|
||||||
return budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBudget(Budget budget) {
|
|
||||||
this.budget = budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum FrequencyUnit {
|
|
||||||
DAILY(0),
|
|
||||||
WEEKLY(7),
|
|
||||||
MONTHLY(30),
|
|
||||||
YEARLY(365);
|
|
||||||
|
|
||||||
int maxValue;
|
|
||||||
|
|
||||||
FrequencyUnit(int maxValue) {
|
|
||||||
this.maxValue = maxValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,168 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.ErrorResponse;
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import com.wbrawner.budgetserver.category.CategoryRepository;
|
|
||||||
import com.wbrawner.budgetserver.permission.Permission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRepository;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.getCurrentUser;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping(path = "/recurrence")
|
|
||||||
@Transactional
|
|
||||||
public class RecurringTransactionController {
|
|
||||||
private final CategoryRepository categoryRepository;
|
|
||||||
private final RecurringTransactionRepository recurringTransactionRepository;
|
|
||||||
private final UserPermissionRepository userPermissionsRepository;
|
|
||||||
|
|
||||||
private final Logger logger = LoggerFactory.getLogger(RecurringTransactionController.class);
|
|
||||||
|
|
||||||
public RecurringTransactionController(
|
|
||||||
CategoryRepository categoryRepository,
|
|
||||||
RecurringTransactionRepository recurringTransactionRepository,
|
|
||||||
UserPermissionRepository userPermissionsRepository
|
|
||||||
) {
|
|
||||||
this.categoryRepository = categoryRepository;
|
|
||||||
this.recurringTransactionRepository = recurringTransactionRepository;
|
|
||||||
this.userPermissionsRepository = userPermissionsRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<List<RecurringTransactionResponse>> getRecurringTransactions(
|
|
||||||
@RequestParam("budgetId") String budgetId
|
|
||||||
) {
|
|
||||||
List<UserPermission> userPermissions = userPermissionsRepository.findAllByUserAndBudget_IdIn(
|
|
||||||
getCurrentUser(),
|
|
||||||
Collections.singletonList(budgetId),
|
|
||||||
null
|
|
||||||
);
|
|
||||||
if (userPermissions.isEmpty()) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
var budget = userPermissions.get(0).getBudget();
|
|
||||||
var transactions = recurringTransactionRepository.findAllByBudget(budget)
|
|
||||||
.stream()
|
|
||||||
.map(RecurringTransactionResponse::new)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
return ResponseEntity.ok(transactions);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<RecurringTransactionResponse> getRecurringTransaction(@PathVariable String id) {
|
|
||||||
var budgets = userPermissionsRepository.findAllByUser(getCurrentUser(), null)
|
|
||||||
.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
var transaction = recurringTransactionRepository.findByIdAndBudgetIn(id, budgets).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
return ResponseEntity.ok(new RecurringTransactionResponse(transaction));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(path = "", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<Object> newTransaction(@RequestBody RecurringTransactionRequest request) {
|
|
||||||
var userResponse = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), request.getBudgetId())
|
|
||||||
.orElse(null);
|
|
||||||
if (userResponse == null) {
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Invalid budget ID"));
|
|
||||||
}
|
|
||||||
if (userResponse.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
var budget = userResponse.getBudget();
|
|
||||||
Category category = null;
|
|
||||||
if (request.getCategoryId() != null) {
|
|
||||||
category = categoryRepository.findByBudgetAndId(budget, request.getCategoryId()).orElse(null);
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new RecurringTransactionResponse(recurringTransactionRepository.save(new RecurringTransaction(
|
|
||||||
request.getTitle(),
|
|
||||||
request.getDescription(),
|
|
||||||
request.getFrequencyUnit(),
|
|
||||||
request.getFrequencyValue(),
|
|
||||||
request.getTimeZone(),
|
|
||||||
request.getTime(),
|
|
||||||
request.getAmount(),
|
|
||||||
category,
|
|
||||||
request.getExpense(),
|
|
||||||
getCurrentUser(),
|
|
||||||
budget
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<Object> updateTransaction(@PathVariable String id, @RequestBody RecurringTransactionRequest request) {
|
|
||||||
var transaction = recurringTransactionRepository.findById(id).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), transaction.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
if (request.getTitle() != null) {
|
|
||||||
transaction.setTitle(request.getTitle());
|
|
||||||
}
|
|
||||||
if (request.getDescription() != null) {
|
|
||||||
transaction.setDescription(request.getDescription());
|
|
||||||
}
|
|
||||||
if (request.getTimeZone() != null) {
|
|
||||||
transaction.setTimeZone(request.getTimeZone());
|
|
||||||
}
|
|
||||||
if (request.getAmount() != null) {
|
|
||||||
transaction.setAmount(request.getAmount());
|
|
||||||
}
|
|
||||||
if (request.getExpense() != null) {
|
|
||||||
transaction.setExpense(request.getExpense());
|
|
||||||
}
|
|
||||||
if (request.getTime() != null) {
|
|
||||||
transaction.setTimeOfDayInSeconds(request.getTime());
|
|
||||||
}
|
|
||||||
if (request.getFrequencyUnit() != null && request.getFrequencyValue() != null) {
|
|
||||||
transaction.setFrequency(request.getFrequencyUnit(), request.getFrequencyValue());
|
|
||||||
}
|
|
||||||
if (request.getBudgetId() != null) {
|
|
||||||
var newUserPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), request.getBudgetId()).orElse(null);
|
|
||||||
if (newUserPermission == null || newUserPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity
|
|
||||||
.badRequest()
|
|
||||||
.body(new ErrorResponse("Invalid budget"));
|
|
||||||
}
|
|
||||||
transaction.setBudget(newUserPermission.getBudget());
|
|
||||||
}
|
|
||||||
if (request.getCategoryId() != null) {
|
|
||||||
var category = categoryRepository.findByBudgetAndId(transaction.getBudget(), request.getCategoryId()).orElse(null);
|
|
||||||
if (category == null) {
|
|
||||||
return ResponseEntity
|
|
||||||
.badRequest()
|
|
||||||
.body(new ErrorResponse("Invalid category"));
|
|
||||||
}
|
|
||||||
transaction.setCategory(category);
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new RecurringTransactionResponse(recurringTransactionRepository.save(transaction)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping(path = "/{id}", produces = {MediaType.TEXT_PLAIN_VALUE})
|
|
||||||
public ResponseEntity<Void> deleteTransaction(@PathVariable String id) {
|
|
||||||
var transaction = recurringTransactionRepository.findById(id).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
// Check that the transaction belongs to an budget that the user has access to before deleting it
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), transaction.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
recurringTransactionRepository.delete(transaction);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,13 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface RecurringTransactionRepository extends PagingAndSortingRepository<RecurringTransaction, String> {
|
|
||||||
Optional<RecurringTransaction> findByIdAndBudgetIn(String id, List<Budget> budgets);
|
|
||||||
|
|
||||||
List<RecurringTransaction> findAllByBudget(Budget budget);
|
|
||||||
}
|
|
|
@ -1,83 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
class RecurringTransactionRequest {
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final Long amount;
|
|
||||||
private final String categoryId;
|
|
||||||
private final Boolean expense;
|
|
||||||
private final String budgetId;
|
|
||||||
private final String timeZone;
|
|
||||||
private final Integer time;
|
|
||||||
private final RecurringTransaction.FrequencyUnit frequencyUnit;
|
|
||||||
private final Integer frequencyValue;
|
|
||||||
|
|
||||||
|
|
||||||
RecurringTransactionRequest() {
|
|
||||||
this(null, null, null, 0, null, 0, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
RecurringTransactionRequest(
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
RecurringTransaction.FrequencyUnit frequencyUnit,
|
|
||||||
int frequencyValue,
|
|
||||||
String timeZone,
|
|
||||||
int time,
|
|
||||||
Long amount,
|
|
||||||
String categoryId,
|
|
||||||
Boolean expense,
|
|
||||||
String budgetId
|
|
||||||
) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.frequencyUnit = frequencyUnit;
|
|
||||||
this.frequencyValue = frequencyValue;
|
|
||||||
this.timeZone = timeZone;
|
|
||||||
this.time = time;
|
|
||||||
this.amount = amount;
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
this.expense = expense;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTimeZone() {
|
|
||||||
return timeZone;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getTime() {
|
|
||||||
return time;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RecurringTransaction.FrequencyUnit getFrequencyUnit() {
|
|
||||||
return frequencyUnit;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getFrequencyValue() {
|
|
||||||
return frequencyValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,62 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
class RecurringTransactionResponse {
|
|
||||||
public final String id;
|
|
||||||
public final String title;
|
|
||||||
public final String description;
|
|
||||||
public final long amount;
|
|
||||||
public final boolean expense;
|
|
||||||
public final String budgetId;
|
|
||||||
public final String categoryId;
|
|
||||||
public final String createdBy;
|
|
||||||
public final String timeZone;
|
|
||||||
public final int time;
|
|
||||||
public final RecurringTransaction.FrequencyUnit frequencyUnit;
|
|
||||||
public final int frequencyValue;
|
|
||||||
|
|
||||||
|
|
||||||
RecurringTransactionResponse(
|
|
||||||
String id,
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
long amount,
|
|
||||||
boolean expense,
|
|
||||||
String budgetId,
|
|
||||||
String categoryId,
|
|
||||||
String createdBy,
|
|
||||||
String timeZone,
|
|
||||||
int time,
|
|
||||||
RecurringTransaction.FrequencyUnit frequencyUnit,
|
|
||||||
int frequencyValue
|
|
||||||
) {
|
|
||||||
this.id = id;
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.amount = amount;
|
|
||||||
this.expense = expense;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
this.createdBy = createdBy;
|
|
||||||
this.timeZone = timeZone;
|
|
||||||
this.time = time;
|
|
||||||
this.frequencyUnit = frequencyUnit;
|
|
||||||
this.frequencyValue = frequencyValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
RecurringTransactionResponse(RecurringTransaction recurringTransaction) {
|
|
||||||
this(
|
|
||||||
recurringTransaction.getId(),
|
|
||||||
recurringTransaction.getTitle(),
|
|
||||||
recurringTransaction.getDescription(),
|
|
||||||
recurringTransaction.getAmount(),
|
|
||||||
recurringTransaction.isExpense(),
|
|
||||||
recurringTransaction.getBudget().getId(),
|
|
||||||
recurringTransaction.getCategory() != null ? recurringTransaction.getCategory().getId() : null,
|
|
||||||
recurringTransaction.getCreatedBy().getId(),
|
|
||||||
recurringTransaction.getTimeZone(),
|
|
||||||
recurringTransaction.getTimeOfDayInSeconds(),
|
|
||||||
recurringTransaction.getFrequencyUnit(),
|
|
||||||
recurringTransaction.getFrequencyValue()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,84 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.recurrence;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.transaction.Transaction;
|
|
||||||
import com.wbrawner.budgetserver.transaction.TransactionRepository;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.util.Calendar;
|
|
||||||
import java.util.GregorianCalendar;
|
|
||||||
import java.util.TimeZone;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class RecurringTransactionTask {
|
|
||||||
private final RecurringTransactionRepository recurringTransactionRepository;
|
|
||||||
private final TransactionRepository transactionRepository;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public RecurringTransactionTask(
|
|
||||||
RecurringTransactionRepository recurringTransactionRepository,
|
|
||||||
TransactionRepository transactionRepository
|
|
||||||
) {
|
|
||||||
this.recurringTransactionRepository = recurringTransactionRepository;
|
|
||||||
this.transactionRepository = transactionRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Scheduled(cron = "0 0 * * * *")
|
|
||||||
public void createTransactions() {
|
|
||||||
recurringTransactionRepository.findAll().forEach(recurringTransaction -> {
|
|
||||||
GregorianCalendar today = new GregorianCalendar(TimeZone.getTimeZone(recurringTransaction.getTimeZone()));
|
|
||||||
// if recurrence matches today, create a new transaction
|
|
||||||
int adjustedFrequencyValue, calendarField;
|
|
||||||
switch (recurringTransaction.getFrequencyUnit()) {
|
|
||||||
case DAILY -> {
|
|
||||||
// Daily transactions should have the frequency value set to 0, so we just force it to be the same
|
|
||||||
// as the current date in order to force the transaction creation.
|
|
||||||
adjustedFrequencyValue = today.get(Calendar.DATE);
|
|
||||||
calendarField = Calendar.DATE;
|
|
||||||
}
|
|
||||||
case WEEKLY -> {
|
|
||||||
// No adjustments needed for day of week
|
|
||||||
adjustedFrequencyValue = today.get(Calendar.DAY_OF_WEEK);
|
|
||||||
calendarField = Calendar.DAY_OF_WEEK;
|
|
||||||
}
|
|
||||||
case MONTHLY -> {
|
|
||||||
// Check if the day of the month is correct
|
|
||||||
adjustedFrequencyValue = Math.min(recurringTransaction.getFrequencyValue(), today.getActualMaximum(Calendar.DAY_OF_MONTH));
|
|
||||||
calendarField = Calendar.DAY_OF_MONTH;
|
|
||||||
}
|
|
||||||
case YEARLY -> {
|
|
||||||
adjustedFrequencyValue = recurringTransaction.getFrequencyValue();
|
|
||||||
if (today.isLeapYear(today.get(Calendar.YEAR)) && today.get(Calendar.DAY_OF_YEAR) >= 31 + 29) {
|
|
||||||
// We're just pretending that Feb 29th doesn't exist here...
|
|
||||||
adjustedFrequencyValue -= 1;
|
|
||||||
}
|
|
||||||
calendarField = Calendar.DAY_OF_YEAR;
|
|
||||||
}
|
|
||||||
default -> throw new IllegalStateException("Unexpected value: " + recurringTransaction.getFrequencyUnit());
|
|
||||||
}
|
|
||||||
if (adjustedFrequencyValue == today.get(calendarField)) {
|
|
||||||
createTransaction(recurringTransaction, today);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void createTransaction(RecurringTransaction recurringTransaction, Calendar transactionCalendar) {
|
|
||||||
transactionCalendar.set(Calendar.HOUR, 0);
|
|
||||||
transactionCalendar.set(Calendar.MINUTE, 0);
|
|
||||||
transactionCalendar.set(Calendar.SECOND, 0);
|
|
||||||
transactionCalendar.set(Calendar.MILLISECOND, 0);
|
|
||||||
transactionCalendar.add(Calendar.SECOND, recurringTransaction.getTimeOfDayInSeconds());
|
|
||||||
transactionRepository.save(new Transaction(
|
|
||||||
recurringTransaction.getTitle(),
|
|
||||||
recurringTransaction.getDescription(),
|
|
||||||
transactionCalendar.toInstant(),
|
|
||||||
recurringTransaction.getAmount(),
|
|
||||||
recurringTransaction.getCategory(),
|
|
||||||
recurringTransaction.isExpense(),
|
|
||||||
recurringTransaction.getCreatedBy(),
|
|
||||||
recurringTransaction.getBudget(),
|
|
||||||
recurringTransaction
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,44 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.session;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.*;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class Session {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
private final String userId;
|
|
||||||
private final String token = randomString(255);
|
|
||||||
private Date expiration = twoWeeksFromNow();
|
|
||||||
|
|
||||||
public Session() {
|
|
||||||
this("");
|
|
||||||
}
|
|
||||||
|
|
||||||
public Session(String userId) {
|
|
||||||
this.userId = userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUserId() {
|
|
||||||
return userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getToken() {
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Date getExpiration() {
|
|
||||||
return expiration;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpiration(Date expiration) {
|
|
||||||
this.expiration = expiration;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,22 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.session;
|
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
|
||||||
import org.springframework.stereotype.Component;
|
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
@Component
|
|
||||||
public class SessionCleanupTask {
|
|
||||||
private final UserSessionRepository sessionRepository;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public SessionCleanupTask(UserSessionRepository sessionRepository) {
|
|
||||||
this.sessionRepository = sessionRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Scheduled(cron = "0 0 * * * *")
|
|
||||||
public void cleanup() {
|
|
||||||
sessionRepository.deleteAllByExpirationBefore(new Date());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,25 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.session;
|
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
|
|
||||||
public class SessionResponse {
|
|
||||||
private final String token;
|
|
||||||
private final String expiration;
|
|
||||||
|
|
||||||
public SessionResponse(Session session) {
|
|
||||||
this(session.getToken(), session.getExpiration());
|
|
||||||
}
|
|
||||||
|
|
||||||
public SessionResponse(String token, Date expiration) {
|
|
||||||
this.token = token;
|
|
||||||
this.expiration = expiration.toInstant().toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getToken() {
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getExpiration() {
|
|
||||||
return expiration;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,17 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.session;
|
|
||||||
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface UserSessionRepository extends PagingAndSortingRepository<Session, String> {
|
|
||||||
List<Session> findByUserId(String userId);
|
|
||||||
|
|
||||||
Optional<Session> findByToken(String token);
|
|
||||||
|
|
||||||
Optional<Session> findByUserIdAndToken(String userId, String token);
|
|
||||||
|
|
||||||
void deleteAllByExpirationBefore(Date expiration);
|
|
||||||
}
|
|
|
@ -1,53 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
class NewTransactionRequest {
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final String date;
|
|
||||||
private final Long amount;
|
|
||||||
private final String categoryId;
|
|
||||||
private final Boolean expense;
|
|
||||||
private final String budgetId;
|
|
||||||
|
|
||||||
NewTransactionRequest() {
|
|
||||||
this(null, null, null, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
NewTransactionRequest(String title, String description, String date, Long amount, String categoryId, Boolean expense, String budgetId) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.date = date;
|
|
||||||
this.amount = amount;
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
this.expense = expense;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDate() {
|
|
||||||
return date;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,138 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import com.wbrawner.budgetserver.recurrence.RecurringTransaction;
|
|
||||||
import com.wbrawner.budgetserver.user.User;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
import javax.persistence.JoinColumn;
|
|
||||||
import javax.persistence.ManyToOne;
|
|
||||||
import java.time.Instant;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class Transaction implements Comparable<Transaction> {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
@ManyToOne
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
private final User createdBy;
|
|
||||||
private String title;
|
|
||||||
private String description;
|
|
||||||
private Instant date;
|
|
||||||
private Long amount;
|
|
||||||
@ManyToOne
|
|
||||||
private Category category;
|
|
||||||
private Boolean expense;
|
|
||||||
@ManyToOne
|
|
||||||
@JoinColumn(nullable = false)
|
|
||||||
private Budget budget;
|
|
||||||
@ManyToOne
|
|
||||||
private RecurringTransaction recurrence;
|
|
||||||
|
|
||||||
public Transaction() {
|
|
||||||
this(null, null, null, null, null, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Transaction(
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
Instant date,
|
|
||||||
Long amount,
|
|
||||||
Category category,
|
|
||||||
Boolean expense,
|
|
||||||
User createdBy,
|
|
||||||
Budget budget,
|
|
||||||
RecurringTransaction recurrence
|
|
||||||
) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.date = date;
|
|
||||||
this.amount = amount;
|
|
||||||
this.category = category;
|
|
||||||
this.expense = expense;
|
|
||||||
this.createdBy = createdBy;
|
|
||||||
this.budget = budget;
|
|
||||||
this.recurrence = recurrence;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTitle(String title) {
|
|
||||||
this.title = title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDescription(String description) {
|
|
||||||
this.description = description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Instant getDate() {
|
|
||||||
return date;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDate(Instant date) {
|
|
||||||
this.date = date;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAmount(Long amount) {
|
|
||||||
this.amount = amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Category getCategory() {
|
|
||||||
return category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCategory(Category category) {
|
|
||||||
this.category = category;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setExpense(Boolean expense) {
|
|
||||||
this.expense = expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public User getCreatedBy() {
|
|
||||||
return createdBy;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Budget getBudget() {
|
|
||||||
return budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setBudget(Budget budget) {
|
|
||||||
this.budget = budget;
|
|
||||||
}
|
|
||||||
|
|
||||||
public RecurringTransaction getRecurrence() {
|
|
||||||
return this.recurrence;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setRecurrence(RecurringTransaction recurrence) {
|
|
||||||
this.recurrence = recurrence;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int compareTo(Transaction other) {
|
|
||||||
return this.date.compareTo(other.date);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,210 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.ErrorResponse;
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import com.wbrawner.budgetserver.category.CategoryRepository;
|
|
||||||
import com.wbrawner.budgetserver.permission.Permission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermission;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRepository;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.data.domain.Sort;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.*;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping(path = "/transactions")
|
|
||||||
@Transactional
|
|
||||||
public class TransactionController {
|
|
||||||
private final CategoryRepository categoryRepository;
|
|
||||||
private final TransactionRepository transactionRepository;
|
|
||||||
private final UserPermissionRepository userPermissionsRepository;
|
|
||||||
|
|
||||||
private final Logger logger = LoggerFactory.getLogger(TransactionController.class);
|
|
||||||
|
|
||||||
public TransactionController(CategoryRepository categoryRepository,
|
|
||||||
TransactionRepository transactionRepository,
|
|
||||||
UserPermissionRepository userPermissionsRepository) {
|
|
||||||
this.categoryRepository = categoryRepository;
|
|
||||||
this.transactionRepository = transactionRepository;
|
|
||||||
this.userPermissionsRepository = userPermissionsRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<List<TransactionResponse>> getTransactions(
|
|
||||||
@RequestParam(value = "categoryIds", required = false) List<String> categoryIds,
|
|
||||||
@RequestParam(value = "budgetIds", required = false) List<String> budgetIds,
|
|
||||||
@RequestParam(value = "from", required = false) String from,
|
|
||||||
@RequestParam(value = "to", required = false) String to,
|
|
||||||
@RequestParam(value = "count", required = false) Integer count,
|
|
||||||
@RequestParam(value = "page", required = false) Integer page,
|
|
||||||
@RequestParam(value = "sortBy", required = false) String sortBy,
|
|
||||||
@RequestParam(value = "sortOrder", required = false) Sort.Direction sortOrder
|
|
||||||
) {
|
|
||||||
List<UserPermission> userPermissions;
|
|
||||||
if (budgetIds != null && !budgetIds.isEmpty()) {
|
|
||||||
userPermissions = userPermissionsRepository.findAllByUserAndBudget_IdIn(
|
|
||||||
getCurrentUser(),
|
|
||||||
budgetIds,
|
|
||||||
PageRequest.of(page != null ? page : 0, count != null ? count : 1000)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
userPermissions = userPermissionsRepository.findAllByUser(getCurrentUser(), null);
|
|
||||||
}
|
|
||||||
var budgets = userPermissions.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
List<Category> categories = null;
|
|
||||||
if (categoryIds != null && !categoryIds.isEmpty()) {
|
|
||||||
categories = categoryRepository.findAllByBudgetInAndIdIn(budgets, categoryIds, null);
|
|
||||||
}
|
|
||||||
var pageRequest = PageRequest.of(
|
|
||||||
Math.min(0, page != null ? page - 1 : 0),
|
|
||||||
count != null ? count : 1000,
|
|
||||||
sortOrder != null ? sortOrder : Sort.Direction.DESC,
|
|
||||||
sortBy != null ? sortBy : "date"
|
|
||||||
);
|
|
||||||
Instant fromInstant;
|
|
||||||
try {
|
|
||||||
fromInstant = Instant.parse(from);
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (!(e instanceof NullPointerException))
|
|
||||||
logger.error("Failed to parse '" + from + "' to Instant for 'from' parameter", e);
|
|
||||||
fromInstant = getFirstOfMonth().toInstant();
|
|
||||||
}
|
|
||||||
Instant toInstant;
|
|
||||||
try {
|
|
||||||
toInstant = Instant.parse(to);
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (!(e instanceof NullPointerException))
|
|
||||||
logger.error("Failed to parse '" + to + "' to Instant for 'to' parameter", e);
|
|
||||||
toInstant = getEndOfMonth().toInstant();
|
|
||||||
}
|
|
||||||
var query = categories == null ? transactionRepository.findAllByBudgetInAndDateGreaterThanAndDateLessThan(
|
|
||||||
budgets,
|
|
||||||
fromInstant,
|
|
||||||
toInstant,
|
|
||||||
pageRequest
|
|
||||||
) : transactionRepository.findAllByBudgetInAndCategoryInAndDateGreaterThanAndDateLessThan(
|
|
||||||
budgets,
|
|
||||||
categories,
|
|
||||||
fromInstant,
|
|
||||||
toInstant,
|
|
||||||
pageRequest
|
|
||||||
);
|
|
||||||
var transactions = query
|
|
||||||
.stream()
|
|
||||||
.map(TransactionResponse::new)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
return ResponseEntity.ok(transactions);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<TransactionResponse> getTransaction(@PathVariable String id) {
|
|
||||||
var budgets = userPermissionsRepository.findAllByUser(getCurrentUser(), null)
|
|
||||||
.stream()
|
|
||||||
.map(UserPermission::getBudget)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
var transaction = transactionRepository.findByIdAndBudgetIn(id, budgets).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
return ResponseEntity.ok(new TransactionResponse(transaction));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(path = "", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<Object> newTransaction(@RequestBody NewTransactionRequest request) {
|
|
||||||
var userResponse = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), request.getBudgetId())
|
|
||||||
.orElse(null);
|
|
||||||
if (userResponse == null) {
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Invalid budget ID"));
|
|
||||||
}
|
|
||||||
if (userResponse.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
var budget = userResponse.getBudget();
|
|
||||||
Category category = null;
|
|
||||||
if (request.getCategoryId() != null) {
|
|
||||||
category = categoryRepository.findByBudgetAndId(budget, request.getCategoryId()).orElse(null);
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new TransactionResponse(transactionRepository.save(new Transaction(
|
|
||||||
request.getTitle(),
|
|
||||||
request.getDescription(),
|
|
||||||
Instant.parse(request.getDate()),
|
|
||||||
request.getAmount(),
|
|
||||||
category,
|
|
||||||
request.getExpense(),
|
|
||||||
getCurrentUser(),
|
|
||||||
budget,
|
|
||||||
null
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
public ResponseEntity<Object> updateTransaction(@PathVariable String id, @RequestBody UpdateTransactionRequest request) {
|
|
||||||
var transaction = transactionRepository.findById(id).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), transaction.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
if (request.getTitle() != null) {
|
|
||||||
transaction.setTitle(request.getTitle());
|
|
||||||
}
|
|
||||||
if (request.getDescription() != null) {
|
|
||||||
transaction.setDescription(request.getDescription());
|
|
||||||
}
|
|
||||||
if (request.getDate() != null) {
|
|
||||||
transaction.setDate(Instant.parse(request.getDate()));
|
|
||||||
}
|
|
||||||
if (request.getAmount() != null) {
|
|
||||||
transaction.setAmount(request.getAmount());
|
|
||||||
}
|
|
||||||
if (request.getExpense() != null) {
|
|
||||||
transaction.setExpense(request.getExpense());
|
|
||||||
}
|
|
||||||
if (request.getBudgetId() != null) {
|
|
||||||
var newUserPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), request.getBudgetId()).orElse(null);
|
|
||||||
if (newUserPermission == null || newUserPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity
|
|
||||||
.badRequest()
|
|
||||||
.body(new ErrorResponse("Invalid budget"));
|
|
||||||
}
|
|
||||||
transaction.setBudget(newUserPermission.getBudget());
|
|
||||||
}
|
|
||||||
if (request.getCategoryId() != null) {
|
|
||||||
var category = categoryRepository.findByBudgetAndId(transaction.getBudget(), request.getCategoryId()).orElse(null);
|
|
||||||
if (category == null) {
|
|
||||||
return ResponseEntity
|
|
||||||
.badRequest()
|
|
||||||
.body(new ErrorResponse("Invalid category"));
|
|
||||||
}
|
|
||||||
transaction.setCategory(category);
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new TransactionResponse(transactionRepository.save(transaction)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping(path = "/{id}", produces = {MediaType.TEXT_PLAIN_VALUE})
|
|
||||||
public ResponseEntity<Void> deleteTransaction(@PathVariable String id) {
|
|
||||||
var transaction = transactionRepository.findById(id).orElse(null);
|
|
||||||
if (transaction == null) return ResponseEntity.notFound().build();
|
|
||||||
// Check that the transaction belongs to an budget that the user has access to before deleting it
|
|
||||||
var userPermission = userPermissionsRepository.findByUserAndBudget_Id(getCurrentUser(), transaction.getBudget().getId()).orElse(null);
|
|
||||||
if (userPermission == null) return ResponseEntity.notFound().build();
|
|
||||||
if (userPermission.getPermission().isNotAtLeast(Permission.WRITE)) {
|
|
||||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
|
||||||
}
|
|
||||||
transactionRepository.delete(transaction);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.budget.Budget;
|
|
||||||
import com.wbrawner.budgetserver.category.Category;
|
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.jpa.repository.Query;
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface TransactionRepository extends PagingAndSortingRepository<Transaction, String> {
|
|
||||||
Optional<Transaction> findByIdAndBudgetIn(String id, List<Budget> budgets);
|
|
||||||
|
|
||||||
List<Transaction> findAllByBudgetInAndCategoryInAndDateGreaterThanAndDateLessThan(
|
|
||||||
List<Budget> budgets,
|
|
||||||
List<Category> categories,
|
|
||||||
Instant start,
|
|
||||||
Instant end,
|
|
||||||
Pageable pageable
|
|
||||||
);
|
|
||||||
|
|
||||||
List<Transaction> findAllByBudgetInAndDateGreaterThanAndDateLessThan(
|
|
||||||
List<Budget> budgets,
|
|
||||||
Instant start,
|
|
||||||
Instant end,
|
|
||||||
Pageable pageable
|
|
||||||
);
|
|
||||||
|
|
||||||
List<Transaction> findAllByBudgetAndCategory(Budget budget, Category category);
|
|
||||||
|
|
||||||
@Query(
|
|
||||||
nativeQuery = true,
|
|
||||||
value = "SELECT (COALESCE((SELECT SUM(amount) from transaction WHERE Budget_id = :BudgetId AND expense = 0 AND date >= :from AND date <= :to), 0)) - (COALESCE((SELECT SUM(amount) from transaction WHERE Budget_id = :BudgetId AND expense = 1 AND date >= :from AND date <= :to), 0));"
|
|
||||||
)
|
|
||||||
Long sumBalanceByBudgetId(String BudgetId, Instant from, Instant to);
|
|
||||||
|
|
||||||
@Query(
|
|
||||||
nativeQuery = true,
|
|
||||||
value = "SELECT (COALESCE((SELECT SUM(amount) from transaction WHERE category_id = :categoryId AND expense = 0 AND date > :start), 0)) - (COALESCE((SELECT SUM(amount) from transaction WHERE category_id = :categoryId AND expense = 1 AND date > :start), 0));"
|
|
||||||
)
|
|
||||||
Long sumBalanceByCategoryId(String categoryId, Date start);
|
|
||||||
}
|
|
|
@ -1,83 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
class TransactionResponse {
|
|
||||||
private final String id;
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final String date;
|
|
||||||
private final Long amount;
|
|
||||||
private final Boolean expense;
|
|
||||||
private final String budgetId;
|
|
||||||
private final String categoryId;
|
|
||||||
private final String createdBy;
|
|
||||||
|
|
||||||
TransactionResponse(String id,
|
|
||||||
String title,
|
|
||||||
String description,
|
|
||||||
String date,
|
|
||||||
Long amount,
|
|
||||||
Boolean expense,
|
|
||||||
String budgetId,
|
|
||||||
String categoryId,
|
|
||||||
String createdBy) {
|
|
||||||
this.id = id;
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.date = date;
|
|
||||||
this.amount = amount;
|
|
||||||
this.expense = expense;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
this.createdBy = createdBy;
|
|
||||||
}
|
|
||||||
|
|
||||||
TransactionResponse(Transaction transaction) {
|
|
||||||
this(
|
|
||||||
transaction.getId(),
|
|
||||||
transaction.getTitle(),
|
|
||||||
transaction.getDescription(),
|
|
||||||
transaction.getDate().toString(),
|
|
||||||
transaction.getAmount(),
|
|
||||||
transaction.getExpense(),
|
|
||||||
transaction.getBudget().getId(),
|
|
||||||
transaction.getCategory() != null ? transaction.getCategory().getId() : null,
|
|
||||||
transaction.getCreatedBy().getId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDate() {
|
|
||||||
return date;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCreatedBy() {
|
|
||||||
return createdBy;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,59 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.transaction;
|
|
||||||
|
|
||||||
class UpdateTransactionRequest {
|
|
||||||
private final String title;
|
|
||||||
private final String description;
|
|
||||||
private final String date;
|
|
||||||
private final Long amount;
|
|
||||||
private final String categoryId;
|
|
||||||
private final Boolean expense;
|
|
||||||
private final String budgetId;
|
|
||||||
private final String createdBy;
|
|
||||||
|
|
||||||
UpdateTransactionRequest() {
|
|
||||||
this(null, null, null, null, null, null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
UpdateTransactionRequest(String title, String description, String date, Long amount, String categoryId, Boolean expense, String budgetId, String createdBy) {
|
|
||||||
this.title = title;
|
|
||||||
this.description = description;
|
|
||||||
this.date = date;
|
|
||||||
this.amount = amount;
|
|
||||||
this.categoryId = categoryId;
|
|
||||||
this.expense = expense;
|
|
||||||
this.budgetId = budgetId;
|
|
||||||
this.createdBy = createdBy;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getTitle() {
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDescription() {
|
|
||||||
return description;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getDate() {
|
|
||||||
return date;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getAmount() {
|
|
||||||
return amount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCategoryId() {
|
|
||||||
return categoryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Boolean getExpense() {
|
|
||||||
return expense;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBudgetId() {
|
|
||||||
return budgetId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCreatedBy() {
|
|
||||||
return createdBy;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,23 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
public class LoginRequest {
|
|
||||||
private final String username;
|
|
||||||
private final String password;
|
|
||||||
|
|
||||||
public LoginRequest() {
|
|
||||||
this(null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public LoginRequest(String username, String password) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
public class NewUserRequest {
|
|
||||||
private final String username;
|
|
||||||
private final String password;
|
|
||||||
private final String email;
|
|
||||||
|
|
||||||
public NewUserRequest() {
|
|
||||||
this(null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public NewUserRequest(String username, String password, String email) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
public class UpdateUserRequest {
|
|
||||||
private final String username;
|
|
||||||
private final String password;
|
|
||||||
private final String email;
|
|
||||||
|
|
||||||
public UpdateUserRequest() {
|
|
||||||
this(null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public UpdateUserRequest(String username, String password, String email) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,96 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
import org.springframework.lang.NonNull;
|
|
||||||
import org.springframework.security.core.GrantedAuthority;
|
|
||||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
|
||||||
|
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
import javax.persistence.Transient;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.randomId;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
public class User implements UserDetails {
|
|
||||||
@Id
|
|
||||||
private final String id = randomId();
|
|
||||||
@Transient
|
|
||||||
private final List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("USER"));
|
|
||||||
private String username;
|
|
||||||
private String password;
|
|
||||||
private String email;
|
|
||||||
|
|
||||||
public User() {
|
|
||||||
this(null, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public User(String username, String password, String email) {
|
|
||||||
this.username = username;
|
|
||||||
this.password = password;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
@NonNull
|
|
||||||
public String getId() {
|
|
||||||
// This shouldn't ever need to be set manually, only through Hibernate
|
|
||||||
//noinspection ConstantConditions
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsername(String username) {
|
|
||||||
this.username = username;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPassword(String password) {
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isAccountNonExpired() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isAccountNonLocked() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isCredentialsNonExpired() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isEnabled() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
|
||||||
return authorities;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
|
@ -1,157 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
import com.wbrawner.budgetserver.ErrorResponse;
|
|
||||||
import com.wbrawner.budgetserver.budget.BudgetRepository;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionRepository;
|
|
||||||
import com.wbrawner.budgetserver.permission.UserPermissionResponse;
|
|
||||||
import com.wbrawner.budgetserver.session.Session;
|
|
||||||
import com.wbrawner.budgetserver.session.SessionResponse;
|
|
||||||
import com.wbrawner.budgetserver.session.UserSessionRepository;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
||||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.core.AuthenticationException;
|
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
|
||||||
import org.springframework.web.bind.annotation.*;
|
|
||||||
|
|
||||||
import javax.transaction.Transactional;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import static com.wbrawner.budgetserver.Utils.getCurrentUser;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
@RequestMapping("/users")
|
|
||||||
@Transactional
|
|
||||||
public class UserController {
|
|
||||||
private final BudgetRepository budgetRepository;
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
private final PasswordEncoder passwordEncoder;
|
|
||||||
private final UserPermissionRepository userPermissionsRepository;
|
|
||||||
private final UserSessionRepository userSessionRepository;
|
|
||||||
private final DaoAuthenticationProvider authenticationProvider;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
public UserController(BudgetRepository budgetRepository,
|
|
||||||
UserRepository userRepository,
|
|
||||||
UserSessionRepository userSessionRepository,
|
|
||||||
PasswordEncoder passwordEncoder,
|
|
||||||
UserPermissionRepository userPermissionsRepository,
|
|
||||||
DaoAuthenticationProvider authenticationProvider) {
|
|
||||||
this.budgetRepository = budgetRepository;
|
|
||||||
this.userRepository = userRepository;
|
|
||||||
this.userSessionRepository = userSessionRepository;
|
|
||||||
this.passwordEncoder = passwordEncoder;
|
|
||||||
this.userPermissionsRepository = userPermissionsRepository;
|
|
||||||
this.authenticationProvider = authenticationProvider;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@GetMapping(path = "", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<List<UserPermissionResponse>> getUsers(String budgetId) {
|
|
||||||
var budget = budgetRepository.findById(budgetId).orElse(null);
|
|
||||||
if (budget == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
var userPermissions = userPermissionsRepository.findAllByBudget(budget, null);
|
|
||||||
|
|
||||||
var userInBudget = userPermissions.stream()
|
|
||||||
.anyMatch(userPermission ->
|
|
||||||
userPermission.getUser().getId().equals(getCurrentUser().getId()));
|
|
||||||
if (!userInBudget) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(userPermissions.stream().map(UserPermissionResponse::new).collect(Collectors.toList()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(path = "/login", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<SessionResponse> login(@RequestBody LoginRequest request) {
|
|
||||||
var authReq = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
|
|
||||||
Authentication auth;
|
|
||||||
try {
|
|
||||||
auth = authenticationProvider.authenticate(authReq);
|
|
||||||
} catch (AuthenticationException e) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
|
||||||
var user = Objects.requireNonNull(getCurrentUser());
|
|
||||||
var session = userSessionRepository.save(new Session(user.getId()));
|
|
||||||
return ResponseEntity.ok(new SessionResponse(session));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/me", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<UserResponse> getProfile() {
|
|
||||||
var user = getCurrentUser();
|
|
||||||
if (user == null) return ResponseEntity.status(401).build();
|
|
||||||
return ResponseEntity.ok(new UserResponse(user));
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/search", produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<List<UserResponse>> searchUsers(String query) {
|
|
||||||
return ResponseEntity.ok(
|
|
||||||
userRepository.findByUsernameContains(query)
|
|
||||||
.stream()
|
|
||||||
.map(UserResponse::new)
|
|
||||||
.collect(Collectors.toList())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping(path = "/{id}")
|
|
||||||
ResponseEntity<UserResponse> getUser(@PathVariable String id) {
|
|
||||||
var user = userRepository.findById(id).orElse(null);
|
|
||||||
if (user == null) {
|
|
||||||
return ResponseEntity.notFound().build();
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new UserResponse(user));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PostMapping(path = "", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<Object> newUser(@RequestBody NewUserRequest request) {
|
|
||||||
if (userRepository.findByUsername(request.getUsername()).isPresent())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Username taken"));
|
|
||||||
if (userRepository.findByEmail(request.getEmail()).isPresent())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Email taken"));
|
|
||||||
if (request.getPassword().isBlank())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Invalid password"));
|
|
||||||
return ResponseEntity.ok(new UserResponse(userRepository.save(new User(
|
|
||||||
request.getUsername(),
|
|
||||||
passwordEncoder.encode(request.getPassword()),
|
|
||||||
request.getEmail()
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE})
|
|
||||||
ResponseEntity<Object> updateUser(@PathVariable Long id, @RequestBody UpdateUserRequest request) {
|
|
||||||
if (!getCurrentUser().getId().equals(id)) return ResponseEntity.status(403).build();
|
|
||||||
var user = userRepository.findById(getCurrentUser().getId()).orElse(null);
|
|
||||||
if (user == null) return ResponseEntity.notFound().build();
|
|
||||||
if (request.getUsername() != null) {
|
|
||||||
if (userRepository.findByUsername(request.getUsername()).isPresent())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Username taken"));
|
|
||||||
user.setUsername(request.getUsername());
|
|
||||||
}
|
|
||||||
if (request.getEmail() != null) {
|
|
||||||
if (userRepository.findByEmail(request.getEmail()).isPresent())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Email taken"));
|
|
||||||
user.setEmail(request.getEmail());
|
|
||||||
}
|
|
||||||
if (request.getPassword() != null) {
|
|
||||||
if (request.getPassword().isBlank())
|
|
||||||
return ResponseEntity.badRequest().body(new ErrorResponse("Invalid password"));
|
|
||||||
user.setPassword(passwordEncoder.encode(request.getPassword()));
|
|
||||||
}
|
|
||||||
return ResponseEntity.ok(new UserResponse(userRepository.save(user)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping(path = "/{id}", produces = {MediaType.TEXT_PLAIN_VALUE})
|
|
||||||
ResponseEntity<Void> deleteUser(@PathVariable String id) {
|
|
||||||
if (!getCurrentUser().getId().equals(id)) return ResponseEntity.status(403).build();
|
|
||||||
userRepository.deleteById(id);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,16 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface UserRepository extends PagingAndSortingRepository<User, String> {
|
|
||||||
Optional<User> findByUsername(String username);
|
|
||||||
|
|
||||||
Optional<User> findByUsernameAndPassword(String username, String password);
|
|
||||||
|
|
||||||
List<User> findByUsernameContains(String username);
|
|
||||||
|
|
||||||
Optional<User> findByEmail(String email);
|
|
||||||
}
|
|
|
@ -1,29 +0,0 @@
|
||||||
package com.wbrawner.budgetserver.user;
|
|
||||||
|
|
||||||
public class UserResponse {
|
|
||||||
private final String id;
|
|
||||||
private final String username;
|
|
||||||
private final String email;
|
|
||||||
|
|
||||||
public UserResponse(User user) {
|
|
||||||
this(user.getId(), user.getUsername(), user.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
public UserResponse(String id, String username, String email) {
|
|
||||||
this.id = id;
|
|
||||||
this.username = username;
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getUsername() {
|
|
||||||
return username;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
}
|
|
60
api/src/main/kotlin/com/wbrawner/twigs/BudgetRoutes.kt
Normal file
60
api/src/main/kotlin/com/wbrawner/twigs/BudgetRoutes.kt
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
66
api/src/main/kotlin/com/wbrawner/twigs/CategoryRoutes.kt
Normal file
66
api/src/main/kotlin/com/wbrawner/twigs/CategoryRoutes.kt
Normal file
|
@ -0,0 +1,66 @@
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,62 @@
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
87
api/src/main/kotlin/com/wbrawner/twigs/TransactionRoutes.kt
Normal file
87
api/src/main/kotlin/com/wbrawner/twigs/TransactionRoutes.kt
Normal file
|
@ -0,0 +1,87 @@
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
84
api/src/main/kotlin/com/wbrawner/twigs/UserRoutes.kt
Normal file
84
api/src/main/kotlin/com/wbrawner/twigs/UserRoutes.kt
Normal file
|
@ -0,0 +1,84 @@
|
||||||
|
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,10 +0,0 @@
|
||||||
spring.jpa.hibernate.ddl-auto=none
|
|
||||||
spring.datasource.url=jdbc:mysql://localhost:3306/budget
|
|
||||||
spring.datasource.username=budget
|
|
||||||
spring.datasource.password=budget
|
|
||||||
spring.profiles.active=prod
|
|
||||||
spring.session.jdbc.initialize-schema=always
|
|
||||||
spring.datasource.testWhileIdle=true
|
|
||||||
spring.datasource.timeBetweenEvictionRunsMillis=60000
|
|
||||||
spring.datasource.validationQuery=SELECT 1
|
|
||||||
twigs.cors.domains=*
|
|
1
app/.gitignore
vendored
Normal file
1
app/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
build/
|
61
app/build.gradle.kts
Normal file
61
app/build.gradle.kts
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
274
app/src/main/kotlin/com/wbrawner/twigs/server/Application.kt
Normal file
274
app/src/main/kotlin/com/wbrawner/twigs/server/Application.kt
Normal file
|
@ -0,0 +1,274 @@
|
||||||
|
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()
|
||||||
|
}
|
|
@ -0,0 +1,92 @@
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package com.wbrawner.twigs.server
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.storage.SessionRepository
|
||||||
|
|
||||||
|
class SessionCleanupJob(private val sessionRepository: SessionRepository) : Job {
|
||||||
|
override suspend fun run() {
|
||||||
|
sessionRepository.deleteExpired()
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,77 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
49
app/src/main/resources/email/html/passwordreset.html
Normal file
49
app/src/main/resources/email/html/passwordreset.html
Normal file
|
@ -0,0 +1,49 @@
|
||||||
|
<!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>
|
5
app/src/main/resources/email/plain/passwordreset.txt
Normal file
5
app/src/main/resources/email/plain/passwordreset.txt
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
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}
|
597
app/src/main/resources/openapi/documentation.yaml
Normal file
597
app/src/main/resources/openapi/documentation.yaml
Normal file
|
@ -0,0 +1,597 @@
|
||||||
|
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"
|
|
@ -0,0 +1,356 @@
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
82
app/src/test/kotlin/com/wbrawner/twigs/server/api/ApiTest.kt
Normal file
82
app/src/test/kotlin/com/wbrawner/twigs/server/api/ApiTest.kt
Normal file
|
@ -0,0 +1,82 @@
|
||||||
|
package com.wbrawner.twigs.server.api
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.server.moduleWithDependencies
|
||||||
|
import com.wbrawner.twigs.service.budget.DefaultBudgetService
|
||||||
|
import com.wbrawner.twigs.service.category.DefaultCategoryService
|
||||||
|
import com.wbrawner.twigs.service.recurringtransaction.DefaultRecurringTransactionService
|
||||||
|
import com.wbrawner.twigs.service.transaction.DefaultTransactionService
|
||||||
|
import com.wbrawner.twigs.service.user.DefaultUserService
|
||||||
|
import com.wbrawner.twigs.test.helpers.FakeEmailService
|
||||||
|
import com.wbrawner.twigs.test.helpers.repository.*
|
||||||
|
import io.ktor.client.*
|
||||||
|
import io.ktor.client.plugins.contentnegotiation.*
|
||||||
|
import io.ktor.serialization.kotlinx.json.*
|
||||||
|
import io.ktor.server.testing.*
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import org.junit.jupiter.api.BeforeEach
|
||||||
|
|
||||||
|
open class ApiTest {
|
||||||
|
lateinit var budgetRepository: FakeBudgetRepository
|
||||||
|
lateinit var categoryRepository: FakeCategoryRepository
|
||||||
|
lateinit var emailService: FakeEmailService
|
||||||
|
lateinit var metadataRepository: FakeMetadataRepository
|
||||||
|
lateinit var passwordResetRepository: FakePasswordResetRepository
|
||||||
|
lateinit var permissionRepository: FakePermissionRepository
|
||||||
|
lateinit var recurringTransactionRepository: FakeRecurringTransactionRepository
|
||||||
|
lateinit var sessionRepository: FakeSessionRepository
|
||||||
|
lateinit var transactionRepository: FakeTransactionRepository
|
||||||
|
lateinit var userRepository: FakeUserRepository
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
fun setup() {
|
||||||
|
budgetRepository = FakeBudgetRepository()
|
||||||
|
categoryRepository = FakeCategoryRepository()
|
||||||
|
emailService = FakeEmailService()
|
||||||
|
metadataRepository = FakeMetadataRepository()
|
||||||
|
passwordResetRepository = FakePasswordResetRepository()
|
||||||
|
permissionRepository = FakePermissionRepository()
|
||||||
|
recurringTransactionRepository = FakeRecurringTransactionRepository()
|
||||||
|
sessionRepository = FakeSessionRepository()
|
||||||
|
transactionRepository = FakeTransactionRepository()
|
||||||
|
userRepository = FakeUserRepository()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun apiTest(test: suspend ApiTest.(client: HttpClient) -> Unit) = testApplication {
|
||||||
|
application {
|
||||||
|
moduleWithDependencies(
|
||||||
|
budgetService = DefaultBudgetService(budgetRepository, permissionRepository),
|
||||||
|
categoryService = DefaultCategoryService(categoryRepository, permissionRepository),
|
||||||
|
recurringTransactionService = DefaultRecurringTransactionService(
|
||||||
|
recurringTransactionRepository,
|
||||||
|
permissionRepository
|
||||||
|
),
|
||||||
|
transactionService = DefaultTransactionService(
|
||||||
|
transactionRepository,
|
||||||
|
categoryRepository,
|
||||||
|
permissionRepository
|
||||||
|
),
|
||||||
|
userService = DefaultUserService(
|
||||||
|
emailService,
|
||||||
|
passwordResetRepository,
|
||||||
|
permissionRepository,
|
||||||
|
sessionRepository,
|
||||||
|
userRepository,
|
||||||
|
{ it }
|
||||||
|
),
|
||||||
|
jobs = listOf(),
|
||||||
|
sessionValidator = {
|
||||||
|
sessionRepository.findAll(it.token).firstOrNull()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val client = createClient {
|
||||||
|
install(ContentNegotiation) {
|
||||||
|
json(json = Json {
|
||||||
|
encodeDefaults = true
|
||||||
|
explicitNulls = false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
test(client)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,419 @@
|
||||||
|
package com.wbrawner.twigs.server.api
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.model.*
|
||||||
|
import com.wbrawner.twigs.service.budget.BudgetRequest
|
||||||
|
import com.wbrawner.twigs.service.budget.BudgetResponse
|
||||||
|
import com.wbrawner.twigs.service.user.UserPermissionRequest
|
||||||
|
import com.wbrawner.twigs.service.user.UserPermissionResponse
|
||||||
|
import io.ktor.client.call.*
|
||||||
|
import io.ktor.client.request.*
|
||||||
|
import io.ktor.http.*
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
|
||||||
|
class BudgetRouteTest : ApiTest() {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `fetching budgets requires authentication`() = apiTest { client ->
|
||||||
|
val response = client.get("/api/budgets")
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `fetching budgets returns empty list when there are no budgets`() = apiTest { client ->
|
||||||
|
val session = Session()
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val response = client.get("/api/budgets") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
assertEquals(0, response.body<List<BudgetResponse>>().size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `fetching budgets only returns budgets for current user`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val currentUserBudget = budgetRepository.save(Budget(name = "Test User's Budget"))
|
||||||
|
val otherUserBudget = budgetRepository.save(Budget(name = "Other User's Budget"))
|
||||||
|
permissionRepository.save(
|
||||||
|
UserPermission(
|
||||||
|
budgetId = currentUserBudget.id,
|
||||||
|
userId = users[0].id,
|
||||||
|
Permission.OWNER
|
||||||
|
)
|
||||||
|
)
|
||||||
|
permissionRepository.save(UserPermission(budgetId = otherUserBudget.id, userId = users[1].id, Permission.OWNER))
|
||||||
|
val response = client.get("/api/budgets") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
val returnedBudgets = response.body<List<BudgetResponse>>()
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
assertEquals(1, returnedBudgets.size)
|
||||||
|
assertEquals(currentUserBudget.id, returnedBudgets.first().id)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `creating budgets requires authentication`() = apiTest { client ->
|
||||||
|
val request = BudgetRequest("Test Budget", "A budget for testing")
|
||||||
|
val response = client.post("/api/budgets") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `newly created budgets are saved`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermissionRequest(users[0].id, Permission.OWNER),
|
||||||
|
UserPermissionRequest(users[1].id, Permission.READ),
|
||||||
|
)
|
||||||
|
val request = BudgetRequest("Test Budget", "A budget for testing", permissions)
|
||||||
|
val response = client.post("/api/budgets") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val responseBody: BudgetResponse = response.body()
|
||||||
|
assert(responseBody.id.isNotEmpty())
|
||||||
|
assertEquals("Test Budget", responseBody.name)
|
||||||
|
assertEquals("A budget for testing", responseBody.description)
|
||||||
|
assertEquals(2, responseBody.users.size)
|
||||||
|
assert(responseBody.users.containsAll(permissions.map { UserPermissionResponse(it.user, it.permission) }))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `newly created budgets include current user as owner if omitted`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermissionRequest(users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
val request = BudgetRequest("Test Budget", "A budget for testing", permissions)
|
||||||
|
val response = client.post("/api/budgets") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val responseBody: BudgetResponse = response.body()
|
||||||
|
assert(responseBody.id.isNotEmpty())
|
||||||
|
assertEquals("Test Budget", responseBody.name)
|
||||||
|
assertEquals("A budget for testing", responseBody.description)
|
||||||
|
assertEquals(2, responseBody.users.size)
|
||||||
|
val expectedPermissions = listOf(
|
||||||
|
UserPermissionResponse(users[0].id, Permission.OWNER),
|
||||||
|
UserPermissionResponse(users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
assert(responseBody.users.containsAll(expectedPermissions))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets requires authentication`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets returns forbidden for users with read only access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.READ),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets returns forbidden for users with write only access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.WRITE),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets returns success for users with manage access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val updatedBudget: BudgetResponse = response.body()
|
||||||
|
assertEquals(request.name, updatedBudget.name)
|
||||||
|
assertEquals(request.description, updatedBudget.description)
|
||||||
|
val expectedUsers = permissions.map { UserPermissionResponse(it.userId, it.permission) }
|
||||||
|
val updatedUsers = updatedBudget.users
|
||||||
|
assertEquals(expectedUsers, updatedUsers)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets returns forbidden for users with no access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating non-existent budgets returns not found`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val request = BudgetRequest("Update Budget", "An update budget for testing")
|
||||||
|
val response = client.put("/api/budgets/random-budget-id") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `updating budgets returns forbidden for users with manage access attempting to remove owner`() =
|
||||||
|
apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget =
|
||||||
|
budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val request = BudgetRequest(
|
||||||
|
"Update Budget",
|
||||||
|
"An update budget for testing",
|
||||||
|
setOf(
|
||||||
|
UserPermissionRequest(users[0].id, Permission.OWNER),
|
||||||
|
UserPermissionRequest(users[0].id, Permission.MANAGE),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deleting budgets requires authentication`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val request = BudgetRequest("Update Budget", "A budget for testing")
|
||||||
|
val response = client.put("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deleting budgets returns forbidden for users with read only access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.READ),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deleting budgets returns forbidden for users with write only access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.WRITE),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deleting budgets returns forbidden for users with manage access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.MANAGE),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Forbidden, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `deleting budgets returns success for users with owner access`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val existingBudget = budgetRepository.save(Budget(name = "Test Budget", description = "A budget for testing"))
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val permissions = setOf(
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[0].id, Permission.OWNER),
|
||||||
|
UserPermission(budgetId = existingBudget.id, userId = users[1].id, Permission.OWNER),
|
||||||
|
)
|
||||||
|
permissions.forEach {
|
||||||
|
permissionRepository.save(it)
|
||||||
|
}
|
||||||
|
val response = client.delete("/api/budgets/${existingBudget.id}") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.NoContent, response.status)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,92 @@
|
||||||
|
package com.wbrawner.twigs.server.api
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.model.PasswordResetToken
|
||||||
|
import com.wbrawner.twigs.randomString
|
||||||
|
import com.wbrawner.twigs.service.ErrorResponse
|
||||||
|
import com.wbrawner.twigs.service.user.PasswordResetRequest
|
||||||
|
import com.wbrawner.twigs.service.user.ResetPasswordRequest
|
||||||
|
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.TEST_USER
|
||||||
|
import io.ktor.client.call.*
|
||||||
|
import io.ktor.client.request.*
|
||||||
|
import io.ktor.http.*
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.*
|
||||||
|
|
||||||
|
class PasswordResetRouteTest : ApiTest() {
|
||||||
|
@Test
|
||||||
|
fun `reset password with invalid username returns 202`() = apiTest { client ->
|
||||||
|
val request = ResetPasswordRequest(username = "invaliduser")
|
||||||
|
val response = client.post("/api/users/resetpassword") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Accepted, response.status)
|
||||||
|
assert(emailService.emails.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `reset password with valid username returns 202`() = apiTest { client ->
|
||||||
|
val request = ResetPasswordRequest(username = "testuser")
|
||||||
|
val response = client.post("/api/users/resetpassword") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Accepted, response.status)
|
||||||
|
assertEquals(1, emailService.emails.size)
|
||||||
|
val email = emailService.emails.first()
|
||||||
|
assertEquals(TEST_USER.email, email.to)
|
||||||
|
assertEquals(1, passwordResetRepository.entities.size)
|
||||||
|
val passwordReset = passwordResetRepository.entities.first()
|
||||||
|
assertEquals(TEST_USER.id, passwordReset.userId)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `password reset with invalid token returns 401`() = apiTest { client ->
|
||||||
|
val request = PasswordResetRequest(token = randomString(), password = "newpass")
|
||||||
|
val response = client.put("/api/users/resetpassword") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val error = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Invalid token", error.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `password reset with expired token returns 401`() = apiTest { client ->
|
||||||
|
val token = passwordResetRepository.save(PasswordResetToken(expiration = twoWeeksAgo))
|
||||||
|
val request = PasswordResetRequest(token = token.id, password = "newpass")
|
||||||
|
val response = client.put("/api/users/resetpassword") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val error = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Token expired", error.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `password reset with valid token returns 204`() = apiTest { client ->
|
||||||
|
val token =
|
||||||
|
passwordResetRepository.save(PasswordResetToken(userId = userRepository.findAll("testuser").first().id))
|
||||||
|
val request = PasswordResetRequest(token = token.id, password = "newpass")
|
||||||
|
val response = client.put("/api/users/resetpassword") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.NoContent, response.status)
|
||||||
|
assertEquals(
|
||||||
|
"newpass",
|
||||||
|
userRepository.findAll(TEST_USER.name).first().password
|
||||||
|
)
|
||||||
|
assert(passwordResetRepository.entities.isEmpty())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val twoWeeksAgo: Instant
|
||||||
|
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
|
||||||
|
add(Calendar.DATE, -14)
|
||||||
|
toInstant()
|
||||||
|
}
|
|
@ -0,0 +1,249 @@
|
||||||
|
package com.wbrawner.twigs.server.api
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.model.Session
|
||||||
|
import com.wbrawner.twigs.model.User
|
||||||
|
import com.wbrawner.twigs.service.ErrorResponse
|
||||||
|
import com.wbrawner.twigs.service.user.*
|
||||||
|
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.OTHER_USER
|
||||||
|
import com.wbrawner.twigs.test.helpers.repository.FakeUserRepository.Companion.TEST_USER
|
||||||
|
import io.ktor.client.call.*
|
||||||
|
import io.ktor.client.request.*
|
||||||
|
import io.ktor.http.*
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertNotNull
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
|
||||||
|
class UserRouteTest : ApiTest() {
|
||||||
|
@Test
|
||||||
|
fun `login with invalid username returns 401`() = apiTest { client ->
|
||||||
|
val request = LoginRequest("invalid", "pass")
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Invalid credentials", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login with empty username returns 401`() = apiTest { client ->
|
||||||
|
val request = LoginRequest("", "pass")
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Invalid credentials", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login with invalid password returns 401`() = apiTest { client ->
|
||||||
|
val request = LoginRequest(TEST_USER.name, "pass")
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Invalid credentials", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login with empty password returns 401`() = apiTest { client ->
|
||||||
|
val request = LoginRequest(TEST_USER.name, "")
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("Invalid credentials", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login with valid username and password returns 200`() = apiTest { client ->
|
||||||
|
val request = LoginRequest(TEST_USER.name, TEST_USER.password)
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val session = response.body<SessionResponse>()
|
||||||
|
assertEquals(TEST_USER.id, session.userId)
|
||||||
|
assert(session.token.isNotBlank())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `login with valid email and password returns 200`() = apiTest { client ->
|
||||||
|
val request = LoginRequest(requireNotNull(TEST_USER.email), TEST_USER.password)
|
||||||
|
val response = client.post("/api/users/login") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val session = response.body<SessionResponse>()
|
||||||
|
assertEquals(TEST_USER.id, session.userId)
|
||||||
|
assert(session.token.isNotBlank())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with null username returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(password = "")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("username must not be null or blank", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with empty username returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(username = "", password = "")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("username must not be null or blank", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with null password returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(username = "test@example.com")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("password must not be null or blank", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with empty password returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(username = "test@example.com", password = "")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("password must not be null or blank", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with existing username returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(username = TEST_USER.name, password = "password")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("username or email already taken", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with existing email returns 400`() = apiTest { client ->
|
||||||
|
val request = UserRequest(username = "testuser2", email = TEST_USER.email, password = "password")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val errorBody = response.body<ErrorResponse>()
|
||||||
|
assertEquals("username or email already taken", errorBody.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `register with valid username and password returns 200`() = apiTest { client ->
|
||||||
|
val initialUserCount = userRepository.entities.size
|
||||||
|
val request = UserRequest("newuser", "newpass")
|
||||||
|
val response = client.post("/api/users/register") {
|
||||||
|
header("Content-Type", "application/json")
|
||||||
|
setBody(request)
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val userResponse = response.body<UserResponse>()
|
||||||
|
assert(userResponse.id.isNotBlank())
|
||||||
|
assertEquals(request.username, userResponse.username)
|
||||||
|
assertEquals(null, userResponse.email)
|
||||||
|
assertEquals(initialUserCount + 1, userRepository.entities.size)
|
||||||
|
val savedUser: User? = userRepository.findAll("newuser").firstOrNull()
|
||||||
|
assertNotNull(savedUser)
|
||||||
|
requireNotNull(savedUser)
|
||||||
|
assertEquals(userResponse.id, savedUser.id)
|
||||||
|
assertEquals(request.username, savedUser.name)
|
||||||
|
assertEquals(null, savedUser.email)
|
||||||
|
assertEquals("newpass", savedUser.password)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `get users requires authentication`() = apiTest { client ->
|
||||||
|
val response = client.get("/api/users")
|
||||||
|
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `get users with empty query returns 400`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val response = client.get("/api/users?query=") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
val error: ErrorResponse = response.body()
|
||||||
|
assertEquals("query cannot be empty", error.message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `get users with valid query but no matches returns empty list`() = apiTest { client ->
|
||||||
|
val users = listOf(
|
||||||
|
User(name = "testuser", password = "testpassword"),
|
||||||
|
User(name = "otheruser", password = "otherpassword"),
|
||||||
|
)
|
||||||
|
users.forEach { userRepository.save(it) }
|
||||||
|
val session = Session(userId = users.first().id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val response = client.get("/api/users?query=something") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val userQueryResponse: List<UserResponse> = response.body()
|
||||||
|
assertEquals(0, userQueryResponse.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `get users with valid query and matches returns list`() = apiTest { client ->
|
||||||
|
val session = Session(userId = TEST_USER.id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val response = client.get("/api/users?query=user") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.OK, response.status)
|
||||||
|
val userQueryResponse: List<UserResponse> = response.body()
|
||||||
|
assertEquals(2, userQueryResponse.size)
|
||||||
|
assertEquals(TEST_USER.asResponse(), userQueryResponse[0])
|
||||||
|
assertEquals(OTHER_USER.asResponse(), userQueryResponse[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `get users with empty budgetId returns 400`() = apiTest { client ->
|
||||||
|
val session = Session(userId = TEST_USER.id)
|
||||||
|
sessionRepository.save(session)
|
||||||
|
val response = client.get("/api/users?budgetId=") {
|
||||||
|
header("Authorization", "Bearer ${session.token}")
|
||||||
|
}
|
||||||
|
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||||
|
}
|
||||||
|
}
|
29
build.gradle
29
build.gradle
|
@ -1,29 +0,0 @@
|
||||||
buildscript {
|
|
||||||
repositories {
|
|
||||||
mavenLocal()
|
|
||||||
mavenCentral()
|
|
||||||
maven { url "http://repo.spring.io/snapshot" }
|
|
||||||
maven { url "http://repo.spring.io/milestone" }
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
|
||||||
classpath "org.springframework.boot:spring-boot-gradle-plugin:2.4.3"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
apply plugin: 'java'
|
|
||||||
|
|
||||||
allprojects {
|
|
||||||
repositories {
|
|
||||||
mavenLocal()
|
|
||||||
mavenCentral()
|
|
||||||
maven { url "http://repo.spring.io/snapshot" }
|
|
||||||
maven { url "http://repo.spring.io/milestone" }
|
|
||||||
maven { url "http://repo.maven.apache.org/maven2" }
|
|
||||||
}
|
|
||||||
|
|
||||||
jar {
|
|
||||||
group = "com.wbrawner"
|
|
||||||
archiveVersion.set("0.0.1-SNAPSHOT")
|
|
||||||
}
|
|
||||||
}
|
|
40
build.gradle.kts
Normal file
40
build.gradle.kts
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
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,4 +0,0 @@
|
||||||
{
|
|
||||||
"schemaVersion": 2,
|
|
||||||
"dockerfilePath": "./Dockerfile"
|
|
||||||
}
|
|
1
core/.gitignore
vendored
Normal file
1
core/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
||||||
|
build/
|
15
core/build.gradle.kts
Normal file
15
core/build.gradle.kts
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
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()
|
||||||
|
}
|
7
core/src/main/kotlin/com/wbrawner/twigs/EmailService.kt
Normal file
7
core/src/main/kotlin/com/wbrawner/twigs/EmailService.kt
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
package com.wbrawner.twigs
|
||||||
|
|
||||||
|
import com.wbrawner.twigs.model.PasswordResetToken
|
||||||
|
|
||||||
|
interface EmailService {
|
||||||
|
fun sendPasswordResetEmail(token: PasswordResetToken, to: String)
|
||||||
|
}
|
5
core/src/main/kotlin/com/wbrawner/twigs/Identifiable.kt
Normal file
5
core/src/main/kotlin/com/wbrawner/twigs/Identifiable.kt
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
package com.wbrawner.twigs
|
||||||
|
|
||||||
|
interface Identifiable {
|
||||||
|
val id: String
|
||||||
|
}
|
5
core/src/main/kotlin/com/wbrawner/twigs/Logger.kt
Normal file
5
core/src/main/kotlin/com/wbrawner/twigs/Logger.kt
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
package com.wbrawner.twigs
|
||||||
|
|
||||||
|
interface Logger {
|
||||||
|
fun log(message: String)
|
||||||
|
}
|
62
core/src/main/kotlin/com/wbrawner/twigs/Utils.kt
Normal file
62
core/src/main/kotlin/com/wbrawner/twigs/Utils.kt
Normal file
|
@ -0,0 +1,62 @@
|
||||||
|
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)
|
11
core/src/main/kotlin/com/wbrawner/twigs/model/Budget.kt
Normal file
11
core/src/main/kotlin/com/wbrawner/twigs/model/Budget.kt
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
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
|
14
core/src/main/kotlin/com/wbrawner/twigs/model/Category.kt
Normal file
14
core/src/main/kotlin/com/wbrawner/twigs/model/Category.kt
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
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
|
|
@ -0,0 +1,12 @@
|
||||||
|
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
|
|
@ -0,0 +1,197 @@
|
||||||
|
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
|
||||||
|
}
|
25
core/src/main/kotlin/com/wbrawner/twigs/model/Session.kt
Normal file
25
core/src/main/kotlin/com/wbrawner/twigs/model/Session.kt
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
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)
|
17
core/src/main/kotlin/com/wbrawner/twigs/model/Transaction.kt
Normal file
17
core/src/main/kotlin/com/wbrawner/twigs/model/Transaction.kt
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
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,24 +1,44 @@
|
||||||
package com.wbrawner.budgetserver.permission;
|
package com.wbrawner.twigs.model
|
||||||
|
|
||||||
public enum Permission {
|
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.
|
* The user can read the content but cannot make any modifications.
|
||||||
*/
|
*/
|
||||||
READ,
|
READ,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The user can read and write the content but cannot make any modifications to the container of the content.
|
* The user can read and write the content but cannot make any modifications to the container of the content.
|
||||||
*/
|
*/
|
||||||
WRITE,
|
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).
|
* 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,
|
MANAGE,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The user has complete control over the resource. There can only be a single owner user at any given time.
|
* The user has complete control over the resource. There can only be a single owner user at any given time.
|
||||||
*/
|
*/
|
||||||
OWNER;
|
OWNER;
|
||||||
|
|
||||||
public boolean isNotAtLeast(Permission wanted) {
|
fun isAtLeast(wanted: Permission): Boolean {
|
||||||
return ordinal() < wanted.ordinal();
|
return ordinal >= wanted.ordinal
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
data class UserPermission(
|
||||||
|
val budgetId: String,
|
||||||
|
val userId: String,
|
||||||
|
val permission: Permission = Permission.READ
|
||||||
|
)
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue