Compare commits

...

195 commits

Author SHA1 Message Date
ff03e8331d Update dependency gradle to v8.11.1
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m35s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 14m15s
2024-11-20 18:11:49 +00:00
41748200cc Update ktor to v2.3.13
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m46s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h15m59s
2024-11-20 16:03:39 +00:00
67944d6017 Update dependency com.zaxxer:HikariCP to v6.2.1
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m40s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 59m48s
2024-11-18 11:04:04 +00:00
9537d8b6bc Update dependency gradle to v8.11
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m45s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h14m39s
2024-11-11 22:07:28 +00:00
8d68d54a31 Update dependency com.zaxxer:HikariCP to v6.1.0
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m19s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h8m19s
2024-11-06 02:04:06 +00:00
1e33bedfff Update dependency ch.qos.logback:logback-classic to v1.5.12
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m59s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h13m7s
2024-10-25 21:03:17 +00:00
6020fd647f Update dependency org.junit.jupiter:junit-jupiter-api to v5.11.3
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m41s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h10m2s
2024-10-23 04:05:11 +00:00
a9165e9867 Update dependency org.xerial:sqlite-jdbc to v3.47.0.0
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m48s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m32s
2024-10-23 03:03:26 +00:00
5918e351c2 Update dependency ch.qos.logback:logback-classic to v1.5.11
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m38s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h10m51s
2024-10-15 11:06:02 +00:00
c4fb0b3391 Update dependency ch.qos.logback:logback-classic to v1.5.10
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m36s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h8m58s
2024-10-12 09:06:10 +00:00
00afb3f4bf Update kotlin to v2.0.21
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m42s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m9s
2024-10-10 10:13:59 +00:00
374b2a79b0 Update dependency ch.qos.logback:logback-classic to v1.5.9
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m9s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h11m19s
2024-10-08 14:03:23 +00:00
7175036135 Update dependency org.junit.jupiter:junit-jupiter-api to v5.11.2
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m47s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h11m39s
2024-10-04 14:03:28 +00:00
5ae22d6d36 Update postgres Docker tag to v17
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 7m26s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 3m57s
2024-09-27 03:08:25 +00:00
d04dfa1bd5 Update dependency org.xerial:sqlite-jdbc to v3.46.1.3
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 5m35s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 40m38s
2024-09-26 09:09:14 +00:00
a5039c27b1 Update dependency org.xerial:sqlite-jdbc to v3.46.1.2
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m56s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h14m16s
2024-09-25 12:07:48 +00:00
a5600fee0a Update dependency org.junit.jupiter:junit-jupiter-api to v5.11.1
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m50s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m54s
2024-09-25 08:09:10 +00:00
ea188430d0 Update dependency org.xerial:sqlite-jdbc to v3.46.1.1
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m52s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h10m52s
2024-09-25 02:08:16 +00:00
cbfe0b2131 Update dependency gradle to v8.10.2
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m38s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m1s
2024-09-23 22:21:03 +00:00
58bcd48ea7 Update dependency com.zaxxer:HikariCP to v6
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m46s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h15m27s
2024-09-23 21:08:48 +00:00
9843046db7 Update kotlinx.coroutines to v1.9.0
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m28s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h11m3s
2024-09-16 20:09:49 +00:00
a737f40398 Update dependency gradle to v8.10.1
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m44s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h9m5s
2024-09-09 09:15:51 +00:00
84ad21011a Update dependency ch.qos.logback:logback-classic to v1.5.8
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m59s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m43s
2024-09-06 21:08:34 +00:00
3bb586bf14 Update dependency org.postgresql:postgresql to v42.7.4
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 3m56s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h8m58s
2024-08-22 20:09:18 +00:00
b58cbfc388 Update kotlin to v2.0.20
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 6m38s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h12m34s
2024-08-22 09:09:55 +00:00
92bb5a4827 Update dependency org.xerial:sqlite-jdbc to v3.46.1.0
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 7m13s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h16m28s
2024-08-19 03:06:47 +00:00
287576f3c2 Update dependency ch.qos.logback:logback-classic to v1.5.7
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 7m6s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 27s
2024-08-15 17:06:09 +00:00
14861078c0 Update dependency gradle to v8.10
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m50s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 22s
2024-08-14 12:15:03 +00:00
6ab4f20137 Update dependency org.junit.jupiter:junit-jupiter-api to v5.11.0
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 4m56s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 22s
2024-08-14 10:06:12 +00:00
4f2c1f067a Update kotlin to v2.0.10
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m52s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 21s
2024-08-06 10:07:35 +00:00
134814c515 Update dependency org.xerial:sqlite-jdbc to v3.46.0.1
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 4m4s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h14m55s
2024-07-30 13:04:01 +00:00
b9e212c2c0 Update dependency gradle to v8.9
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 5m53s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h20m28s
2024-07-11 15:06:43 +00:00
3434bf099c
Fix some styling issues for forms
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 3m34s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h16m22s
2024-07-07 10:54:49 -06:00
5aef4630a6
Switch to ibm-semeru for docker images
All checks were successful
Pull request workflow / Build and Test (pull_request) Successful in 3m40s
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 1h15m50s
2024-07-07 10:22:57 -06:00
d13b784826 Update postgres Docker tag to v16
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m21s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m25s
2024-07-07 11:01:45 +00:00
3d5bf4af1f Update openjdk Docker tag to v24
Some checks failed
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m24s
2024-07-07 10:12:34 +00:00
d1ef0bfb1c Update gradle/wrapper-validation-action action to v3
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m27s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 10:01:54 +00:00
fbc936e2bb Update gradle/gradle-build-action action to v3
Some checks failed
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m17s
2024-07-07 09:12:53 +00:00
b761256862 Update docker/setup-qemu-action action to v3
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m25s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 09:02:00 +00:00
02b60757bb Update docker/setup-buildx-action action to v3
Some checks failed
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m10s
2024-07-07 08:12:29 +00:00
0ecc077b9d Update docker/metadata-action action to v5
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m29s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 08:01:55 +00:00
2d3c987be0 Update docker/login-action action to v3
Some checks failed
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m19s
2024-07-07 07:12:40 +00:00
4b5827b315 Update docker/build-push-action action to v6
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m16s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 07:02:15 +00:00
6c96c6f2c2 Update actions/setup-java action to v4
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m34s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m13s
2024-07-07 06:01:54 +00:00
0b26bf9240 Update actions/checkout action to v4
Some checks failed
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 1m17s
2024-07-07 05:12:26 +00:00
a66c934d79 Update dependency gradle to v8.8
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 3m44s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 05:03:44 +00:00
d5a449c719 Update ktor to v2.3.12
All checks were successful
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 32m49s
2024-07-07 04:11:29 +00:00
d1d3814839 Update dependency org.junit.jupiter:junit-jupiter-api to v5.10.3
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 5m3s
Publish Docker image / Push Docker image to Forgejo Packages (push) Has been cancelled
2024-07-07 04:01:54 +00:00
d062fa056e Fix docker image workflow
All checks were successful
Publish Docker image / Push Docker image to Forgejo Packages (push) Successful in 33m44s
2024-07-07 03:15:31 +00:00
21cc7ff0ce Add renovate.json
Some checks failed
Pull request workflow / Build and Test (pull_request) Successful in 4m57s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 17s
2024-07-07 02:50:10 +00:00
d391c60f91
Remove dependabot config and add Forgejo workflows
Some checks failed
Enable Auto Merge / auto-merge (pull_request) Failing after 3s
Pull request workflow / Build and Test (pull_request) Successful in 5m44s
Publish Docker image / Push Docker image to Forgejo Packages (push) Failing after 17s
2024-07-06 20:48:44 -06:00
dependabot[bot]
2dc415553d Bump org.xerial:sqlite-jdbc from 3.45.3.0 to 3.46.0.0
Bumps [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.45.3.0 to 3.46.0.0.
- [Release notes](https://github.com/xerial/sqlite-jdbc/releases)
- [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG)
- [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.45.3.0...3.46.0.0)

---
updated-dependencies:
- dependency-name: org.xerial:sqlite-jdbc
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-03 02:52:37 -06:00
dependabot[bot]
960723c6e4 Bump kotlinx-coroutines from 1.8.0 to 1.8.1
Bumps `kotlinx-coroutines` from 1.8.0 to 1.8.1.

Updates `org.jetbrains.kotlinx:kotlinx-coroutines-core` from 1.8.0 to 1.8.1
- [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases)
- [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md)
- [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.8.0...1.8.1)

Updates `org.jetbrains.kotlinx:kotlinx-coroutines-test` from 1.8.0 to 1.8.1
- [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases)
- [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md)
- [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.8.0...1.8.1)

---
updated-dependencies:
- dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-test
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-27 03:12:08 -06:00
dependabot[bot]
cb8e9ecf7a Bump kotlin from 1.9.24 to 2.0.0
Bumps `kotlin` from 1.9.24 to 2.0.0.

Updates `org.jetbrains.kotlin:kotlin-gradle-plugin` from 1.9.24 to 2.0.0
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v2.0.0/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.24...v2.0.0)

Updates `org.jetbrains.kotlin:kotlin-reflect` from 1.9.24 to 2.0.0
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v2.0.0/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.24...v2.0.0)

Updates `org.jetbrains.kotlin:kotlin-test-junit` from 1.9.24 to 2.0.0
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v2.0.0/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.24...v2.0.0)

Updates `org.jetbrains.kotlin.jvm` from 1.9.24 to 2.0.0
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v2.0.0/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.24...v2.0.0)

Updates `org.jetbrains.kotlin.plugin.serialization` from 1.9.24 to 2.0.0
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v2.0.0/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.24...v2.0.0)

---
updated-dependencies:
- dependency-name: org.jetbrains.kotlin:kotlin-gradle-plugin
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: org.jetbrains.kotlin:kotlin-reflect
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: org.jetbrains.kotlin:kotlin-test-junit
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: org.jetbrains.kotlin.jvm
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: org.jetbrains.kotlin.plugin.serialization
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-27 03:09:31 -06:00
dependabot[bot]
426a522683 Bump ktor from 2.3.10 to 2.3.11
Bumps `ktor` from 2.3.10 to 2.3.11.

Updates `io.ktor:ktor-client-content-negotiation` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-serialization-kotlinx-json` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-auth` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-call-logging` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-cio` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-content-negotiation` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-core` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-cors` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-forwarded-header` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-mustache` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-sessions` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

Updates `io.ktor:ktor-server-test-host` from 2.3.10 to 2.3.11
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.11/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.10...2.3.11)

---
updated-dependencies:
- dependency-name: io.ktor:ktor-client-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-serialization-kotlinx-json
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-auth
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-call-logging
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cio
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cors
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-forwarded-header
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-mustache
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-sessions
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-test-host
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-13 03:04:42 -06:00
dependabot[bot]
b6dc6693e2 Bump kotlin from 1.9.23 to 1.9.24
Bumps `kotlin` from 1.9.23 to 1.9.24.

Updates `org.jetbrains.kotlin:kotlin-gradle-plugin` from 1.9.23 to 1.9.24
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.23...v1.9.24)

Updates `org.jetbrains.kotlin:kotlin-reflect` from 1.9.23 to 1.9.24
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.23...v1.9.24)

Updates `org.jetbrains.kotlin:kotlin-test-junit` from 1.9.23 to 1.9.24
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.23...v1.9.24)

Updates `org.jetbrains.kotlin.jvm` from 1.9.23 to 1.9.24
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.23...v1.9.24)

Updates `org.jetbrains.kotlin.plugin.serialization` from 1.9.23 to 1.9.24
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.23...v1.9.24)

---
updated-dependencies:
- dependency-name: org.jetbrains.kotlin:kotlin-gradle-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin:kotlin-reflect
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin:kotlin-test-junit
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin.jvm
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin.plugin.serialization
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-13 03:03:38 -06:00
dependabot[bot]
488193bba8 Bump org.xerial:sqlite-jdbc from 3.45.2.0 to 3.45.3.0
Bumps [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.45.2.0 to 3.45.3.0.
- [Release notes](https://github.com/xerial/sqlite-jdbc/releases)
- [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG)
- [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.45.2.0...3.45.3.0)

---
updated-dependencies:
- dependency-name: org.xerial:sqlite-jdbc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-22 02:56:53 -06:00
dependabot[bot]
96f563af56 Bump ch.qos.logback:logback-classic from 1.5.5 to 1.5.6
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.5.5 to 1.5.6.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.5.5...v_1.5.6)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-22 02:56:43 -06:00
c60eff2cbb Add more debug logging around failed logins 2024-04-21 10:27:57 -06:00
e92ffd376a Add XForwardedHeaders plugin 2024-04-21 10:05:43 -06:00
22061e3f4a Add logout link in sidebar 2024-04-21 10:05:43 -06:00
955ee0f126 Fix failure in UserRouteTest 2024-04-20 22:06:44 -06:00
197fee1033 Fix kotlinx serialization not being applied 2024-04-20 22:06:44 -06:00
f1dc6bbca3 Fix paths to icons in manifest.json 2024-04-20 22:06:44 -06:00
c4fea5a06f Comment out unimplemented pages in sidebar 2024-04-20 22:06:44 -06:00
b1267dd4cf Update README 2024-04-20 22:06:44 -06:00
d8b89bc8d2 Implement transaction list page and ensure consistency with budget list in sidebar 2024-04-20 22:06:44 -06:00
689dbc39e2 Implement deletion of budgets, categories, and transactions 2024-04-20 22:06:44 -06:00
ef1deaf19b Implement category creation/editing 2024-04-20 22:06:44 -06:00
59aa48817a More progress on transaction editing, also removed some debug logging for hikari and set the docker compose file to use postgres 2024-04-20 22:06:44 -06:00
64e7cb9d52 Add transaction form page 2024-04-20 22:06:44 -06:00
5a9b988c63 Fix styles for various form inputs 2024-04-20 22:06:44 -06:00
961c60a183 Use SameSite=Strict for session cookie 2024-04-20 22:06:44 -06:00
fed06cd155 Add transaction details page 2024-04-20 22:06:44 -06:00
e8d3719adc Add category details page 2024-04-20 22:06:44 -06:00
978de59d36 More work on budget details page 2024-04-20 22:06:44 -06:00
7e49dbeb31 Add some budget pages
I also added titles to the other pages, but it needs styling
2024-04-20 22:06:44 -06:00
a2579dbd6d Fix form disabling upon submission
Turns out if you disable everything then nothing is sent!
2024-04-20 22:06:44 -06:00
7a8c9c1035 Disable forms upon submission
This is an attempt to avoid duplicate submissions
2024-04-20 22:06:44 -06:00
1e14057dfa Add mustache support with static assets and functional login/registration 2024-04-20 22:06:44 -06:00
dependabot[bot]
040af1ba36 Bump ch.qos.logback:logback-classic from 1.5.3 to 1.5.5
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.5.3 to 1.5.5.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.5.3...v_1.5.5)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-15 02:42:01 -06:00
dependabot[bot]
3c4fc35daa Bump ktor from 2.3.9 to 2.3.10
Bumps `ktor` from 2.3.9 to 2.3.10.

Updates `io.ktor:ktor-client-content-negotiation` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-serialization-kotlinx-json` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-auth` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-call-logging` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-cio` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-content-negotiation` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-core` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-cors` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-html-builder` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-sessions` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

Updates `io.ktor:ktor-server-test-host` from 2.3.9 to 2.3.10
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/commits)

---
updated-dependencies:
- dependency-name: io.ktor:ktor-client-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-serialization-kotlinx-json
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-auth
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-call-logging
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cio
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cors
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-html-builder
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-sessions
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-test-host
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-08 03:04:32 -06:00
dependabot[bot]
e537b1b32a Bump org.xerial:sqlite-jdbc from 3.45.1.0 to 3.45.2.0
Bumps [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.45.1.0 to 3.45.2.0.
- [Release notes](https://github.com/xerial/sqlite-jdbc/releases)
- [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG)
- [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.45.1.0...3.45.2.0)

---
updated-dependencies:
- dependency-name: org.xerial:sqlite-jdbc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-27 20:29:40 -06:00
dependabot[bot]
9877d9288b Bump org.postgresql:postgresql from 42.7.2 to 42.7.3
Bumps [org.postgresql:postgresql](https://github.com/pgjdbc/pgjdbc) from 42.7.2 to 42.7.3.
- [Release notes](https://github.com/pgjdbc/pgjdbc/releases)
- [Changelog](https://github.com/pgjdbc/pgjdbc/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pgjdbc/pgjdbc/compare/REL42.7.2...REL42.7.3)

---
updated-dependencies:
- dependency-name: org.postgresql:postgresql
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-27 20:26:50 -06:00
dfe81b7a2f Fix permissions for pull request workflow 2024-03-27 20:22:05 -06:00
76237b331a Fix permissions for pull request workflow 2024-03-27 20:22:05 -06:00
5e8337da29
Fix PR workflow 2024-03-27 17:01:25 -06:00
9a01fb39ec Finish implementing remaining service classes 2024-03-27 16:59:18 -06:00
a460421497 WIP: Move API logic to shared services 2024-03-27 16:59:18 -06:00
2b66ea916b Split auto-merge into separate workflow 2024-03-27 16:53:53 -06:00
94a373f779 Fix PR workflows 2024-03-14 22:42:35 -06:00
e4e77c4df7
Only run docker-image workflow after a PR is merged 2024-03-14 21:34:29 -06:00
bd9c0e5857
Run docker-image workflow when PRs on main are merged 2024-03-14 21:33:30 -06:00
dependabot[bot]
f3b1976a0b Bump at.favre.lib:bcrypt from 0.9.0 to 0.10.2
Bumps [at.favre.lib:bcrypt](https://github.com/patrickfav/bcrypt) from 0.9.0 to 0.10.2.
- [Release notes](https://github.com/patrickfav/bcrypt/releases)
- [Changelog](https://github.com/patrickfav/bcrypt/blob/main/CHANGELOG)
- [Commits](https://github.com/patrickfav/bcrypt/compare/v0.9.0...v0.10.2)

---
updated-dependencies:
- dependency-name: at.favre.lib:bcrypt
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 08:48:18 +00:00
dependabot[bot]
f90c68ca06 Bump org.junit.jupiter:junit-jupiter-api from 5.8.2 to 5.10.2
Bumps [org.junit.jupiter:junit-jupiter-api](https://github.com/junit-team/junit5) from 5.8.2 to 5.10.2.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.8.2...r5.10.2)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter-api
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 08:48:12 +00:00
dependabot[bot]
2fc1aebaac Bump com.github.johnrengelman.shadow from 7.0.0 to 8.1.1
Bumps com.github.johnrengelman.shadow from 7.0.0 to 8.1.1.

---
updated-dependencies:
- dependency-name: com.github.johnrengelman.shadow
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 08:45:56 +00:00
dependabot[bot]
be58b72e04 Bump com.zaxxer:HikariCP from 5.0.1 to 5.1.0
Bumps [com.zaxxer:HikariCP](https://github.com/brettwooldridge/HikariCP) from 5.0.1 to 5.1.0.
- [Changelog](https://github.com/brettwooldridge/HikariCP/blob/dev/CHANGES)
- [Commits](https://github.com/brettwooldridge/HikariCP/compare/HikariCP-5.0.1...HikariCP-5.1.0)

---
updated-dependencies:
- dependency-name: com.zaxxer:HikariCP
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 08:45:40 +00:00
dependabot[bot]
d80d0273bc Bump kotlin from 1.9.10 to 1.9.23
Bumps `kotlin` from 1.9.10 to 1.9.23.

Updates `org.jetbrains.kotlin:kotlin-gradle-plugin` from 1.9.10 to 1.9.23
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.9.23/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.10...v1.9.23)

Updates `org.jetbrains.kotlin:kotlin-reflect` from 1.9.10 to 1.9.23
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.9.23/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.10...v1.9.23)

Updates `org.jetbrains.kotlin:kotlin-test-junit` from 1.9.10 to 1.9.23
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.9.23/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.10...v1.9.23)

Updates `org.jetbrains.kotlin.jvm` from 1.9.10 to 1.9.23
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.9.23/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.10...v1.9.23)

Updates `org.jetbrains.kotlin.plugin.serialization` from 1.9.10 to 1.9.23
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.9.23/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.9.10...v1.9.23)

---
updated-dependencies:
- dependency-name: org.jetbrains.kotlin:kotlin-gradle-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin:kotlin-reflect
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin:kotlin-test-junit
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin.jvm
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: org.jetbrains.kotlin.plugin.serialization
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-11 08:45:24 +00:00
dependabot[bot]
3c14ebd2bf Bump org.xerial:sqlite-jdbc from 3.42.0.0 to 3.45.1.0
Bumps [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.42.0.0 to 3.45.1.0.
- [Release notes](https://github.com/xerial/sqlite-jdbc/releases)
- [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG)
- [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.42.0.0...3.45.1.0)

---
updated-dependencies:
- dependency-name: org.xerial:sqlite-jdbc
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-09 14:37:26 -07:00
dependabot[bot]
9a148b8984 Bump kotlinx-coroutines from 1.6.2 to 1.8.0
Bumps `kotlinx-coroutines` from 1.6.2 to 1.8.0.

Updates `org.jetbrains.kotlinx:kotlinx-coroutines-core` from 1.6.2 to 1.8.0
- [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases)
- [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md)
- [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.6.2...1.8.0)

Updates `org.jetbrains.kotlinx:kotlinx-coroutines-test` from 1.6.2 to 1.8.0
- [Release notes](https://github.com/Kotlin/kotlinx.coroutines/releases)
- [Changelog](https://github.com/Kotlin/kotlinx.coroutines/blob/master/CHANGES.md)
- [Commits](https://github.com/Kotlin/kotlinx.coroutines/compare/1.6.2...1.8.0)

---
updated-dependencies:
- dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-core
  dependency-type: direct:production
  update-type: version-update:semver-minor
- dependency-name: org.jetbrains.kotlinx:kotlinx-coroutines-test
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-09 14:37:17 -07:00
dependabot[bot]
16845b3129 Bump ch.qos.logback:logback-classic from 1.2.11 to 1.5.3
Bumps [ch.qos.logback:logback-classic](https://github.com/qos-ch/logback) from 1.2.11 to 1.5.3.
- [Commits](https://github.com/qos-ch/logback/compare/v_1.2.11...v_1.5.3)

---
updated-dependencies:
- dependency-name: ch.qos.logback:logback-classic
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-09 14:37:08 -07:00
e7d0093ede Switch to AGPLv3 2024-03-09 16:34:20 +00:00
dependabot[bot]
d480ebc63c Bump ktor from 2.3.4 to 2.3.9
Bumps `ktor` from 2.3.4 to 2.3.9.

Updates `io.ktor:ktor-client-content-negotiation` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-serialization-kotlinx-json` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-auth` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-call-logging` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-cio` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-content-negotiation` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-core` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-cors` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-sessions` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

Updates `io.ktor:ktor-server-test-host` from 2.3.4 to 2.3.9
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/2.3.9/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/2.3.4...2.3.9)

---
updated-dependencies:
- dependency-name: io.ktor:ktor-client-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-serialization-kotlinx-json
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-auth
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-call-logging
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cio
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-content-negotiation
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-core
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-cors
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-sessions
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: io.ktor:ktor-server-test-host
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-09 09:33:22 -07:00
dependabot[bot]
45dfa9a681 Bump org.postgresql:postgresql from 42.3.8 to 42.7.2
Bumps [org.postgresql:postgresql](https://github.com/pgjdbc/pgjdbc) from 42.3.8 to 42.7.2.
- [Release notes](https://github.com/pgjdbc/pgjdbc/releases)
- [Changelog](https://github.com/pgjdbc/pgjdbc/blob/master/CHANGELOG.md)
- [Commits](https://github.com/pgjdbc/pgjdbc/compare/REL42.3.8...REL42.7.2)

---
updated-dependencies:
- dependency-name: org.postgresql:postgresql
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-03-09 16:29:40 +00:00
b5ee8fffd1 Use rebase for auto merge workflow 2024-03-09 16:25:23 +00:00
d3fb723611 Enable auto-merge for PRs from dependabot 2024-03-09 09:13:57 -07:00
e934ebf4e4 Add dependabot.yml 2024-03-09 09:13:57 -07:00
8a128a1104 Update deprecated method calls in front end 2024-03-09 09:13:57 -07:00
0fe4072a6e Bump gradle wrapper version 2024-03-09 09:13:57 -07:00
6b9c34d5d1 Remove config file, just load data from env 2024-03-09 09:13:57 -07:00
4ae19c09c2 Fix failures in UserRouteTest 2024-03-09 09:03:30 -07:00
aa96cbbf3a Add more tests for user routes 2024-03-09 09:03:30 -07:00
1060e35019 Add test for get users 2024-03-09 09:03:30 -07:00
4cc3a6c070 Add tests for password reset routes 2024-03-09 09:03:30 -07:00
0a99788a2f Add tests for reset password 2024-03-09 09:03:30 -07:00
589bc18069 Add tests for user registration routes 2024-03-09 09:03:30 -07:00
c3a4e94bd4 Add tests for UserRoutes 2024-03-09 09:03:30 -07:00
f9bf4eed65 Remove unused workflow parameter 2024-03-09 09:03:30 -07:00
619c243b8f Set java version to 17 for pull request workflow 2024-03-09 09:03:30 -07:00
fcf9bc6cd3 Fix compilation 2024-03-09 09:03:30 -07:00
d02f472e48 Bump gradle wrapper version 2024-03-09 09:03:30 -07:00
2ae81f7f82 Fix gradle build CI task 2024-03-09 09:03:30 -07:00
f9dfbe719d Fix gradle build CI task 2024-03-09 09:03:30 -07:00
e86427e152 Re-enable automerge 2024-03-09 09:03:30 -07:00
a1f4f3a693 Fix test reporter job 2024-03-09 09:03:30 -07:00
9d42cee5e3 Show failed tests in CI 2024-03-09 09:03:30 -07:00
e10ed36838 Rename Unit tests job to Gradle Check 2024-03-09 09:03:30 -07:00
d36b166416 Use --no-daemon and --no-configuration-cache for gradlew tasks 2024-03-09 09:03:30 -07:00
2f29f5d34a Add names for pull request workflow jobs 2024-03-09 09:03:30 -07:00
github-actions[bot]
ff7b80a273
Merge pull request #1 from wbrawner/add-tests
Add tests
2023-09-27 12:40:22 +00:00
4deccdbd0b
Add tests for /api/budget routes 2023-09-26 20:04:55 -06:00
47d7e79d5d Add pull request workflow for GitHub Actions 2023-09-24 20:03:08 -06:00
b6b88afdb2 Add property and env var for DB type 2023-09-24 11:03:23 -06:00
96b833cb52 Add support for sqlite 2023-08-07 20:42:01 -06:00
fb2e04f90e WIP: Add static web frontend 2023-06-19 10:15:44 -06:00
694743e3f2 Check if username/email is taken in registration 2023-06-17 10:15:08 -06:00
1eab86489b Update repository for GitHub Actions builds
Signed-off-by: William Brawner <me@wbrawner.com>
2023-03-04 10:15:03 -07:00
13c4096fe8 Truncate recurring transaction times to seconds
Signed-off-by: William Brawner <me@wbrawner.com>
2023-03-04 09:16:49 -07:00
1fa28fb2e1 Generate OpenAPI Spec
This still needs a lot of love but the generated spec is a good start

Signed-off-by: William Brawner <me@wbrawner.com>
2023-02-18 22:51:51 -07:00
615e4640c6 Remove deploy step from GitHub action
The docker image will still be published to the registry, it'll just no longer auto-update my own personal server.
2023-01-03 21:39:57 -07:00
1d15b116c2 Bump gradle wrapper to 7.6
Signed-off-by: William Brawner <me@wbrawner.com>
2022-12-11 20:27:29 -06:00
747aec51ef Remove caprover-related code
Signed-off-by: William Brawner <me@wbrawner.com>
2022-12-11 20:27:17 -06:00
225bfc6b00
Allow CORS requests from localhost 2022-11-07 20:57:28 -07:00
b170d632e4 Update Ktor to 2.0.2
Signed-off-by: Billy Brawner <me@wbrawner.com>
2022-06-22 13:42:01 -05:00
698051fab1 Update README with environment variable configuration options
Signed-off-by: Billy Brawner <me@wbrawner.com>
2022-06-03 22:50:13 -06:00
909b667c62 Implement password reset
Signed-off-by: Billy Brawner <me@wbrawner.com>
2022-06-03 22:46:02 -06:00
58c6508d0a Use gradle version catalogs 2022-06-02 20:28:44 -06:00
cee28c0e1e Fix RecurringTransactionsResponse sending "null" in finish field 2022-05-28 21:38:01 -06:00
3d7a4d9772 Exclude null values from json encoding 2022-05-28 20:33:53 -06:00
c3df8a252e Fix cross-platform docker builds 2022-05-18 18:38:18 -06:00
1ba8565909 Add docker builds for arm 2022-05-18 18:35:15 -06:00
2a7d674204 Fix monthly recurring transactions not being created when the year changes
The previous implementation only checked that at least one month had passed between the last run date and now by subtracting the ordinal values. If it were February (month 2) and the previous run date were in January (month 1), then 2 - 1 would equal 1, so it would have been one month since the previous run and we would create the recurring transaction. If it were December however (month 12), the following month would be January (month 1), and 1 - 12 would be -11, so it would appear that we had already created a transaction 11 months in the future. The new implementation also takes the year into account to avoid this situation.
2022-02-02 21:21:20 -07:00
f8c970eb68
Fix links to other projects in README 2021-12-21 21:13:16 -07:00
97a6807b84 Fix CORS setup
AnyHost * is not allowed in combination with Allow-Credentials, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
2021-12-18 09:10:22 -07:00
d3de43dcd9 Fix CORS setup
AnyHost * is not allowed in combination with Allow-Credentials, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
2021-12-18 08:56:40 -07:00
04842b6dba Fix CORS setup
AnyHost * is not allowed in combination with Allow-Credentials, see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
2021-12-18 08:56:15 -07:00
b6ccae2abe Run twigs as user instead of root in docker image 2021-12-18 07:44:01 -07:00
6b606b86a9 Bump all dependencies 2021-12-18 07:18:52 -07:00
ab8d213431 Bump logback version 2021-12-18 07:14:17 -07:00
8969a7f2d2 Fix recurring transactions query 2021-12-06 21:41:44 -07:00
82939020f7 Fix: only create recurring transactions that haven't already ended 2021-11-27 21:52:36 -07:00
1fe62dc410 Automatically deploy changes on pushes to main 2021-11-24 16:25:13 -07:00
4bdcc90746 Add support for CORS 2021-11-24 16:14:40 -07:00
58f1b1d373 Fix Dockerfile to not rely on local builds 2021-11-19 10:23:35 -07:00
3ab7d28741 Fix URL to Android repo in README 2021-10-02 14:39:38 -06:00
f85f2057c6 Update README 2021-10-02 14:38:13 -06:00
6bea66e7a5 Fix recurring transactions being created multiple times 2021-09-20 19:48:43 -06:00
fe65921ac0 Add missing SQL migration files 2021-09-19 21:50:51 -06:00
7754bfaae5 Run jobs every hour instead of every day 2021-09-19 20:29:12 -06:00
62eb6b0976 Add test for looping hourly instead of daily 2021-09-19 20:25:55 -06:00
722805f732 fixup! Exclude milliseconds from transaction dates 2021-09-19 20:25:35 -06:00
9446b52e3d Run jobs before delay 2021-09-19 20:21:03 -06:00
a9611eee23 Implement recurring transactions 2021-09-19 20:21:03 -06:00
1ab9af9d17 WIP: Implement recurring transactions 2021-09-19 20:21:02 -06:00
5d26ee9af3 Exclude milliseconds from transaction dates 2021-09-14 19:22:53 -06:00
ca28d32aa9 Minor fixes for web and mobile 2021-08-16 15:25:32 -06:00
f2700f7148 Add frontend web target 2021-08-15 21:10:39 -06:00
ff70db9280 Fix issues with transaction and category routes 2021-08-13 16:09:05 -06:00
2900915842 Fix userRoutes 2021-08-13 10:59:53 -06:00
4ef2fed502 WIP: Finish ktor migration 2021-08-12 15:22:06 -06:00
9fc3d1ac1c Add Transaction routes 2021-08-05 21:00:23 -06:00
f6e0157560 Add user routes 2021-08-05 19:35:42 -06:00
4de09a8f1c Add category routes 2021-08-03 19:55:03 -06:00
ed1dde49bf WIP: Migrate to Ktor 2021-07-29 10:40:22 -06:00
b882d8b089 fixup! Rename api module to app 2021-07-28 18:50:26 -06:00
c38cdb2621 Rename api module to app 2021-07-28 18:49:48 -06:00
7020cc15a5 fixup! fixup! Add ktor dependencies and basic server 2021-07-06 09:48:48 -06:00
6f94dedbe3 fixup! Add ktor dependencies and basic server 2021-07-06 09:18:48 -06:00
3e33f84416 fixup! Move com.wbrawner.budgetserver to com.wbrawner.twigs.server 2021-07-06 09:18:23 -06:00
bcb58d47d7 Add ktor dependencies and basic server 2021-07-05 19:08:09 -06:00
00ffbbe303 Move com.wbrawner.budgetserver to com.wbrawner.twigs.server 2021-07-05 19:07:19 -06:00
ab73dfcc76 Update gradle and kotlin versions 2021-07-05 19:05:25 -06:00
d7a3398655 Fix Docker builds 2021-06-20 13:30:46 -06:00
8e6454cb72 Convert code to Kotlin
Convert ErrorResponse to Kotlin

Convert TwigsServerApplication to Kotlin

Convert BudgetController to Kotlin

Convert CategoryController to Kotlin

Convert UserController to Kotlin

Convert TransactionController to Kotlin

Convert Budget models to Kotlin

Convert Category models to Kotlin

Convert PasswordResetRequest models to Kotlin

Convert Transaction models to Kotlin

Convert user models to Kotlin

Convert permission models to Kotlin

Conver session models to Kotlin

Finish Kotlin conversions

Fix more Kotlin conversion issues

Remove swagger

Use Kotlin DSL for Gradle scripts

Signed-off-by: William Brawner <me@wbrawner.com>

Resolve some warnings

Move source to src/main/kotlin

Move source to src/main/kotlin
2021-06-20 13:23:37 -06:00
9b3b4fac17 Switch to OpenJ9 for container 2021-06-15 08:07:09 -06:00
214 changed files with 9367 additions and 2800 deletions

View 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 }}

View 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

View file

@ -1,9 +1,8 @@
name: Publish Docker image
on:
push:
branches: main
tags:
- '*'
branches:
- main
jobs:
push_to_registry:
@ -11,12 +10,36 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v2
- name: Push to GitHub Packages
uses: docker/build-push-action@v1
uses: actions/checkout@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
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 }}
password: ${{ secrets.GITHUB_TOKEN }}
repository: ${{ github.repository }}/${{ github.event.repository.name }}
registry: docker.pkg.github.com
tag_with_ref: true
- 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 }}

31
.github/workflows/pull-request.yml vendored Normal file
View 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
View file

@ -29,3 +29,5 @@ HELP.md
.vscode/
.gradle
*.sql
twigs.db

661
COPYING Normal file
View 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/>.

View file

@ -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>
RUN groupadd --system --gid 1000 gradle \
@ -6,10 +6,12 @@ RUN groupadd --system --gid 1000 gradle \
COPY --chown=gradle:gradle . /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
COPY --from=builder /home/gradle/src/api/build/libs/api.jar twigs-api.jar
CMD /usr/local/openjdk-14/bin/java $JVM_ARGS -jar /twigs-api.jar
RUN groupadd --system --gid 1000 twigs \
&& useradd --system --gid twigs --uid 1000 --create-home twigs
COPY --from=builder --chown=twigs:twigs /home/gradle/src/app/build/libs/twigs.jar twigs.jar
USER twigs
CMD /opt/java/openjdk/bin/java $JVM_ARGS -jar /twigs.jar

661
LICENSE
View file

@ -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/>.

View file

@ -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
- JDK 14 or newer
- MySQL 5.7 or newer
- JDK 17 or newer
- PostgreSQL 13 or newer
- (optional) Docker
## 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 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/>.

View file

@ -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
View 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()
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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);
}
}

View file

@ -1,6 +0,0 @@
package com.wbrawner.budgetserver.budget;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface BudgetRepository extends PagingAndSortingRepository<Budget, String> {
}

View file

@ -1,30 +0,0 @@
package com.wbrawner.budgetserver.budget;
import com.wbrawner.budgetserver.permission.UserPermissionRequest;
import javax.validation.constraints.NotNull;
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);
}
@NotNull
public Set<UserPermissionRequest> getUsers() {
return Set.copyOf(users);
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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");
}
}

View file

@ -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 {
}

View file

@ -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);
}
}

View file

@ -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);
}
}

View file

@ -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());
}
}

View file

@ -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);
}
}

View file

@ -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);
}
}
}

View file

@ -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;
}
}

View file

@ -1,6 +0,0 @@
package com.wbrawner.budgetserver.passwordresetrequest;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PasswordResetRequestRepository extends PagingAndSortingRepository<PasswordResetRequest, Long> {
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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());
}
}

View file

@ -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;
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -1,122 +0,0 @@
package com.wbrawner.budgetserver.transaction;
import com.wbrawner.budgetserver.budget.Budget;
import com.wbrawner.budgetserver.category.Category;
import com.wbrawner.budgetserver.user.User;
import javax.persistence.*;
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;
public Transaction() {
this(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) {
this.title = title;
this.description = description;
this.date = date;
this.amount = amount;
this.category = category;
this.expense = expense;
this.createdBy = createdBy;
this.budget = budget;
}
public String getId() {
// This should only be set from Hibernate so it shouldn't actually be null ever
//noinspection ConstantConditions
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;
}
@Override
public int compareTo(Transaction other) {
return this.date.compareTo(other.date);
}
}

View file

@ -1,209 +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
))));
}
@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();
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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);
}

View file

@ -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;
}
}

View 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
}
}
}
}
}
}

View 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
}
}
}
}
}
}

View file

@ -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
}
}
}
}
}
}

View 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
}
}
}
}
}
}

View 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
}
}
}
}
}
}

View file

@ -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
View file

@ -0,0 +1 @@
build/

61
app/build.gradle.kts Normal file
View 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)
}
}

View 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()
}

View file

@ -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))
}
}
}

View file

@ -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()
}
}

View file

@ -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)
}
}

View 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>

View 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}

View 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"

View file

@ -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)
}
}

View 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)
}
}

View file

@ -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)
}
}

View file

@ -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()
}

View file

@ -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)
}
}

View file

@ -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.2.2.RELEASE"
}
}
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
View 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
}
}

View file

@ -1,4 +0,0 @@
{
"schemaVersion": 2,
"dockerfilePath": "./Dockerfile"
}

1
core/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build/

15
core/build.gradle.kts Normal file
View 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()
}

View file

@ -0,0 +1,7 @@
package com.wbrawner.twigs
import com.wbrawner.twigs.model.PasswordResetToken
interface EmailService {
fun sendPasswordResetEmail(token: PasswordResetToken, to: String)
}

View file

@ -0,0 +1,5 @@
package com.wbrawner.twigs
interface Identifiable {
val id: String
}

View file

@ -0,0 +1,5 @@
package com.wbrawner.twigs
interface Logger {
fun log(message: String)
}

View 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)

View 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

View 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

View file

@ -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

View file

@ -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
}

View 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)

View 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

View file

@ -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.
*/
READ,
/**
* The user can read and write the content but cannot make any modifications to the container of the content.
*/
WRITE,
/**
* The user can read and write the content, and make modifications to the container of the content including things like name, description, and other users' permissions (with the exception of the owner user, whose role can never be removed by a user with only MANAGE permissions).
*/
MANAGE,
/**
* The user has complete control over the resource. There can only be a single owner user at any given time.
*/
OWNER;
public boolean isNotAtLeast(Permission wanted) {
return ordinal() < wanted.ordinal();
fun isAtLeast(wanted: Permission): Boolean {
return ordinal >= wanted.ordinal
}
}
data class UserPermission(
val budgetId: String,
val userId: String,
val permission: Permission = Permission.READ
)

1
db/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build/

21
db/build.gradle.kts Normal file
View file

@ -0,0 +1,21 @@
plugins {
kotlin("jvm")
`java-library`
}
val ktorVersion: String by rootProject.extra
dependencies {
implementation(kotlin("stdlib"))
api(project(":storage"))
runtimeOnly(libs.postgres)
runtimeOnly(libs.sqlite)
api(libs.hikari)
implementation(libs.logback)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View file

@ -0,0 +1,6 @@
package com.wbrawner.twigs.db
data class DatabaseMetadata(
val version: Int = 0,
val salt: String = ""
)

View file

@ -0,0 +1,31 @@
package com.wbrawner.twigs.db
import com.wbrawner.twigs.model.Budget
import com.wbrawner.twigs.storage.BudgetRepository
import java.sql.ResultSet
import javax.sql.DataSource
class JdbcBudgetRepository(dataSource: DataSource) : JdbcRepository<Budget, JdbcBudgetRepository.Fields>(dataSource),
BudgetRepository {
override val tableName: String = TABLE_BUDGET
override val fields: Map<Fields, (Budget) -> Any?> = Fields.values().associateWith { it.entityField }
override val conflictFields: Collection<String> = listOf(ID)
override fun ResultSet.toEntity(): Budget = Budget(
id = getString(ID),
name = getString(Fields.NAME.name.lowercase()),
description = getString(Fields.DESCRIPTION.name.lowercase()),
currencyCode = getString(Fields.CURRENCY_CODE.name.lowercase())
)
enum class Fields(val entityField: (Budget) -> Any?) {
NAME({ it.name }),
DESCRIPTION({ it.description }),
CURRENCY_CODE({ it.currencyCode })
}
companion object {
const val TABLE_BUDGET = "budgets"
}
}

View file

@ -0,0 +1,66 @@
package com.wbrawner.twigs.db
import com.wbrawner.twigs.model.Category
import com.wbrawner.twigs.storage.CategoryRepository
import java.sql.ResultSet
import javax.sql.DataSource
class JdbcCategoryRepository(dataSource: DataSource) :
JdbcRepository<Category, JdbcCategoryRepository.Fields>(dataSource), CategoryRepository {
override val tableName: String = TABLE_CATEGORY
override val fields: Map<Fields, (Category) -> Any?> = Fields.values().associateWith { it.entityField }
override val conflictFields: Collection<String> = listOf(ID)
override fun findAll(
budgetIds: List<String>,
ids: List<String>?,
expense: Boolean?,
archived: Boolean?
): List<Category> = dataSource.connection.use { conn ->
if (budgetIds.isEmpty()) {
throw Error("budgetIds cannot be empty")
}
val sql =
StringBuilder("SELECT * FROM $tableName WHERE ${Fields.BUDGET_ID.name.lowercase()} in (${budgetIds.questionMarks()})")
val params = mutableListOf<Any?>()
params.addAll(budgetIds)
ids?.let {
sql.append(" AND $ID IN (${it.questionMarks()})")
params.addAll(it)
}
expense?.let {
sql.append(" AND ${Fields.EXPENSE.name.lowercase()} = ?")
params.add(it)
}
archived?.let {
sql.append(" AND ${Fields.ARCHIVED.name.lowercase()} = ?")
params.add(it)
}
sql.append(" ORDER BY ${Fields.TITLE.name.lowercase()} ASC")
conn.executeQuery(sql.toString(), params)
}
override fun ResultSet.toEntity(): Category = Category(
id = getString(ID),
title = getString(Fields.TITLE.name.lowercase()),
description = getString(Fields.DESCRIPTION.name.lowercase()),
amount = getLong(Fields.AMOUNT.name.lowercase()),
expense = getBoolean(Fields.EXPENSE.name.lowercase()),
archived = getBoolean(Fields.ARCHIVED.name.lowercase()),
budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
)
enum class Fields(val entityField: (Category) -> Any?) {
TITLE({ it.title }),
DESCRIPTION({ it.description }),
AMOUNT({ it.amount }),
EXPENSE({ it.expense }),
ARCHIVED({ it.archived }),
BUDGET_ID({ it.budgetId }),
}
companion object {
const val TABLE_CATEGORY = "categories"
}
}

View file

@ -0,0 +1,30 @@
package com.wbrawner.twigs.db
import com.wbrawner.twigs.model.PasswordResetToken
import com.wbrawner.twigs.storage.PasswordResetRepository
import java.sql.ResultSet
import javax.sql.DataSource
class JdbcPasswordResetRepository(dataSource: DataSource) :
JdbcRepository<PasswordResetToken, JdbcPasswordResetRepository.Fields>(dataSource),
PasswordResetRepository {
override val tableName: String = TABLE_USER
override val fields: Map<Fields, (PasswordResetToken) -> Any?> = Fields.values().associateWith { it.entityField }
override val conflictFields: Collection<String> = listOf(ID)
override fun ResultSet.toEntity(): PasswordResetToken = PasswordResetToken(
id = getString(ID),
userId = getString(Fields.USER_ID.name.lowercase()),
expiration = getInstant(Fields.EXPIRATION.name.lowercase())!!
)
enum class Fields(val entityField: (PasswordResetToken) -> Any?) {
USER_ID({ it.userId }),
EXPIRATION({ it.expiration })
}
companion object {
const val TABLE_USER = "password_reset_tokens"
}
}

Some files were not shown because too many files have changed in this diff Show more