Compare commits

...

149 commits
go ... main

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
136 changed files with 7198 additions and 1249 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 name: Publish Docker image
on: on:
push: push:
branches: main branches:
tags: - main
- '*'
jobs: jobs:
push_to_registry: push_to_registry:
@ -11,13 +10,13 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Check out the repo - name: Check out the repo
uses: actions/checkout@v2 uses: actions/checkout@v4
- name: Docker meta - name: Docker meta
id: meta id: meta
uses: docker/metadata-action@v4 uses: docker/metadata-action@v5
with: with:
images: | images: |
ghcr.io/wbrawner/twigs-server ghcr.io/wbrawner/twigs
tags: | tags: |
type=schedule type=schedule
type=ref,event=branch type=ref,event=branch
@ -27,30 +26,20 @@ jobs:
type=semver,pattern={{major}} type=semver,pattern={{major}}
type=sha type=sha
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v2 uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2 uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry - name: Login to GitHub Container Registry
uses: docker/login-action@v2 uses: docker/login-action@v3
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.actor }} username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v3 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
push: true push: true
tags: ${{ steps.meta.outputs.tags }} tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }} labels: ${{ steps.meta.outputs.labels }}
- name: Deploy
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
script: |
docker compose pull twigs
docker compose up -d --build twigs
docker image prune -f

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/ .vscode/
.gradle .gradle
*.sql *.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:17-jdk as builder FROM ibm-semeru-runtimes:open-21-jdk as builder
MAINTAINER William Brawner <me@wbrawner.com> MAINTAINER William Brawner <me@wbrawner.com>
RUN groupadd --system --gid 1000 gradle \ RUN groupadd --system --gid 1000 gradle \
@ -8,10 +8,10 @@ COPY --chown=gradle:gradle . /home/gradle/src
WORKDIR /home/gradle/src WORKDIR /home/gradle/src
RUN /home/gradle/src/gradlew --console=plain --no-daemon shadowJar RUN /home/gradle/src/gradlew --console=plain --no-daemon shadowJar
FROM openjdk:17-slim FROM ibm-semeru-runtimes:open-21-jre
EXPOSE 8080 EXPOSE 8080
RUN groupadd --system --gid 1000 twigs \ RUN groupadd --system --gid 1000 twigs \
&& useradd --system --gid twigs --uid 1000 --create-home 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 COPY --from=builder --chown=twigs:twigs /home/gradle/src/app/build/libs/twigs.jar twigs.jar
USER twigs USER twigs
CMD /usr/local/openjdk-17/bin/java $JVM_ARGS -jar /twigs.jar CMD /opt/java/openjdk/bin/java $JVM_ARGS -jar /twigs.jar

661
LICENSE
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,16 +1,20 @@
# Twigs Server # Twigs
This is the backend application that powers the [Android](../../../twigs-android), [iOS](../../../twigs-ios), and [web](../../../twigs-web) applications for Twigs, a personal finance/budgeting app. None of these apps are complete, so expect bugs, and they are all in various stages of development, so expect some feature disparity between platforms. Twigs is a personal finance application tailored to individuals and small groups that want robust budgeting features
without needing to pay a monthly subscription.
## Prerequisites ## Prerequisites
- JDK 14 or newer - JDK 17 or newer
- PostgreSQL 13 or newer - PostgreSQL 13 or newer
- (optional) Docker - (optional) Docker
## Running ## Running
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: 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 run ./gradlew run
@ -18,15 +22,20 @@ Prior to running the app, make sure you have a PostgreSQL server running, with a
Some parameters of Twigs can be configured via environment variables: Some parameters of Twigs can be configured via environment variables:
Environment Variable|Default Value|Note | Environment Variable | Default Value | Note |
:---:|:---:|:--- |:--------------------:|:-------------:|:--------------------------------------------------------|
`TWIGS_PORT`|`8080`|Port for web server to listen on | `TWIGS_PORT` | `8080` | Port for web server to listen on |
`TWIGS_DB_HOST`|`localhost`|PostgreSQL server host | `TWIGS_DB_HOST` | `localhost` | PostgreSQL server host |
`TWIGS_DB_PORT`|`5432`|PostgreSQL server port | `TWIGS_DB_PORT` | `5432` | PostgreSQL server port |
`TWIGS_DB_NAME`|`twigs`|PostgreSQL database name | `TWIGS_DB_NAME` | `twigs` | PostgreSQL database name |
`TWIGS_DB_USER`|`twigs`|PostgreSQL database user | `TWIGS_DB_USER` | `twigs` | PostgreSQL database user |
`TWIGS_DB_PASS`|`twigs`|PostgreSQL database password | `TWIGS_DB_PASS` | `twigs` | PostgreSQL database password |
`TWIGS_PW_SALT`||Salt to use for password, generated if empty or null | `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
@ -34,3 +43,12 @@ Building the app is also handled with gradle:
./gradlew shadowJar ./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,20 +1,16 @@
plugins { plugins {
kotlin("jvm") kotlin("jvm")
kotlin("plugin.serialization") version "1.5.20"
`java-library` `java-library`
} }
val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
api(project(":core")) api(project(":core"))
implementation(project(":service"))
implementation(project(":storage")) implementation(project(":storage"))
api("io.ktor:ktor-server-core:$ktorVersion") api(libs.ktor.server.core)
api("io.ktor:ktor-serialization:$ktorVersion") api(libs.kotlinx.coroutines.core)
api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") testImplementation(project(":testhelpers"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
} }
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {

View file

@ -1,62 +0,0 @@
package com.wbrawner.twigs
import com.wbrawner.twigs.model.Budget
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.Session
import com.wbrawner.twigs.storage.BudgetRepository
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.util.pipeline.*
suspend inline fun PipelineContext<Unit, ApplicationCall>.requireBudgetWithPermission(
permissionRepository: PermissionRepository,
userId: String,
budgetId: String?,
permission: Permission,
otherwise: () -> Unit
) {
if (budgetId.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "budgetId is required")
return
}
permissionRepository.findAll(
userId = userId,
budgetIds = listOf(budgetId)
).firstOrNull {
it.permission.isAtLeast(permission)
} ?: run {
errorResponse(HttpStatusCode.Forbidden, "Insufficient permissions on budget $budgetId")
otherwise()
}
}
suspend fun PipelineContext<Unit, ApplicationCall>.budgetWithPermission(
budgetRepository: BudgetRepository,
permissionRepository: PermissionRepository,
budgetId: String,
permission: Permission,
block: suspend (Budget) -> Unit
) {
val session = call.principal<Session>()!!
val userPermission = permissionRepository.findAll(
userId = session.userId,
budgetIds = listOf(budgetId)
).firstOrNull()
if (userPermission?.permission?.isAtLeast(permission) != true) {
errorResponse(HttpStatusCode.Forbidden)
return
}
block(budgetRepository.findAll(ids = listOf(budgetId)).first())
}
suspend inline fun PipelineContext<Unit, ApplicationCall>.errorResponse(
httpStatusCode: HttpStatusCode = HttpStatusCode.NotFound,
message: String? = null
) {
message?.let {
call.respond(httpStatusCode, ErrorResponse(message))
}?: call.respond(httpStatusCode)
}

View file

@ -1,107 +1,57 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import com.wbrawner.twigs.model.Budget import com.wbrawner.twigs.service.budget.BudgetService
import com.wbrawner.twigs.model.Permission import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.service.respondCatching
import com.wbrawner.twigs.model.UserPermission
import com.wbrawner.twigs.storage.BudgetRepository
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.request.* import io.ktor.server.application.*
import io.ktor.response.* import io.ktor.server.auth.*
import io.ktor.routing.* import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
fun Application.budgetRoutes( fun Application.budgetRoutes(budgetService: BudgetService) {
budgetRepository: BudgetRepository,
permissionRepository: PermissionRepository
) {
routing { routing {
route("/api/budgets") { route("/api/budgets") {
authenticate(optional = false) { authenticate(optional = false) {
get { get {
val session = call.principal<Session>()!! call.respondCatching {
val budgetIds = permissionRepository.findAll(userId = session.userId).map { it.budgetId } budgetService.budgetsForUser(userId = requireSession().userId)
if (budgetIds.isEmpty()) {
call.respond(emptyList<BudgetResponse>())
return@get
} }
val budgets = budgetRepository.findAll(ids = budgetIds).map {
BudgetResponse(it, permissionRepository.findAll(budgetIds = listOf(it.id)))
}
call.respond(budgets)
} }
get("/{id}") { get("/{id}") {
budgetWithPermission(budgetRepository, permissionRepository, call.parameters["id"]!!, Permission.READ) { budget -> call.respondCatching {
val users = permissionRepository.findAll(budgetIds = listOf(budget.id)) budgetService.budget(
call.respond(BudgetResponse(budget, users)) budgetId = call.parameters.getOrFail("id"),
userId = requireSession().userId
)
} }
} }
post { post {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<BudgetRequest>() budgetService.save(request = call.receive(), userId = requireSession().userId)
if (request.name.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Name cannot be empty or null")
return@post
} }
val budget = budgetRepository.save(
Budget(
name = request.name,
description = request.description
)
)
val users = request.users?.map {
permissionRepository.save(
UserPermission(
budgetId = budget.id,
userId = it.user,
permission = it.permission
)
)
}?.toMutableSet() ?: mutableSetOf()
if (users.none { it.userId == session.userId }) {
users.add(
permissionRepository.save(
UserPermission(
budgetId = budget.id,
userId = session.userId,
permission = Permission.OWNER
)
)
)
}
call.respond(BudgetResponse(budget, users))
} }
put("/{id}") { put("/{id}") {
budgetWithPermission(budgetRepository, permissionRepository, call.parameters["id"]!!, Permission.MANAGE) { budget -> call.respondCatching {
val request = call.receive<BudgetRequest>() budgetService.save(
val name = request.name ?: budget.name request = call.receive(),
val description = request.description ?: budget.description userId = requireSession().userId,
val users = request.users?.map { budgetId = call.parameters.getOrFail("id")
permissionRepository.save(UserPermission(budget.id, it.user, it.permission))
} ?: permissionRepository.findAll(budgetIds = listOf(budget.id))
permissionRepository.findAll(budgetIds = listOf(budget.id)).forEach {
if (it.permission != Permission.OWNER && users.none { userPermission -> userPermission.userId == it.userId }) {
permissionRepository.delete(it)
}
}
call.respond(
BudgetResponse(
budgetRepository.save(budget.copy(name = name, description = description)),
users
)
) )
} }
} }
delete("/{id}") { delete("/{id}") {
budgetWithPermission(budgetRepository, permissionRepository, budgetId = call.parameters["id"]!!, Permission.OWNER) { budget -> call.respondCatching {
budgetRepository.delete(budget) budgetService.delete(
call.respond(HttpStatusCode.NoContent) budgetId = call.parameters.getOrFail("id"),
userId = requireSession().userId
)
HttpStatusCode.NoContent
} }
} }
} }

View file

@ -1,139 +1,64 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import com.wbrawner.twigs.model.Category import com.wbrawner.twigs.service.category.CategoryRequest
import com.wbrawner.twigs.model.Permission import com.wbrawner.twigs.service.category.CategoryService
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.storage.CategoryRepository import com.wbrawner.twigs.service.respondCatching
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.request.* import io.ktor.server.application.*
import io.ktor.response.* import io.ktor.server.auth.*
import io.ktor.routing.* import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
fun Application.categoryRoutes( fun Application.categoryRoutes(categoryService: CategoryService) {
categoryRepository: CategoryRepository,
permissionRepository: PermissionRepository
) {
routing { routing {
route("/api/categories") { route("/api/categories") {
authenticate(optional = false) { authenticate(optional = false) {
get { get {
val session = call.principal<Session>()!! call.respondCatching {
val budgetIds = permissionRepository.findAll( categoryService.categories(
budgetIds = call.request.queryParameters.getAll("budgetIds"), budgetIds = call.request.queryParameters.getAll("budgetIds").orEmpty(),
userId = session.userId userId = requireSession().userId,
).map { it.budgetId } expense = call.request.queryParameters["expense"]?.toBoolean(),
if (budgetIds.isEmpty()) { archived = call.request.queryParameters["archived"]?.toBoolean()
call.respond(emptyList<CategoryResponse>()) )
return@get
} }
call.respond(categoryRepository.findAll(
budgetIds = budgetIds,
expense = call.request.queryParameters["expense"]?.toBoolean(),
archived = call.request.queryParameters["archived"]?.toBoolean()
).map { it.asResponse() })
} }
get("/{id}") { get("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val budgetIds = permissionRepository.findAll(userId = session.userId).map { it.budgetId } categoryService.category(
if (budgetIds.isEmpty()) { categoryId = call.parameters.getOrFail("id"),
errorResponse() userId = requireSession().userId
return@get )
} }
categoryRepository.findAll(
ids = call.parameters.getAll("id"),
budgetIds = budgetIds
)
.map { it.asResponse() }
.firstOrNull()?.let {
call.respond(it)
} ?: errorResponse()
} }
post { post {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<CategoryRequest>() categoryService.save(call.receive<CategoryRequest>(), requireSession().userId)
if (request.title.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty")
return@post
} }
if (request.budgetId.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
return@post
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
request.budgetId,
Permission.WRITE
) {
return@post
}
call.respond(
categoryRepository.save(
Category(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId
)
).asResponse()
)
} }
put("/{id}") { put("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<CategoryRequest>() categoryService.save(
val category = categoryRepository.findAll(ids = call.parameters.getAll("id")) request = call.receive<CategoryRequest>(),
.firstOrNull() userId = requireSession().userId,
?: run { categoryId = call.parameters.getOrFail("id")
call.respond(HttpStatusCode.NotFound) )
return@put
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
category.budgetId,
Permission.WRITE
) {
return@put
} }
call.respond(
categoryRepository.save(
category.copy(
title = request.title ?: category.title,
description = request.description ?: category.description,
amount = request.amount ?: category.amount,
expense = request.expense ?: category.expense,
archived = request.archived ?: category.archived,
)
).asResponse()
)
} }
delete("/{id}") { delete("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val categoryId = call.parameters.entries().first().value categoryService.delete(
val category = categoryRepository.findAll(ids = categoryId) call.parameters.getOrFail("id"),
.firstOrNull() requireSession().userId
?: run { )
errorResponse(HttpStatusCode.NotFound) HttpStatusCode.NoContent
return@delete
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
category.budgetId,
Permission.WRITE
) {
return@delete
} }
categoryRepository.delete(category)
call.respond(HttpStatusCode.NoContent)
} }
} }
} }

View file

@ -1,6 +0,0 @@
package com.wbrawner.twigs
import kotlinx.serialization.Serializable
@Serializable
data class ErrorResponse(val message: String)

View file

@ -1,158 +1,59 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import com.wbrawner.twigs.model.Permission import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionRequest
import com.wbrawner.twigs.model.RecurringTransaction import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionService
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.storage.PermissionRepository import com.wbrawner.twigs.service.respondCatching
import com.wbrawner.twigs.storage.RecurringTransactionRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.request.* import io.ktor.server.application.*
import io.ktor.response.* import io.ktor.server.auth.*
import io.ktor.routing.* import io.ktor.server.request.*
import io.ktor.util.pipeline.* import io.ktor.server.routing.*
import java.time.Instant import io.ktor.server.util.*
fun Application.recurringTransactionRoutes(
recurringTransactionRepository: RecurringTransactionRepository,
permissionRepository: PermissionRepository
) {
suspend fun PipelineContext<Unit, ApplicationCall>.recurringTransactionAfterPermissionCheck(
id: String?,
userId: String,
success: suspend (RecurringTransaction) -> Unit
) {
if (id.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "id is required")
return
}
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(id)).firstOrNull()
?: run {
errorResponse()
return
}
requireBudgetWithPermission(
permissionRepository,
userId,
recurringTransaction.budgetId,
Permission.WRITE
) {
application.log.info("No permissions on budget ${recurringTransaction.budgetId}.")
return
}
success(recurringTransaction)
}
fun Application.recurringTransactionRoutes(recurringTransactionService: RecurringTransactionService) {
routing { routing {
route("/api/recurringtransactions") { route("/api/recurringtransactions") {
authenticate(optional = false) { authenticate(optional = false) {
get { get {
val session = call.principal<Session>()!! call.respondCatching {
val budgetId = call.request.queryParameters["budgetId"] recurringTransactionService.recurringTransactions(
requireBudgetWithPermission( budgetId = call.request.queryParameters.getOrFail("budgetId"),
permissionRepository, userId = requireSession().userId
session.userId,
budgetId,
Permission.WRITE
) {
return@get
}
call.respond(
recurringTransactionRepository.findAll(
budgetId = budgetId!!
).map { it.asResponse() }
)
}
get("/{id}") {
val session = call.principal<Session>()!!
recurringTransactionAfterPermissionCheck(call.parameters["id"]!!, session.userId) {
call.respond(it.asResponse())
}
}
post {
val session = call.principal<Session>()!!
val request = call.receive<RecurringTransactionRequest>()
if (request.title.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty")
return@post
}
if (request.budgetId.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
return@post
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
request.budgetId,
Permission.WRITE
) {
return@post
}
call.respond(
recurringTransactionRepository.save(
RecurringTransaction(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId,
categoryId = request.categoryId,
createdBy = session.userId,
start = request.start?.toInstant() ?: Instant.now(),
finish = request.finish?.toInstant(),
frequency = request.frequency.asFrequency()
)
).asResponse()
)
}
put("/{id}") {
val session = call.principal<Session>()!!
val request = call.receive<RecurringTransactionRequest>()
recurringTransactionAfterPermissionCheck(
call.parameters["id"]!!,
session.userId
) { recurringTransaction ->
if (request.budgetId != recurringTransaction.budgetId) {
requireBudgetWithPermission(
permissionRepository,
session.userId,
request.budgetId,
Permission.WRITE
) {
return@recurringTransactionAfterPermissionCheck
}
}
call.respond(
recurringTransactionRepository.save(
recurringTransaction.copy(
title = request.title ?: recurringTransaction.title,
description = request.description ?: recurringTransaction.description,
amount = request.amount ?: recurringTransaction.amount,
expense = request.expense ?: recurringTransaction.expense,
categoryId = request.categoryId ?: recurringTransaction.categoryId,
budgetId = request.budgetId ?: recurringTransaction.budgetId,
start = request.start?.toInstant() ?: recurringTransaction.start,
finish = request.finish?.toInstant() ?: recurringTransaction.finish,
frequency = request.frequency.asFrequency()
)
).asResponse()
) )
} }
} }
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}") { delete("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
recurringTransactionAfterPermissionCheck(call.parameters["id"]!!, session.userId) { recurringTransactionService.delete(call.parameters.getOrFail("id"), requireSession().userId)
val response = if (recurringTransactionRepository.delete(it)) { HttpStatusCode.NoContent
HttpStatusCode.NoContent
} else {
HttpStatusCode.InternalServerError
}
call.respond(response)
} }
} }
} }

View file

@ -1,169 +1,85 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import com.wbrawner.twigs.model.Permission import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.service.respondCatching
import com.wbrawner.twigs.model.Transaction import com.wbrawner.twigs.service.transaction.BalanceResponse
import com.wbrawner.twigs.storage.PermissionRepository import com.wbrawner.twigs.service.transaction.TransactionRequest
import com.wbrawner.twigs.storage.TransactionRepository import com.wbrawner.twigs.service.transaction.TransactionService
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.request.* import io.ktor.server.application.*
import io.ktor.response.* import io.ktor.server.auth.*
import io.ktor.routing.* import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import java.time.Instant import java.time.Instant
fun Application.transactionRoutes( fun Application.transactionRoutes(transactionService: TransactionService) {
transactionRepository: TransactionRepository,
permissionRepository: PermissionRepository
) {
routing { routing {
route("/api/transactions") { route("/api/transactions") {
authenticate(optional = false) { authenticate(optional = false) {
get { get {
val session = call.principal<Session>()!! call.respondCatching {
call.respond( transactionService.transactions(
transactionRepository.findAll( budgetIds = call.request.queryParameters.getAll("budgetIds").orEmpty(),
budgetIds = permissionRepository.findAll(
budgetIds = call.request.queryParameters.getAll("budgetIds"),
userId = session.userId
).map { it.budgetId },
categoryIds = call.request.queryParameters.getAll("categoryIds"), categoryIds = call.request.queryParameters.getAll("categoryIds"),
from = call.request.queryParameters["from"]?.let { Instant.parse(it) }, from = call.request.queryParameters["from"]?.let { Instant.parse(it) },
to = call.request.queryParameters["to"]?.let { Instant.parse(it) }, to = call.request.queryParameters["to"]?.let { Instant.parse(it) },
expense = call.request.queryParameters["expense"]?.toBoolean(), expense = call.request.queryParameters["expense"]?.toBoolean(),
).map { it.asResponse() }) userId = requireSession().userId
)
}
} }
get("/{id}") { get("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val transaction = transactionRepository.findAll( transactionService.transaction(
ids = call.parameters.getAll("id"), transactionId = call.parameters.getOrFail("id"),
budgetIds = permissionRepository.findAll( userId = requireSession().userId
userId = session.userId
) )
.map { it.budgetId } }
)
.map { it.asResponse() }
.firstOrNull()
transaction?.let {
call.respond(it)
} ?: errorResponse()
} }
get("/sum") { get("/sum") {
val categoryId = call.request.queryParameters["categoryId"] call.respondCatching {
val budgetId = call.request.queryParameters["budgetId"] BalanceResponse(
val from = call.request.queryParameters["from"]?.toInstant() ?: firstOfMonth transactionService.sum(
val to = call.request.queryParameters["to"]?.toInstant() ?: endOfMonth budgetId = call.request.queryParameters["budgetId"],
val balance = if (!categoryId.isNullOrBlank()) { categoryId = call.request.queryParameters["categoryId"],
if (!budgetId.isNullOrBlank()) { from = call.request.queryParameters["from"]?.toInstant() ?: firstOfMonth,
errorResponse( to = call.request.queryParameters["to"]?.toInstant() ?: endOfMonth,
HttpStatusCode.BadRequest, userId = requireSession().userId,
"budgetId and categoryId cannot be provided together"
) )
return@get )
}
transactionRepository.sumByCategory(categoryId, from, to)
} else if (!budgetId.isNullOrBlank()) {
transactionRepository.sumByBudget(budgetId, from, to)
} else {
errorResponse(HttpStatusCode.BadRequest, "budgetId or categoryId must be provided to sum")
return@get
} }
call.respond(BalanceResponse(balance))
} }
post { post {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<TransactionRequest>() transactionService.save(
if (request.title.isNullOrBlank()) { request = call.receive<TransactionRequest>(),
errorResponse(HttpStatusCode.BadRequest, "Title cannot be null or empty") userId = requireSession().userId
return@post )
} }
if (request.budgetId.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Budget ID cannot be null or empty")
return@post
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
request.budgetId,
Permission.WRITE
) {
return@post
}
call.respond(
transactionRepository.save(
Transaction(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId,
categoryId = request.categoryId,
createdBy = session.userId,
date = request.date?.let { Instant.parse(it) } ?: Instant.now()
)
).asResponse()
)
} }
put("/{id}") { put("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<TransactionRequest>() transactionService.save(
val transaction = transactionRepository.findAll(ids = call.parameters.getAll("id")) request = call.receive<TransactionRequest>(),
.firstOrNull() userId = requireSession().userId,
?: run { transactionId = call.parameters.getOrFail("id")
errorResponse() )
return@put
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
transaction.budgetId,
Permission.WRITE
) {
return@put
} }
call.respond(
transactionRepository.save(
transaction.copy(
title = request.title ?: transaction.title,
description = request.description ?: transaction.description,
amount = request.amount ?: transaction.amount,
expense = request.expense ?: transaction.expense,
date = request.date?.let { Instant.parse(it) } ?: transaction.date,
categoryId = request.categoryId ?: transaction.categoryId,
budgetId = request.budgetId ?: transaction.budgetId,
createdBy = transaction.createdBy,
)
).asResponse()
)
} }
delete("/{id}") { delete("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val transaction = transactionRepository.findAll(ids = call.parameters.getAll("id")) transactionService.delete(
.firstOrNull() transactionId = call.parameters.getOrFail("id"),
?: run { userId = requireSession().userId
errorResponse() )
return@delete
}
requireBudgetWithPermission(
permissionRepository,
session.userId,
transaction.budgetId,
Permission.WRITE
) {
return@delete
}
val response = if (transactionRepository.delete(transaction)) {
HttpStatusCode.NoContent HttpStatusCode.NoContent
} else {
HttpStatusCode.InternalServerError
} }
call.respond(response)
} }
} }
} }

View file

@ -1,142 +1,82 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.model.User import com.wbrawner.twigs.service.respondCatching
import com.wbrawner.twigs.storage.PermissionRepository import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.storage.SessionRepository
import com.wbrawner.twigs.storage.UserRepository
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.request.* import io.ktor.server.application.*
import io.ktor.response.* import io.ktor.server.auth.*
import io.ktor.routing.* import io.ktor.server.request.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
fun Application.userRoutes( fun Application.userRoutes(userService: UserService) {
permissionRepository: PermissionRepository,
sessionRepository: SessionRepository,
userRepository: UserRepository
) {
routing { routing {
route("/api/users") { route("/api/users") {
post("/login") { post("/login") {
val request = call.receive<LoginRequest>() call.respondCatching {
val user = userService.login(call.receive())
userRepository.findAll(nameOrEmail = request.username, password = request.password.hash()) }
.firstOrNull()
?: userRepository.findAll(nameOrEmail = request.username, password = request.password.hash())
.firstOrNull()
?: run {
errorResponse(HttpStatusCode.Unauthorized, "Invalid credentials")
return@post
}
val session = sessionRepository.save(Session(userId = user.id))
call.respond(session.asResponse())
} }
post("/register") { post("/register") {
val request = call.receive<UserRequest>() call.respondCatching {
if (request.username.isNullOrBlank()) { userService.register(call.receive())
errorResponse(HttpStatusCode.BadRequest, "Username must not be null or blank")
return@post
} }
if (request.password.isNullOrBlank()) { }
errorResponse(HttpStatusCode.BadRequest, "Password must not be null or blank")
return@post
route("/resetpassword") {
post {
call.respondCatching {
userService.requestPasswordResetEmail(call.receive())
HttpStatusCode.Accepted
}
}
put {
call.respondCatching {
userService.resetPassword(call.receive())
HttpStatusCode.NoContent
}
} }
call.respond(
userRepository.save(
User(
name = request.username,
password = request.password.hash(),
email = request.email
)
).asResponse()
)
} }
authenticate(optional = false) { authenticate(optional = false) {
get { get {
val query = call.request.queryParameters.getAll("query") call.respondCatching {
if (query?.firstOrNull()?.isNotBlank() == true) { userService.users(
call.respond(userRepository.findAll(nameLike = query.first()).map { it.asResponse() }) query = call.request.queryParameters["query"],
return@get budgetIds = call.request.queryParameters.getAll("budgetId"),
requestingUserId = requireSession().userId
)
} }
permissionRepository.findAll(
budgetIds = call.request.queryParameters.getAll("budgetId")
).mapNotNull {
userRepository.findAll(ids = listOf(it.userId))
.firstOrNull()
?.asResponse()
}.run { call.respond(this) }
} }
get("/{id}") { get("/{id}") {
userRepository.findAll(ids = call.parameters.getAll("id")) call.respondCatching {
.firstOrNull() userService.user(call.parameters.getOrFail("id"))
?.asResponse()
?.let { call.respond(it) }
?: errorResponse(HttpStatusCode.NotFound)
}
post {
val request = call.receive<UserRequest>()
if (request.username.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Username must not be null or blank")
return@post
} }
if (request.password.isNullOrBlank()) {
errorResponse(HttpStatusCode.BadRequest, "Password must not be null or blank")
return@post
}
call.respond(
userRepository.save(
User(
name = request.username,
password = request.password,
email = request.email
)
).asResponse()
)
} }
put("/{id}") { put("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
val request = call.receive<UserRequest>() userService.save(
// TODO: Add some kind of admin denotation to allow admins to edit other users request = call.receive(),
if (call.parameters["id"] != session.userId) { targetUserId = call.parameters.getOrFail("id"),
errorResponse(HttpStatusCode.Forbidden) requestingUserId = requireSession().userId
return@put )
} }
call.respond(
userRepository.save(
userRepository.findAll(ids = call.parameters.getAll("id"))
.first()
.run {
copy(
name = request.username ?: name,
password = request.password?.hash() ?: password,
email = request.email ?: email
)
}
).asResponse()
)
} }
delete("/{id}") { delete("/{id}") {
val session = call.principal<Session>()!! call.respondCatching {
// TODO: Add some kind of admin denotation to allow admins to delete other users userService.delete(
val user = userRepository.findAll(call.parameters.entries().first().value).firstOrNull() targetUserId = call.parameters.getOrFail("id"),
if (user == null) { requestingUserId = requireSession().userId
errorResponse() )
return@delete HttpStatusCode.NoContent
} }
if (user.id != session.userId) {
errorResponse(HttpStatusCode.Forbidden)
return@delete
}
userRepository.delete(user)
call.respond(HttpStatusCode.NoContent)
} }
} }
} }

View file

@ -1,11 +1,10 @@
import java.net.URI import java.net.URI
import java.util.*
plugins { plugins {
java java
kotlin("jvm") kotlin("jvm")
application application
id("com.github.johnrengelman.shadow") version "7.0.0" alias(libs.plugins.shadow)
} }
repositories { repositories {
@ -16,24 +15,21 @@ repositories {
} }
} }
val kotlinVersion: String by rootProject.extra
val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(project(":api")) implementation(project(":api"))
implementation(project(":core")) implementation(project(":core"))
implementation(project(":db")) implementation(project(":db"))
implementation(project(":web")) implementation(project(":web"))
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion") implementation(libs.kotlin.reflect)
implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion") implementation(libs.bundles.ktor.server)
implementation("io.ktor:ktor-server-core:$ktorVersion") implementation(libs.kotlinx.coroutines.core)
implementation("io.ktor:ktor-server-cio:$ktorVersion") implementation(libs.bcrypt)
implementation("io.ktor:ktor-server-sessions:$ktorVersion") implementation(libs.logback)
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") implementation(libs.mail)
implementation("ch.qos.logback:logback-classic:1.2.8") implementation(project(mapOf("path" to ":service")))
testImplementation(project(":testhelpers")) testImplementation(project(":testhelpers"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") testImplementation(libs.ktor.client.content.negotiation)
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") testImplementation(libs.ktor.server.test)
} }
description = "twigs-server" description = "twigs-server"
@ -53,56 +49,13 @@ tasks.shadowJar {
} }
} }
val captainDefinition = File(project.buildDir, "captain-definition")
val tarFile = File(project.buildDir, "twigs.tar")
tasks.register("package") {
dependsOn(":app:shadowJar")
doLast {
captainDefinition.createNewFile()
captainDefinition.outputStream().writer().use {
it.appendLine(
"""
{
"schemaVersion": 2,
"dockerfileLines": [
"FROM adoptopenjdk:openj9",
"COPY libs/twigs.jar twigs.jar",
"CMD /opt/java/openjdk/bin/java ${'$'}JVM_ARGS -jar /twigs.jar"
]
}
""".trimIndent()
)
}
exec {
commandLine(
"tar",
"-C",
project.buildDir.absolutePath,
"-cf",
project.buildDir.name + File.separator + tarFile.name,
captainDefinition.name,
"libs/twigs.jar"
)
}
}
}
tasks.register("publish") {
dependsOn(":app:package")
doLast {
var command = listOf("caprover", "deploy", "-t", "build/${tarFile.name}", "-n", "wbrawner", "-a", "twigs-dev")
command = if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows")) {
listOf("powershell", "-Command") + command
} else {
listOf("bash", "-c", "\"${command.joinToString(" ")}\"")
}
exec {
commandLine(command)
}
}
}
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {
useJUnitPlatform() useJUnitPlatform()
} }
tasks.test {
reports {
junitXml.required.set(true)
html.required.set(false)
}
}

View file

@ -1,164 +1,267 @@
package com.wbrawner.twigs.server 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.*
import com.wbrawner.twigs.db.* 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.model.Session
import com.wbrawner.twigs.storage.* import com.wbrawner.twigs.service.budget.BudgetService
import com.wbrawner.twigs.service.budget.DefaultBudgetService
import com.wbrawner.twigs.service.category.CategoryService
import com.wbrawner.twigs.service.category.DefaultCategoryService
import com.wbrawner.twigs.service.recurringtransaction.DefaultRecurringTransactionService
import com.wbrawner.twigs.service.recurringtransaction.RecurringTransactionService
import com.wbrawner.twigs.service.transaction.DefaultTransactionService
import com.wbrawner.twigs.service.transaction.TransactionService
import com.wbrawner.twigs.service.user.DefaultUserService
import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.storage.PasswordHasher
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
import com.wbrawner.twigs.web.webRoutes import com.wbrawner.twigs.web.webRoutes
import com.zaxxer.hikari.HikariConfig import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource import com.zaxxer.hikari.HikariDataSource
import io.ktor.application.* import io.ktor.client.request.forms.*
import io.ktor.auth.*
import io.ktor.features.*
import io.ktor.http.* import io.ktor.http.*
import io.ktor.response.* import io.ktor.serialization.kotlinx.json.*
import io.ktor.serialization.* import io.ktor.server.application.*
import io.ktor.sessions.* import io.ktor.server.auth.*
import kotlinx.coroutines.currentCoroutineContext import io.ktor.server.cio.*
import kotlinx.coroutines.delay import io.ktor.server.engine.*
import kotlinx.coroutines.isActive import io.ktor.server.mustache.*
import kotlinx.coroutines.launch 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 kotlinx.serialization.json.Json
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
fun main(args: Array<String>): Unit = io.ktor.server.cio.EngineMain.main(args) fun main() {
embeddedServer(
CIO,
port = System.getenv("PORT")?.toIntOrNull() ?: 8080,
module = Application::module
).start(wait = true)
}
private const val DATABASE_VERSION = 2 private const val DATABASE_VERSION = 3
fun Application.module() { fun Application.module() {
val dbHost = environment.config.propertyOrNull("twigs.database.host")?.getString() ?: "localhost" val dbType = System.getenv("TWIGS_DB_TYPE") ?: "sqlite"
val dbPort = environment.config.propertyOrNull("twigs.database.port")?.getString() ?: "5432" val dbHost = System.getenv("TWIGS_DB_HOST") ?: "localhost"
val dbName = environment.config.propertyOrNull("twigs.database.name")?.getString() ?: "twigs" val dbPort = System.getenv("TWIGS_DB_PORT") ?: "5432"
val dbUser = environment.config.propertyOrNull("twigs.database.user")?.getString() ?: "twigs" val dbName = System.getenv("TWIGS_DB_NAME") ?: "twigs"
val dbPass = environment.config.propertyOrNull("twigs.database.password")?.getString() ?: "twigs" val dbUser = System.getenv("TWIGS_DB_USER") ?: "twigs"
val jdbcUrl = "jdbc:postgresql://$dbHost:$dbPort/$dbName?stringtype=unspecified" 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 { HikariDataSource(HikariConfig().apply {
setJdbcUrl(jdbcUrl) setJdbcUrl(jdbcUrl)
username = dbUser username = dbUser
password = dbPass password = dbPass
}).also { }).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( moduleWithDependencies(
metadataRepository = MetadataRepository(it), budgetService = DefaultBudgetService(budgetRepository, permissionRepository),
budgetRepository = JdbcBudgetRepository(it), categoryService = DefaultCategoryService(categoryRepository, permissionRepository),
categoryRepository = JdbcCategoryRepository(it), recurringTransactionService = DefaultRecurringTransactionService(
permissionRepository = JdbcPermissionRepository(it), recurringTransactionRepository,
recurringTransactionRepository = JdbcRecurringTransactionRepository(it), permissionRepository
sessionRepository = JdbcSessionRepository(it), ),
transactionRepository = JdbcTransactionRepository(it), transactionService = DefaultTransactionService(
userRepository = JdbcUserRepository(it) transactionRepository,
categoryRepository,
permissionRepository
),
userService = DefaultUserService(
emailService,
passwordResetRepository,
permissionRepository,
sessionRepository,
userRepository,
passwordHasher
),
jobs = jobs,
sessionValidator = sessionValidator
) )
} }
} }
fun Application.moduleWithDependencies( fun Application.moduleWithDependencies(
metadataRepository: MetadataRepository, budgetService: BudgetService,
budgetRepository: BudgetRepository, categoryService: CategoryService,
categoryRepository: CategoryRepository, recurringTransactionService: RecurringTransactionService,
permissionRepository: PermissionRepository, transactionService: TransactionService,
recurringTransactionRepository: RecurringTransactionRepository, userService: UserService,
sessionRepository: SessionRepository, jobs: List<Job>,
transactionRepository: TransactionRepository, sessionValidator: suspend ApplicationCall.(Session) -> Principal?
userRepository: UserRepository
) { ) {
install(XForwardedHeaders)
install(CallLogging) install(CallLogging)
install(Authentication) { install(Authentication) {
session<Session> { session<Session> {
challenge { challenge {
call.respond(HttpStatusCode.Unauthorized) call.respond(HttpStatusCode.Unauthorized)
} }
validate { session -> validate(sessionValidator)
environment.log.info("Validating session") }
val storedSession = sessionRepository.findAll(session.token) session<CookieSession>(TWIGS_SESSION_COOKIE) {
.firstOrNull() challenge {
if (storedSession == null) { call.respond(HttpStatusCode.Unauthorized)
environment.log.info("Did not find session!")
return@validate null
} else {
environment.log.info("Found session!")
}
return@validate if (twoWeeksFromNow.isAfter(storedSession.expiration)) {
sessionRepository.save(storedSession.copy(expiration = twoWeeksFromNow))
} else {
null
}
} }
validate(sessionValidator)
} }
} }
install(Sessions) { install(Sessions) {
header<Session>("Authorization") { header<Session>("Authorization") {
serializer = object : SessionSerializer<Session> { serializer = object : SessionSerializer<Session> {
override fun deserialize(text: String): Session { override fun deserialize(text: String): HeaderSession {
environment.log.info("Deserializing session!") this@moduleWithDependencies.environment.log.info("Deserializing session!")
return Session(token = text.substringAfter("Bearer ")) return HeaderSession(token = text.substringAfter("Bearer "))
} }
override fun serialize(session: Session): String = session.token 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) { install(ContentNegotiation) {
json(json = Json { json(json = Json {
ignoreUnknownKeys = true ignoreUnknownKeys = true
encodeDefaults = true encodeDefaults = true
explicitNulls = false
isLenient = true isLenient = true
allowSpecialFloatingPointValues = true allowSpecialFloatingPointValues = true
allowStructuredMapKeys = true allowStructuredMapKeys = true
prettyPrint = false prettyPrint = false
useArrayPolymorphism = true useArrayPolymorphism = true
}) })
formData()
} }
install(CORS) { install(CORS) {
host("twigs.wbrawner.com", listOf("http", "https")) // TODO: Make configurable allowHost("twigs.wbrawner.com", listOf("http", "https")) // TODO: Make configurable
method(HttpMethod.Options) allowHost("localhost:4200", listOf("http", "https")) // TODO: Make configurable
method(HttpMethod.Put) allowMethod(HttpMethod.Options)
method(HttpMethod.Delete) allowMethod(HttpMethod.Get)
header(HttpHeaders.Authorization) allowMethod(HttpMethod.Post)
header(HttpHeaders.Accept) allowMethod(HttpMethod.Put)
header(HttpHeaders.AcceptEncoding) allowMethod(HttpMethod.Delete)
header(HttpHeaders.AcceptLanguage) allowHeader(HttpHeaders.Authorization)
header(HttpHeaders.Connection) allowHeader(HttpHeaders.Accept)
header(HttpHeaders.ContentType) allowHeader(HttpHeaders.AcceptEncoding)
header(HttpHeaders.Host) allowHeader(HttpHeaders.AcceptLanguage)
header(HttpHeaders.Origin) allowHeader(HttpHeaders.Connection)
header(HttpHeaders.AccessControlRequestHeaders) allowHeader(HttpHeaders.ContentType)
header(HttpHeaders.AccessControlRequestMethod) allowHeader(HttpHeaders.Host)
header("Sec-Fetch-Dest") allowHeader(HttpHeaders.Origin)
header("Sec-Fetch-Mode") allowHeader(HttpHeaders.AccessControlRequestHeaders)
header("Sec-Fetch-Site") allowHeader(HttpHeaders.AccessControlRequestMethod)
header("sec-ch-ua") allowHeader("Sec-Fetch-Dest")
header("sec-ch-ua-mobile") allowHeader("Sec-Fetch-Mode")
header("sec-ch-ua-platform") allowHeader("Sec-Fetch-Site")
header(HttpHeaders.UserAgent) allowHeader("sec-ch-ua")
header("DNT") allowHeader("sec-ch-ua-mobile")
allowHeader("sec-ch-ua-platform")
allowHeader(HttpHeaders.UserAgent)
allowHeader("DNT")
allowCredentials = true allowCredentials = true
} }
budgetRoutes(budgetRepository, permissionRepository) install(Mustache) {
categoryRoutes(categoryRepository, permissionRepository) mustacheFactory = DefaultMustacheFactory("templates")
recurringTransactionRoutes(recurringTransactionRepository, permissionRepository) }
transactionRoutes(transactionRepository, permissionRepository) budgetRoutes(budgetService)
userRoutes(permissionRepository, sessionRepository, userRepository) categoryRoutes(categoryService)
webRoutes() recurringTransactionRoutes(recurringTransactionService)
transactionRoutes(transactionService)
userRoutes(userService)
webRoutes(budgetService, categoryService, transactionService, userService)
launch { launch {
val metadata = (metadataRepository.findAll().firstOrNull() ?: DatabaseMetadata())
var version = metadata.version
while (currentCoroutineContext().isActive && version++ < DATABASE_VERSION) {
metadataRepository.runMigration(version)
metadataRepository.save(metadata.copy(version = version))
}
salt = metadata.salt.ifEmpty {
metadataRepository.save(
metadata.copy(
salt = environment.config
.propertyOrNull("twigs.password.salt")
?.getString()
?: randomString(16)
)
).salt
}
val jobs = listOf(
SessionCleanupJob(sessionRepository),
RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
)
while (currentCoroutineContext().isActive) { while (currentCoroutineContext().isActive) {
jobs.forEach { it.run() } jobs.forEach { it.run() }
delay(TimeUnit.HOURS.toMillis(1)) delay(TimeUnit.HOURS.toMillis(1))
@ -168,4 +271,4 @@ fun Application.moduleWithDependencies(
interface Job { interface Job {
suspend fun run() suspend fun run()
} }

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

@ -1,27 +0,0 @@
ktor {
deployment {
port = 8080
port = ${?TWIGS_PORT}
}
application {
modules = [ com.wbrawner.twigs.server.ApplicationKt.module ]
}
}
twigs {
database {
host = localhost
host = ${?TWIGS_DB_HOST}
port = 5432
port = ${?TWIGS_DB_PORT}
name = twigs
name = ${?TWIGS_DB_NAME}
user = twigs
user = ${?TWIGS_DB_USER}
password = twigs
password = ${?TWIGS_DB_PASS}
}
password {
salt = ${?TWIGS_PW_SALT}
}
}

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

@ -3,9 +3,9 @@ package com.wbrawner.twigs.server
import com.wbrawner.twigs.model.* import com.wbrawner.twigs.model.*
import com.wbrawner.twigs.storage.RecurringTransactionRepository import com.wbrawner.twigs.storage.RecurringTransactionRepository
import com.wbrawner.twigs.storage.TransactionRepository import com.wbrawner.twigs.storage.TransactionRepository
import com.wbrawner.twigs.test.helpers.repository.FakeRecurringTransactionsRepository import com.wbrawner.twigs.test.helpers.repository.FakeRecurringTransactionRepository
import com.wbrawner.twigs.test.helpers.repository.FakeTransactionRepository import com.wbrawner.twigs.test.helpers.repository.FakeTransactionRepository
import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
@ -21,13 +21,13 @@ class RecurringTransactionProcessingJobTest {
@BeforeEach @BeforeEach
fun setup() { fun setup() {
recurringTransactionRepository = FakeRecurringTransactionsRepository() recurringTransactionRepository = FakeRecurringTransactionRepository()
transactionRepository = FakeTransactionRepository() transactionRepository = FakeTransactionRepository()
job = RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository) job = RecurringTransactionProcessingJob(recurringTransactionRepository, transactionRepository)
} }
@Test @Test
fun `daily transactions are created every day`() = runBlockingTest { fun `daily transactions are created every day`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -49,7 +49,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `daily transactions are only created once per day`() = runBlockingTest { fun `daily transactions are only created once per day`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -71,7 +71,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `daily transactions are created every other day`() = runBlockingTest { fun `daily transactions are created every other day`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -90,7 +90,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `weekly transactions are created every thursday`() = runBlockingTest { fun `weekly transactions are created every thursday`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -113,7 +113,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `weekly transactions are created every third thursday`() = runBlockingTest { fun `weekly transactions are created every third thursday`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -134,7 +134,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `monthly transactions are created every 1st of month`() = runBlockingTest { fun `monthly transactions are created every 1st of month`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -157,7 +157,7 @@ class RecurringTransactionProcessingJobTest {
@Test @Test
fun `monthly transactions are created every last day of month when greater than max days in month`() = fun `monthly transactions are created every last day of month when greater than max days in month`() =
runBlockingTest { runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -180,7 +180,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `monthly transactions are created every 6 months`() = runBlockingTest { fun `monthly transactions are created every 6 months`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -201,7 +201,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `monthly transactions are created every 2nd tuesday`() = runBlockingTest { fun `monthly transactions are created every 2nd tuesday`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -228,7 +228,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `monthly transactions are created every last friday`() = runBlockingTest { fun `monthly transactions are created every last friday`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -255,7 +255,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `monthly transactions are created in the new year`() = runBlockingTest { fun `monthly transactions are created in the new year`() = runTest {
val start = Instant.parse("1971-01-01T00:00:00Z") val start = Instant.parse("1971-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -280,7 +280,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `yearly transactions are created every march 31st`() = runBlockingTest { fun `yearly transactions are created every march 31st`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -303,7 +303,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `yearly transactions are created every other march 31st`() = runBlockingTest { fun `yearly transactions are created every other march 31st`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(
@ -324,7 +324,7 @@ class RecurringTransactionProcessingJobTest {
} }
@Test @Test
fun `yearly transactions are created every february 29th`() = runBlockingTest { fun `yearly transactions are created every february 29th`() = runTest {
val start = Instant.parse("1970-01-01T00:00:00Z") val start = Instant.parse("1970-01-01T00:00:00Z")
recurringTransactionRepository.save( recurringTransactionRepository.save(
RecurringTransaction( RecurringTransaction(

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

@ -2,23 +2,24 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.net.URI import java.net.URI
buildscript { buildscript {
val kotlinVersion: String by extra("1.6.10")
val ktorVersion: String by extra("1.6.6")
repositories { repositories {
mavenLocal() mavenLocal()
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") classpath(libs.kotlin.gradle)
} }
} }
plugins { plugins {
java java
kotlin("jvm") version "1.5.20" alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.kotlin.serialization) apply false
} }
val javaVersion = JavaVersion.VERSION_17
allprojects { allprojects {
repositories { repositories {
mavenLocal() mavenLocal()
@ -29,7 +30,11 @@ allprojects {
} }
group = "com.wbrawner" group = "com.wbrawner"
version = "0.0.1-SNAPSHOT" version = "0.0.1-SNAPSHOT"
tasks.withType<JavaCompile> {
sourceCompatibility = javaVersion.majorVersion
targetCompatibility = javaVersion.majorVersion
}
tasks.withType<KotlinCompile> { tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "16" kotlinOptions.jvmTarget = javaVersion.majorVersion
} }
} }

View file

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

View file

@ -1,16 +1,13 @@
plugins { plugins {
kotlin("jvm")
`java-library` `java-library`
kotlin("jvm")
} }
val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
api("io.ktor:ktor-auth:$ktorVersion") api(libs.ktor.server.auth)
api("at.favre.lib:bcrypt:0.9.0") testImplementation(libs.junit.jupiter.api)
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") testRuntimeOnly(libs.junit.jupiter.engine)
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
} }
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {

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

@ -1,8 +1,8 @@
package com.wbrawner.twigs package com.wbrawner.twigs
import at.favre.lib.crypto.bcrypt.BCrypt
import com.wbrawner.twigs.model.Frequency import com.wbrawner.twigs.model.Frequency
import java.time.Instant import java.time.Instant
import java.time.format.DateTimeParseException
import java.util.* import java.util.*
private val CALENDAR_FIELDS = intArrayOf( private val CALENDAR_FIELDS = intArrayOf(
@ -35,6 +35,12 @@ val twoWeeksFromNow: Instant
toInstant() toInstant()
} }
val tomorrow: Instant
get() = GregorianCalendar(TimeZone.getTimeZone("UTC")).run {
add(Calendar.DATE, 1)
toInstant()
}
private const val CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" private const val CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
fun randomString(length: Int = 32): String { fun randomString(length: Int = 32): String {
@ -45,9 +51,12 @@ fun randomString(length: Int = 32): String {
return id.toString() return id.toString()
} }
lateinit var salt: String
fun String.hash(): String = String(BCrypt.withDefaults().hash(10, salt.toByteArray(), this.toByteArray()))
fun String.toInstant(): Instant = Instant.parse(this) fun String.toInstant(): Instant = Instant.parse(this)
fun String.toInstantOrNull(): Instant? = try {
Instant.parse(this)
} catch (e: DateTimeParseException) {
null
}
fun String.asFrequency(): Frequency = Frequency.parse(this) fun String.asFrequency(): Frequency = Frequency.parse(this)

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

@ -3,12 +3,23 @@ package com.wbrawner.twigs.model
import com.wbrawner.twigs.Identifiable import com.wbrawner.twigs.Identifiable
import com.wbrawner.twigs.randomString import com.wbrawner.twigs.randomString
import com.wbrawner.twigs.twoWeeksFromNow import com.wbrawner.twigs.twoWeeksFromNow
import io.ktor.auth.* import io.ktor.server.auth.*
import java.time.Instant import java.time.Instant
data class Session( open class Session(
override val id: String = randomString(), override val id: String = randomString(),
val userId: String = "", val userId: String = "",
val token: String = randomString(255), open val token: String = randomString(255),
var expiration: Instant = twoWeeksFromNow val expiration: Instant = twoWeeksFromNow
) : Principal, Identifiable ) : 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

@ -2,7 +2,7 @@ package com.wbrawner.twigs.model
import com.wbrawner.twigs.Identifiable import com.wbrawner.twigs.Identifiable
import com.wbrawner.twigs.randomString import com.wbrawner.twigs.randomString
import io.ktor.auth.* import io.ktor.server.auth.*
data class User( data class User(
override val id: String = randomString(), override val id: String = randomString(),

View file

@ -8,11 +8,12 @@ val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
api(project(":storage")) api(project(":storage"))
implementation("org.postgresql:postgresql:42.3.1") runtimeOnly(libs.postgres)
api("com.zaxxer:HikariCP:5.0.0") runtimeOnly(libs.sqlite)
implementation("ch.qos.logback:logback-classic:1.2.8") api(libs.hikari)
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") implementation(libs.logback)
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
} }
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {

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

View file

@ -13,7 +13,7 @@ class JdbcPermissionRepository(dataSource: DataSource) :
override val conflictFields: Collection<String> = override val conflictFields: Collection<String> =
listOf(Fields.USER_ID.name.lowercase(), Fields.BUDGET_ID.name.lowercase()) listOf(Fields.USER_ID.name.lowercase(), Fields.BUDGET_ID.name.lowercase())
override fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> = override suspend fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> =
dataSource.connection.use { conn -> dataSource.connection.use { conn ->
if (budgetIds.isNullOrEmpty() && userId.isNullOrBlank()) { if (budgetIds.isNullOrEmpty() && userId.isNullOrBlank()) {
throw Error("budgetIds or userId must be provided") throw Error("budgetIds or userId must be provided")
@ -32,6 +32,10 @@ class JdbcPermissionRepository(dataSource: DataSource) :
conn.executeQuery(sql.toString(), params) conn.executeQuery(sql.toString(), params)
} }
override suspend fun findAll(ids: List<String>?): List<UserPermission> {
throw UnsupportedOperationException("UserPermission requires a userId and budgetId")
}
override fun ResultSet.toEntity(): UserPermission = UserPermission( override fun ResultSet.toEntity(): UserPermission = UserPermission(
budgetId = getString(Fields.BUDGET_ID.name.lowercase()), budgetId = getString(Fields.BUDGET_ID.name.lowercase()),
userId = getString(Fields.USER_ID.name.lowercase()), userId = getString(Fields.USER_ID.name.lowercase()),

View file

@ -25,11 +25,15 @@ class JdbcUserRepository(dataSource: DataSource) : JdbcRepository<User, JdbcUser
) )
} }
override fun findAll(nameOrEmail: String, password: String): List<User> = dataSource.connection.use { conn -> override fun findAll(nameOrEmail: String, password: String?): List<User> = dataSource.connection.use { conn ->
conn.executeQuery( var sql =
"SELECT * FROM $tableName WHERE (${Fields.USERNAME.name.lowercase()} = ? OR ${Fields.EMAIL.name.lowercase()} = ?) AND ${Fields.PASSWORD.name.lowercase()} = ?", "SELECT * FROM $tableName WHERE (${Fields.USERNAME.name.lowercase()} = ? OR ${Fields.EMAIL.name.lowercase()} = ?)"
listOf(nameOrEmail, nameOrEmail, password) val params = mutableListOf(nameOrEmail, nameOrEmail)
) password?.let {
sql += " AND ${Fields.PASSWORD.name.lowercase()} = ?"
params.add(it)
}
conn.executeQuery(sql, params)
} }
enum class Fields(val entityField: (User) -> Any?) { enum class Fields(val entityField: (User) -> Any?) {

View file

@ -1,20 +1,26 @@
package com.wbrawner.twigs.db package com.wbrawner.twigs.db
import com.wbrawner.twigs.storage.Repository
import java.sql.ResultSet import java.sql.ResultSet
import java.sql.SQLException import java.sql.SQLException
import javax.sql.DataSource import javax.sql.DataSource
class MetadataRepository(dataSource: DataSource) : interface MetadataRepository : Repository<DatabaseMetadata> {
JdbcRepository<DatabaseMetadata, MetadataRepository.Fields>(dataSource) { fun runMigration(toVersion: Int)
}
class JdbcMetadataRepository(dataSource: DataSource) :
JdbcRepository<DatabaseMetadata, JdbcMetadataRepository.Fields>(dataSource), MetadataRepository {
override val tableName: String = TABLE_METADATA override val tableName: String = TABLE_METADATA
override val fields: Map<Fields, (DatabaseMetadata) -> Any?> = Fields.values().associateWith { it.entityField } override val fields: Map<Fields, (DatabaseMetadata) -> Any?> = Fields.values().associateWith { it.entityField }
override val conflictFields: Collection<String> = listOf() override val conflictFields: Collection<String> = listOf()
suspend fun runMigration(toVersion: Int) { override fun runMigration(toVersion: Int) {
val queries = MetadataRepository::class.java val queries = MetadataRepository::class.java
.getResource("/sql/$toVersion.sql") .getResource("/sql/$toVersion.sql")
?.readText() ?.readText()
?.split(";") ?.split(";")
?.filterNot { it.isBlank() }
?: throw Error("No migration found for version $toVersion") ?: throw Error("No migration found for version $toVersion")
dataSource.connection.use { conn -> dataSource.connection.use { conn ->
queries.forEach { query -> queries.forEach { query ->

View file

@ -0,0 +1,25 @@
CREATE TABLE IF NOT EXISTS password_reset_tokens
(
id
TEXT
PRIMARY
KEY,
user_id
TEXT
NOT
NULL,
expiration
TIMESTAMP
NOT
NULL,
CONSTRAINT
fk_users
FOREIGN
KEY
(
user_id
) REFERENCES users
(
id
) ON DELETE CASCADE
);

View file

@ -9,11 +9,12 @@ services:
- db - db
environment: environment:
TWIGS_DB_HOST: db TWIGS_DB_HOST: db
TWIGS_DB_TYPE: postgresql
networks: networks:
- twigs - twigs
db: db:
image: postgres:13 image: postgres:17
ports: ports:
- "5432:5432" - "5432:5432"
environment: environment:

55
gradle/libs.versions.toml Normal file
View file

@ -0,0 +1,55 @@
[versions]
bcrypt = "0.10.2"
hikari = "6.2.1"
junit = "5.11.3"
kotlin = "2.0.21"
kotlinx-coroutines = "1.9.0"
ktor = "2.3.13"
logback = "1.5.12"
mail = "1.6.2"
postgres = "42.7.4"
shadow = "8.1.1"
sqlite = "3.47.0.0"
[libraries]
bcrypt = { module = "at.favre.lib:bcrypt", version.ref = "bcrypt" }
hikari = { module = "com.zaxxer:HikariCP", version.ref = "hikari" }
junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit" }
junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine" }
kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
ktor-server-auth = { module = "io.ktor:ktor-server-auth", version.ref = "ktor" }
ktor-server-call-logging = { module = "io.ktor:ktor-server-call-logging", version.ref = "ktor" }
ktor-server-cio = { module = "io.ktor:ktor-server-cio", version.ref = "ktor" }
ktor-server-content-negotiation = { module = "io.ktor:ktor-server-content-negotiation", version.ref = "ktor" }
ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor" }
ktor-server-cors = { module = "io.ktor:ktor-server-cors", version.ref = "ktor" }
ktor-server-forwarded-headers = { module = "io.ktor:ktor-server-forwarded-header", version.ref = "ktor" }
ktor-server-mustache = { module = "io.ktor:ktor-server-mustache", version.ref = "ktor" }
ktor-server-sessions = { module = "io.ktor:ktor-server-sessions", version.ref = "ktor" }
ktor-server-test = { module = "io.ktor:ktor-server-test-host", version.ref = "ktor" }
logback = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
mail = { module = "com.sun.mail:javax.mail", version.ref = "mail" }
postgres = { module = "org.postgresql:postgresql", version.ref = "postgres" }
sqlite = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite" }
[bundles]
ktor-server = [
"ktor-server-call-logging",
"ktor-server-cio",
"ktor-server-content-negotiation",
"ktor-server-core",
"ktor-server-cors",
"ktor-server-forwarded-headers",
"ktor-server-sessions"
]
[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
shadow = { id = "com.github.johnrengelman.shadow", version.ref = "shadow" }

Binary file not shown.

View file

@ -1,6 +1,7 @@
#Fri Feb 07 18:11:46 CST 2020
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-all.zip
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

297
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -15,80 +15,116 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -97,87 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

194
gradlew.bat vendored
View file

@ -1,100 +1,94 @@
@rem @rem
@rem Copyright 2015 the original author or authors. @rem Copyright 2015 the original author or authors.
@rem @rem
@rem Licensed under the Apache License, Version 2.0 (the "License"); @rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License. @rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at @rem You may obtain a copy of the License at
@rem @rem
@rem https://www.apache.org/licenses/LICENSE-2.0 @rem https://www.apache.org/licenses/LICENSE-2.0
@rem @rem
@rem Unless required by applicable law or agreed to in writing, software @rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS, @rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@if "%DEBUG%" == "" @echo off @rem
@rem ##########################################################################
@rem @if "%DEBUG%"=="" @echo off
@rem Gradle startup script for Windows @rem ##########################################################################
@rem @rem
@rem ########################################################################## @rem Gradle startup script for Windows
@rem
@rem Set local scope for the variables with windows NT shell @rem ##########################################################################
if "%OS%"=="Windows_NT" setlocal
@rem Set local scope for the variables with windows NT shell
set DIRNAME=%~dp0 if "%OS%"=="Windows_NT" setlocal
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set DIRNAME=%~dp0
set APP_HOME=%DIRNAME% if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set APP_BASE_NAME=%~n0
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" set APP_HOME=%DIRNAME%
@rem Find java.exe @rem Resolve any "." and ".." in APP_HOME to make it shorter.
if defined JAVA_HOME goto findJavaFromJavaHome for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
set JAVA_EXE=java.exe @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
%JAVA_EXE% -version >NUL 2>&1 set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
if "%ERRORLEVEL%" == "0" goto init
@rem Find java.exe
echo. if defined JAVA_HOME goto findJavaFromJavaHome
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. set JAVA_EXE=java.exe
echo Please set the JAVA_HOME variable in your environment to match the %JAVA_EXE% -version >NUL 2>&1
echo location of your Java installation. if %ERRORLEVEL% equ 0 goto execute
goto fail echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
:findJavaFromJavaHome echo. 1>&2
set JAVA_HOME=%JAVA_HOME:"=% echo Please set the JAVA_HOME variable in your environment to match the 1>&2
set JAVA_EXE=%JAVA_HOME%/bin/java.exe echo location of your Java installation. 1>&2
if exist "%JAVA_EXE%" goto init goto fail
echo. :findJavaFromJavaHome
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% set JAVA_HOME=%JAVA_HOME:"=%
echo. set JAVA_EXE=%JAVA_HOME%/bin/java.exe
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. if exist "%JAVA_EXE%" goto execute
goto fail echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
:init echo. 1>&2
@rem Get command-line arguments, handling Windows variants echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
if not "%OS%" == "Windows_NT" goto win9xME_args
goto fail
:win9xME_args
@rem Slurp the command line arguments. :execute
set CMD_LINE_ARGS= @rem Setup the command line
set _SKIP=2
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:win9xME_args_slurp
if "x%~1" == "x" goto execute
@rem Execute Gradle
set CMD_LINE_ARGS=%* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:execute :end
@rem Setup the command line @rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:fail
@rem Execute Gradle rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
:end if %EXIT_CODE% equ 0 set EXIT_CODE=1
@rem End local scope for the variables with windows NT shell if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
if "%ERRORLEVEL%"=="0" goto mainEnd exit /b %EXIT_CODE%
:fail :mainEnd
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of if "%OS%"=="Windows_NT" endlocal
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 :omega
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

3
renovate.json Normal file
View file

@ -0,0 +1,3 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

1
service/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
build/

19
service/build.gradle.kts Normal file
View file

@ -0,0 +1,19 @@
plugins {
`java-library`
alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.kotlin.serialization)
}
dependencies {
implementation(kotlin("stdlib"))
api(libs.ktor.server.core)
implementation(project(":storage"))
api(libs.ktor.serialization)
api(libs.kotlinx.coroutines.core)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View file

@ -0,0 +1,59 @@
package com.wbrawner.twigs.service
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.Session
import com.wbrawner.twigs.model.UserPermission
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.storage.BudgetRepository
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
suspend fun PermissionRepository.requirePermission(
userId: String,
budgetIds: List<String>,
permission: Permission
): List<UserPermission> {
val uniqueBudgetIds = budgetIds.toSet()
val allPermissions = findAll(budgetIds = uniqueBudgetIds.toList(), userId = userId)
if (allPermissions.size != uniqueBudgetIds.size) {
throw HttpException(HttpStatusCode.NotFound)
} else if (allPermissions.any { !it.permission.isAtLeast(permission) }) {
throw HttpException(HttpStatusCode.Forbidden)
}
return allPermissions
}
suspend fun PermissionRepository.requirePermission(
userId: String,
budgetId: String,
permission: Permission
): List<UserPermission> = requirePermission(userId, listOf(budgetId), permission)
suspend fun Pair<BudgetRepository, PermissionRepository>.budgetWithPermission(
userId: String,
budgetId: String,
permission: Permission
): BudgetResponse {
val budget = first.findAll(ids = listOf(budgetId)).firstOrNull() ?: throw HttpException(HttpStatusCode.NotFound)
return BudgetResponse(budget, second.requirePermission(userId, budgetId, permission))
}
fun PipelineContext<Unit, ApplicationCall>.requireSession() = requireNotNull(call.principal<Session>()) {
"Session required but was null"
}
suspend inline fun <reified T : Any> ApplicationCall.respondCatching(block: () -> T) =
try {
val response = block()
if (response is HttpStatusCode) {
respond(status = response, message = Unit)
} else {
respond(HttpStatusCode.OK, response)
}
} catch (e: HttpException) {
respond(e.statusCode, e.toResponse())
}

View file

@ -0,0 +1,18 @@
package com.wbrawner.twigs.service
import io.ktor.http.*
import kotlinx.serialization.Serializable
@Serializable
data class ErrorResponse(val message: String)
class HttpException(
val statusCode: HttpStatusCode,
override val cause: Throwable? = null,
override val message: String? = null
) : Throwable() {
constructor(statusCode: HttpStatusCode) : this(statusCode = statusCode, message = statusCode.description)
fun toResponse(): ErrorResponse =
ErrorResponse(requireNotNull(message) { "Cannot send error to client without message" })
}

View file

@ -1,9 +1,10 @@
package com.wbrawner.twigs package com.wbrawner.twigs.service.budget
import com.wbrawner.twigs.model.Budget import com.wbrawner.twigs.model.Budget
import com.wbrawner.twigs.model.UserPermission import com.wbrawner.twigs.model.UserPermission
import com.wbrawner.twigs.service.user.UserPermissionRequest
import com.wbrawner.twigs.service.user.UserPermissionResponse
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import java.util.*
@Serializable @Serializable
data class BudgetRequest( data class BudgetRequest(
@ -15,12 +16,12 @@ data class BudgetRequest(
@Serializable @Serializable
data class BudgetResponse( data class BudgetResponse(
val id: String, val id: String,
val name: String?, val name: String? = null,
val description: String?, val description: String? = null,
private val users: List<UserPermissionResponse> val users: List<UserPermissionResponse>
) { ) {
constructor(budget: Budget, users: Iterable<UserPermission>) : this( constructor(budget: Budget, users: Iterable<UserPermission>) : this(
Objects.requireNonNull<String>(budget.id), requireNotNull(budget.id),
budget.name, budget.name,
budget.description, budget.description,
users.map { userPermission: UserPermission -> users.map { userPermission: UserPermission ->

View file

@ -0,0 +1,130 @@
package com.wbrawner.twigs.service.budget
import com.wbrawner.twigs.model.Budget
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.UserPermission
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.budgetWithPermission
import com.wbrawner.twigs.service.user.UserPermissionRequest
import com.wbrawner.twigs.storage.BudgetRepository
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.http.*
interface BudgetService {
suspend fun budgetsForUser(userId: String): List<BudgetResponse>
suspend fun budget(budgetId: String, userId: String): BudgetResponse
suspend fun save(request: BudgetRequest, userId: String, budgetId: String? = null): BudgetResponse
suspend fun delete(budgetId: String, userId: String)
}
class DefaultBudgetService(
private val budgetRepository: BudgetRepository,
private val permissionRepository: PermissionRepository
) : BudgetService {
private val budgetPermissionRepository = budgetRepository to permissionRepository
override suspend fun budgetsForUser(userId: String): List<BudgetResponse> {
val budgetIds = permissionRepository.findAll(userId = userId).map { it.budgetId }
if (budgetIds.isEmpty()) {
return emptyList()
}
return budgetRepository.findAll(ids = budgetIds).map {
BudgetResponse(it, permissionRepository.findAll(budgetIds = listOf(it.id)))
}
}
override suspend fun budget(budgetId: String, userId: String): BudgetResponse =
budgetPermissionRepository.budgetWithPermission(userId, budgetId, Permission.READ)
override suspend fun save(request: BudgetRequest, userId: String, budgetId: String?): BudgetResponse {
val budget = if (budgetId?.isNotBlank() == true) {
budgetPermissionRepository.budgetWithPermission(
budgetId = budgetId,
userId = userId,
permission = Permission.MANAGE
).run {
Budget(
id = budgetId,
name = request.name ?: name,
description = request.description ?: description
)
}
} else {
if (request.name.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "Name cannot be empty or null")
}
Budget(
name = request.name,
description = request.description
)
}
val users = budgetId?.let {
// If user is owner, apply changes
// If user is manager, make sure they're not changing ownership
val oldUsers = permissionRepository.findAll(budgetIds = listOf(budgetId))
val oldPermissions = oldUsers.associate { it.userId to it.permission }
val currentUserPermission = oldPermissions[userId] ?: throw HttpException(HttpStatusCode.NotFound)
val newUsers = request.users?.map { userPermission ->
if (userPermission.permission == Permission.OWNER
&& oldPermissions[userPermission.user] !== Permission.OWNER
&& currentUserPermission != Permission.OWNER
) {
// The user is attempting to add a new owner
throw HttpException(
HttpStatusCode.Forbidden,
message = "You must be an owner to be able to modify other users' ownership"
)
}
userPermission
} ?: return@let oldUsers.map { UserPermissionRequest(it.userId, it.permission) }
oldPermissions.filterValues { it == Permission.OWNER }
.forEach { (user, permission) ->
if (newUsers.none { it.user == user && it.permission == permission }
&& currentUserPermission != Permission.OWNER
) {
// The user is attempting to remove a previous owner
throw HttpException(
HttpStatusCode.Forbidden,
message = "You must be an owner to be able to modify other users' ownership"
)
}
}
oldUsers.forEach { oldUserPermission ->
if (newUsers.none { it.user == oldUserPermission.userId && it.permission == oldUserPermission.permission }) {
permissionRepository.delete(oldUserPermission)
}
}
newUsers
} ?: run {
val newUsers = request.users
?.toMutableList()
?: mutableListOf()
val currentUserPermission = newUsers.firstOrNull { it.user == userId }
if (currentUserPermission == null || currentUserPermission.permission != Permission.OWNER) {
newUsers.removeIf { it.user == userId }
newUsers.add(UserPermissionRequest(userId, Permission.OWNER))
}
newUsers
}
val savedBudget = budgetRepository.save(budget)
return BudgetResponse(
savedBudget,
users.map {
permissionRepository.save(
UserPermission(
budgetId = savedBudget.id,
userId = it.user,
permission = it.permission
)
)
}
)
}
override suspend fun delete(budgetId: String, userId: String) {
val budgetResponse = budgetPermissionRepository.budgetWithPermission(userId, budgetId, Permission.OWNER)
budgetRepository.delete(Budget(budgetResponse.id, budgetResponse.name, budgetResponse.description))
}
}

View file

@ -1,4 +1,4 @@
package com.wbrawner.twigs package com.wbrawner.twigs.service.category
import com.wbrawner.twigs.model.Category import com.wbrawner.twigs.model.Category
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable

View file

@ -0,0 +1,104 @@
package com.wbrawner.twigs.service.category
import com.wbrawner.twigs.model.Category
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.requirePermission
import com.wbrawner.twigs.storage.CategoryRepository
import com.wbrawner.twigs.storage.PermissionRepository
import io.ktor.http.*
interface CategoryService {
suspend fun categories(
budgetIds: List<String>,
userId: String,
expense: Boolean? = null,
archived: Boolean? = null,
): List<CategoryResponse>
suspend fun category(categoryId: String, userId: String): CategoryResponse
suspend fun save(request: CategoryRequest, userId: String, categoryId: String? = null): CategoryResponse
suspend fun delete(categoryId: String, userId: String)
}
class DefaultCategoryService(
private val categoryRepository: CategoryRepository,
private val permissionRepository: PermissionRepository
) : CategoryService {
override suspend fun categories(
budgetIds: List<String>,
userId: String,
expense: Boolean?,
archived: Boolean?,
): List<CategoryResponse> {
val validBudgetIds = permissionRepository.findAll(
budgetIds = budgetIds,
userId = userId
).map { it.budgetId }
if (validBudgetIds.isEmpty()) {
return emptyList()
}
return categoryRepository.findAll(
budgetIds = budgetIds,
expense = expense,
archived = archived
).map { it.asResponse() }
}
override suspend fun category(categoryId: String, userId: String): CategoryResponse {
val budgetIds = permissionRepository.findAll(userId = userId).map { it.budgetId }
if (budgetIds.isEmpty()) {
throw HttpException(HttpStatusCode.NotFound)
}
return categoryRepository.findAll(
ids = listOf(categoryId),
budgetIds = budgetIds
)
.map { it.asResponse() }
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
}
override suspend fun save(request: CategoryRequest, userId: String, categoryId: String?): CategoryResponse {
val category = categoryId?.let {
categoryRepository.findAll(ids = listOf(categoryId)).firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
} ?: run {
if (request.title.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
}
if (request.budgetId.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
}
Category(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId
)
}
permissionRepository.requirePermission(userId, category.budgetId, Permission.WRITE)
return categoryRepository.save(
category.copy(
title = request.title?.ifBlank { category.title } ?: category.title,
description = request.description ?: category.description,
amount = request.amount ?: category.amount,
expense = request.expense ?: category.expense,
archived = request.archived ?: category.archived,
budgetId = request.budgetId?.ifBlank { category.budgetId } ?: category.budgetId
)
).asResponse()
}
override suspend fun delete(categoryId: String, userId: String) {
val category = categoryRepository.findAll(ids = listOf(categoryId))
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(userId, category.budgetId, Permission.WRITE)
categoryRepository.delete(category)
}
}

View file

@ -1,7 +1,8 @@
package com.wbrawner.twigs package com.wbrawner.twigs.service.recurringtransaction
import com.wbrawner.twigs.model.RecurringTransaction import com.wbrawner.twigs.model.RecurringTransaction
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import java.time.temporal.ChronoUnit
@Serializable @Serializable
data class RecurringTransactionRequest( data class RecurringTransactionRequest(
@ -23,7 +24,7 @@ data class RecurringTransactionResponse(
val description: String?, val description: String?,
val frequency: String, val frequency: String,
val start: String, val start: String,
val finish: String? = null, val finish: String?,
val amount: Long?, val amount: Long?,
val expense: Boolean?, val expense: Boolean?,
val budgetId: String, val budgetId: String,
@ -36,8 +37,8 @@ fun RecurringTransaction.asResponse(): RecurringTransactionResponse = RecurringT
title = title, title = title,
description = description, description = description,
frequency = frequency.toString(), frequency = frequency.toString(),
start = start.toString(), start = start.truncatedTo(ChronoUnit.SECONDS).toString(),
finish = finish.toString(), finish = finish?.truncatedTo(ChronoUnit.SECONDS)?.toString(),
amount = amount, amount = amount,
expense = expense, expense = expense,
budgetId = budgetId, budgetId = budgetId,

View file

@ -0,0 +1,110 @@
package com.wbrawner.twigs.service.recurringtransaction
import com.wbrawner.twigs.asFrequency
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.RecurringTransaction
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.requirePermission
import com.wbrawner.twigs.storage.PermissionRepository
import com.wbrawner.twigs.storage.RecurringTransactionRepository
import com.wbrawner.twigs.toInstant
import io.ktor.http.*
import java.time.Instant
interface RecurringTransactionService {
suspend fun recurringTransactions(
budgetId: String,
userId: String,
): List<RecurringTransactionResponse>
suspend fun recurringTransaction(recurringTransactionId: String, userId: String): RecurringTransactionResponse
suspend fun save(
request: RecurringTransactionRequest,
userId: String,
recurringTransactionId: String? = null
): RecurringTransactionResponse
suspend fun delete(recurringTransactionId: String, userId: String)
}
class DefaultRecurringTransactionService(
private val recurringTransactionRepository: RecurringTransactionRepository,
private val permissionRepository: PermissionRepository
) : RecurringTransactionService {
override suspend fun recurringTransactions(
budgetId: String,
userId: String
): List<RecurringTransactionResponse> {
permissionRepository.requirePermission(userId, budgetId, Permission.READ)
return recurringTransactionRepository.findAll(budgetId = budgetId)
.map { it.asResponse() }
}
override suspend fun recurringTransaction(
recurringTransactionId: String,
userId: String
): RecurringTransactionResponse {
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(recurringTransactionId))
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.READ)
return recurringTransaction.asResponse()
}
override suspend fun save(
request: RecurringTransactionRequest,
userId: String,
recurringTransactionId: String?
): RecurringTransactionResponse {
val recurringTransaction = recurringTransactionId?.let {
recurringTransactionRepository.findAll(ids = listOf(it))
.firstOrNull()
?.also { recurringTransaction ->
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
}
?: throw HttpException(HttpStatusCode.NotFound)
} ?: run {
if (request.title.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
}
if (request.budgetId.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
}
RecurringTransaction(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId,
categoryId = request.categoryId,
createdBy = userId,
start = request.start?.toInstant() ?: Instant.now(),
finish = request.finish?.toInstant(),
frequency = request.frequency.asFrequency()
)
}
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
return recurringTransactionRepository.save(
recurringTransaction.copy(
title = request.title?.ifBlank { recurringTransaction.title } ?: recurringTransaction.title,
description = request.description ?: recurringTransaction.description,
amount = request.amount ?: recurringTransaction.amount,
expense = request.expense ?: recurringTransaction.expense,
budgetId = request.budgetId?.ifBlank { recurringTransaction.budgetId } ?: recurringTransaction.budgetId,
categoryId = request.categoryId ?: recurringTransaction.categoryId,
start = request.start?.toInstant() ?: recurringTransaction.start,
finish = request.finish?.toInstant() ?: recurringTransaction.finish,
frequency = request.frequency.asFrequency()
)
).asResponse()
}
override suspend fun delete(recurringTransactionId: String, userId: String) {
val recurringTransaction = recurringTransactionRepository.findAll(ids = listOf(recurringTransactionId))
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(userId, recurringTransaction.budgetId, Permission.WRITE)
recurringTransactionRepository.delete(recurringTransaction)
}
}

View file

@ -1,4 +1,4 @@
package com.wbrawner.twigs package com.wbrawner.twigs.service.transaction
import com.wbrawner.twigs.model.Transaction import com.wbrawner.twigs.model.Transaction
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable

View file

@ -0,0 +1,167 @@
package com.wbrawner.twigs.service.transaction
import com.wbrawner.twigs.endOfMonth
import com.wbrawner.twigs.firstOfMonth
import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.Transaction
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.requirePermission
import com.wbrawner.twigs.storage.CategoryRepository
import com.wbrawner.twigs.storage.PermissionRepository
import com.wbrawner.twigs.storage.TransactionRepository
import com.wbrawner.twigs.toInstant
import com.wbrawner.twigs.toInstantOrNull
import io.ktor.http.*
import java.time.Instant
interface TransactionService {
suspend fun transactions(
budgetIds: List<String>,
categoryIds: List<String>? = null,
from: Instant? = null,
to: Instant? = null,
expense: Boolean? = null,
userId: String,
): List<TransactionResponse>
suspend fun transaction(transactionId: String, userId: String): TransactionResponse
suspend fun sum(
userId: String,
budgetId: String? = null,
categoryId: String? = null,
from: Instant? = null,
to: Instant? = null,
): Long
suspend fun save(
request: TransactionRequest,
userId: String,
transactionId: String? = null
): TransactionResponse
suspend fun delete(transactionId: String, userId: String)
}
class DefaultTransactionService(
private val transactionRepository: TransactionRepository,
private val categoryRepository: CategoryRepository,
private val permissionRepository: PermissionRepository
) : TransactionService {
override suspend fun transactions(
budgetIds: List<String>,
categoryIds: List<String>?,
from: Instant?,
to: Instant?,
expense: Boolean?,
userId: String
): List<TransactionResponse> {
permissionRepository.requirePermission(userId, budgetIds, Permission.READ)
return transactionRepository.findAll(
budgetIds = budgetIds,
categoryIds = categoryIds,
from = from,
to = to,
expense = expense
).map { it.asResponse() }
}
override suspend fun transaction(
transactionId: String,
userId: String
): TransactionResponse {
val transaction = transactionRepository.findAll(ids = listOf(transactionId))
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.READ)
return transaction.asResponse()
}
override suspend fun sum(
userId: String,
budgetId: String?,
categoryId: String?,
from: Instant?,
to: Instant?
): Long {
if (budgetId.isNullOrBlank() && categoryId.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId or categoryId must be provided to sum")
}
if (budgetId?.isNotBlank() == true && categoryId?.isNotBlank() == true) {
throw HttpException(
HttpStatusCode.BadRequest,
message = "budgetId and categoryId cannot be provided together"
)
}
return if (!categoryId.isNullOrBlank()) {
val category = categoryRepository.findAll(ids = listOf(categoryId)).firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(
userId = userId,
budgetId = category.budgetId,
permission = Permission.READ
)
transactionRepository.sumByCategory(category.id, from ?: firstOfMonth, to ?: endOfMonth)
} else if (!budgetId.isNullOrBlank()) {
permissionRepository.requirePermission(userId = userId, budgetId = budgetId, permission = Permission.READ)
transactionRepository.sumByBudget(budgetId, from ?: firstOfMonth, to ?: endOfMonth)
} else {
error("Somehow we didn't return either a budget or category sum")
}
}
override suspend fun save(
request: TransactionRequest,
userId: String,
transactionId: String?
): TransactionResponse {
val transaction = transactionId?.let {
transactionRepository.findAll(ids = listOf(it))
.firstOrNull()
?.also { transaction ->
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.WRITE)
}
?: throw HttpException(HttpStatusCode.NotFound)
} ?: run {
if (request.title.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "title cannot be null or empty")
}
if (request.budgetId.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "budgetId cannot be null or empty")
}
if (request.date?.toInstantOrNull() == null) {
throw HttpException(HttpStatusCode.BadRequest, message = "invalid date")
}
Transaction(
title = request.title,
description = request.description,
amount = request.amount ?: 0L,
expense = request.expense ?: true,
budgetId = request.budgetId,
categoryId = request.categoryId,
date = request.date.toInstant(),
createdBy = userId,
)
}
permissionRepository.requirePermission(userId, request.budgetId ?: transaction.budgetId, Permission.WRITE)
return transactionRepository.save(
transaction.copy(
title = request.title?.ifBlank { transaction.title } ?: transaction.title,
description = request.description ?: transaction.description,
amount = request.amount ?: transaction.amount,
expense = request.expense ?: transaction.expense,
budgetId = request.budgetId?.ifBlank { transaction.budgetId } ?: transaction.budgetId,
categoryId = request.categoryId ?: transaction.categoryId,
date = request.date?.toInstantOrNull() ?: transaction.date
)
).asResponse()
}
override suspend fun delete(transactionId: String, userId: String) {
val transaction = transactionRepository.findAll(ids = listOf(transactionId))
.firstOrNull()
?: throw HttpException(HttpStatusCode.NotFound)
permissionRepository.requirePermission(userId, transaction.budgetId, Permission.WRITE)
transactionRepository.delete(transaction)
}
}

View file

@ -1,10 +1,10 @@
package com.wbrawner.twigs package com.wbrawner.twigs.service.user
import com.wbrawner.twigs.model.PasswordResetToken
import com.wbrawner.twigs.model.Permission import com.wbrawner.twigs.model.Permission
import com.wbrawner.twigs.model.Session import com.wbrawner.twigs.model.Session
import com.wbrawner.twigs.model.User import com.wbrawner.twigs.model.User
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import java.util.*
@Serializable @Serializable
data class UserRequest( data class UserRequest(
@ -31,13 +31,24 @@ data class UserPermissionResponse(val user: String, val permission: Permission?)
@Serializable @Serializable
data class SessionResponse(val userId: String, val token: String, val expiration: String) data class SessionResponse(val userId: String, val token: String, val expiration: String)
data class PasswordResetRequest( /**
val userId: Long, * Used to request the password reset email
val id: String = randomString(), */
private val date: Calendar = GregorianCalendar(), @Serializable
private val token: String = randomString() data class ResetPasswordRequest(val username: String)
)
/**
* Used to modify the user's password after receiving the password reset email
*/
@Serializable
data class PasswordResetRequest(val token: String, val password: String)
@Serializable
data class PasswordResetTokenResponse(val userId: String, val id: String, val expiration: String)
fun User.asResponse(): UserResponse = UserResponse(id, name, email) fun User.asResponse(): UserResponse = UserResponse(id, name, email)
fun Session.asResponse(): SessionResponse = SessionResponse(userId, token, expiration.toString()) fun Session.asResponse(): SessionResponse = SessionResponse(userId, token, expiration.toString())
fun PasswordResetToken.asResponse(): PasswordResetTokenResponse =
PasswordResetTokenResponse(userId, id, expiration.toString())

View file

@ -0,0 +1,178 @@
package com.wbrawner.twigs.service.user
import com.wbrawner.twigs.EmailService
import com.wbrawner.twigs.model.PasswordResetToken
import com.wbrawner.twigs.model.Session
import com.wbrawner.twigs.model.User
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.storage.*
import io.ktor.http.*
import java.time.Instant
interface UserService {
suspend fun login(request: LoginRequest): SessionResponse
suspend fun register(request: UserRequest): UserResponse
suspend fun requestPasswordResetEmail(request: ResetPasswordRequest)
suspend fun resetPassword(request: PasswordResetRequest)
suspend fun users(query: String?, budgetIds: List<String>?, requestingUserId: String): List<UserResponse>
suspend fun user(userId: String): UserResponse
suspend fun session(token: String): SessionResponse
suspend fun save(request: UserRequest, targetUserId: String, requestingUserId: String): UserResponse
suspend fun delete(targetUserId: String, requestingUserId: String)
}
class DefaultUserService(
private val emailService: EmailService,
private val passwordResetRepository: PasswordResetRepository,
private val permissionRepository: PermissionRepository,
private val sessionRepository: SessionRepository,
private val userRepository: UserRepository,
private val passwordHasher: PasswordHasher
) : UserService {
override suspend fun login(request: LoginRequest): SessionResponse {
val user = userRepository.findAll(
nameOrEmail = request.username,
password = passwordHasher.hash(request.password)
)
.firstOrNull()
?: throw HttpException(HttpStatusCode.Unauthorized, message = "Invalid credentials")
return sessionRepository.save(Session(userId = user.id)).asResponse()
}
override suspend fun register(request: UserRequest): UserResponse {
if (request.username.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "username must not be null or blank")
}
if (request.password.isNullOrBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "password must not be null or blank")
}
val existingUser = userRepository.findAll(nameOrEmail = request.username).firstOrNull()
?: request.email?.let {
if (it.isBlank()) {
null
} else {
userRepository.findAll(nameOrEmail = it).firstOrNull()
}
}
existingUser?.let {
throw HttpException(HttpStatusCode.BadRequest, message = "username or email already taken")
}
return userRepository.save(
User(
name = request.username,
password = passwordHasher.hash(request.password),
email = if (request.email.isNullOrBlank()) null else request.email
)
).asResponse()
}
override suspend fun requestPasswordResetEmail(request: ResetPasswordRequest) {
userRepository.findAll(nameOrEmail = request.username)
.firstOrNull()
?.let {
val email = it.email ?: return@let
val passwordResetToken = passwordResetRepository.save(PasswordResetToken(userId = it.id))
emailService.sendPasswordResetEmail(passwordResetToken, email)
}
}
override suspend fun resetPassword(request: PasswordResetRequest) {
val passwordResetToken = passwordResetRepository.findAll(listOf(request.token))
.firstOrNull()
?: throw HttpException(HttpStatusCode.Unauthorized, message = "Invalid token")
if (passwordResetToken.expiration.isBefore(Instant.now())) {
throw HttpException(HttpStatusCode.Unauthorized, message = "Token expired")
}
if (request.password.isBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "password cannot be empty")
}
userRepository.findAll(listOf(passwordResetToken.userId))
.firstOrNull()
?.let {
userRepository.save(it.copy(password = passwordHasher.hash(request.password)))
passwordResetRepository.delete(passwordResetToken)
}
?: throw HttpException(HttpStatusCode.InternalServerError, message = "Invalid token")
}
override suspend fun users(
query: String?,
budgetIds: List<String>?,
requestingUserId: String
): List<UserResponse> {
if (query != null) {
if (query.isBlank()) {
throw HttpException(HttpStatusCode.BadRequest, message = "query cannot be empty")
}
return userRepository.findAll(nameLike = query).map { it.asResponse() }
} else if (budgetIds == null || budgetIds.all { it.isBlank() }) {
throw HttpException(HttpStatusCode.BadRequest, message = "query or budgetId required but absent")
}
return permissionRepository.findAll(budgetIds = budgetIds, userId = requestingUserId)
.mapNotNull {
userRepository.findAll(ids = listOf(it.userId))
.firstOrNull()
?.asResponse()
}
}
override suspend fun user(
userId: String
): UserResponse {
return userRepository.findAll(ids = listOf(userId))
.firstOrNull()
?.asResponse()
?: throw HttpException(HttpStatusCode.NotFound)
}
override suspend fun session(token: String): SessionResponse {
return sessionRepository.findAll(token = token)
.firstOrNull()
?.asResponse()
?: throw HttpException(HttpStatusCode.Unauthorized)
}
override suspend fun save(
request: UserRequest,
targetUserId: String,
requestingUserId: String,
): UserResponse {
// TODO: Add some kind of admin denotation to allow admins to edit other users
if (targetUserId != requestingUserId) {
throw HttpException(HttpStatusCode.Forbidden)
}
return userRepository.save(
userRepository.findAll(ids = listOf(targetUserId))
.first()
.run {
val newPassword = if (request.password.isNullOrBlank()) {
password
} else {
passwordHasher.hash(request.password)
}
copy(
name = request.username ?: name,
password = newPassword,
email = request.email ?: email
)
}
).asResponse()
}
override suspend fun delete(targetUserId: String, requestingUserId: String) {
// TODO: Add some kind of admin denotation to allow admins to delete other users
if (targetUserId != requestingUserId) {
throw HttpException(HttpStatusCode.Forbidden)
}
userRepository.delete(userRepository.findAll(targetUserId).first())
}
}

View file

@ -1,3 +1,4 @@
rootProject.name = "twigs" rootProject.name = "twigs"
include("core", "api", "app", "storage", "db", "web") include("core", "api", "app", "storage", "db", "web")
include("testhelpers") include("testhelpers")
include("service")

View file

@ -3,14 +3,12 @@ plugins {
`java-library` `java-library`
} }
val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
api(project(":core")) api(project(":core"))
api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") api(libs.kotlinx.coroutines.core)
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") testImplementation(libs.junit.jupiter.api)
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") testRuntimeOnly(libs.junit.jupiter.engine)
} }
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {

View file

@ -0,0 +1,5 @@
package com.wbrawner.twigs.storage
import com.wbrawner.twigs.model.PasswordResetToken
interface PasswordResetRepository : Repository<PasswordResetToken> {}

View file

@ -3,7 +3,7 @@ package com.wbrawner.twigs.storage
import com.wbrawner.twigs.model.UserPermission import com.wbrawner.twigs.model.UserPermission
interface PermissionRepository : Repository<UserPermission> { interface PermissionRepository : Repository<UserPermission> {
fun findAll( suspend fun findAll(
budgetIds: List<String>? = null, budgetIds: List<String>? = null,
userId: String? = null userId: String? = null
): List<UserPermission> ): List<UserPermission>

View file

@ -5,8 +5,12 @@ import com.wbrawner.twigs.model.User
interface UserRepository : Repository<User> { interface UserRepository : Repository<User> {
fun findAll( fun findAll(
nameOrEmail: String, nameOrEmail: String,
password: String password: String? = null
): List<User> ): List<User>
fun findAll(nameLike: String): List<User> fun findAll(nameLike: String): List<User>
}
fun interface PasswordHasher {
fun hash(password: String): String
} }

View file

@ -6,7 +6,14 @@ plugins {
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
implementation(project(":storage")) implementation(project(":storage"))
api("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.2") api(libs.kotlinx.coroutines.test)
api("org.junit.jupiter:junit-jupiter-api:5.8.2") api(libs.junit.jupiter.api)
api("org.junit.jupiter:junit-jupiter-engine") implementation(project(mapOf("path" to ":db")))
runtimeOnly(libs.junit.jupiter.engine)
} }
tasks {
test {
useJUnitPlatform()
}
}

View file

@ -0,0 +1,14 @@
package com.wbrawner.twigs.test.helpers
import com.wbrawner.twigs.EmailService
import com.wbrawner.twigs.model.PasswordResetToken
class FakeEmailService : EmailService {
val emails = mutableListOf<FakeEmail<*>>()
override fun sendPasswordResetEmail(token: PasswordResetToken, to: String) {
emails.add(FakeEmail(to, token))
}
}
data class FakeEmail<Data>(val to: String, val data: Data)

View file

@ -0,0 +1,6 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.Budget
import com.wbrawner.twigs.storage.BudgetRepository
class FakeBudgetRepository : FakeRepository<Budget>(), BudgetRepository

View file

@ -0,0 +1,18 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.Category
import com.wbrawner.twigs.storage.CategoryRepository
class FakeCategoryRepository : FakeRepository<Category>(), CategoryRepository {
override fun findAll(
budgetIds: List<String>,
ids: List<String>?,
expense: Boolean?,
archived: Boolean?
): List<Category> = entities.filter {
budgetIds.contains(it.budgetId)
&& ids?.contains(it.id) ?: true
&& it.expense == (expense ?: it.expense)
&& it.archived == (archived ?: it.archived)
}
}

View file

@ -0,0 +1,23 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.db.DatabaseMetadata
import com.wbrawner.twigs.db.MetadataRepository
import com.wbrawner.twigs.storage.Repository
const val TEST_SALT = "testtesttesttest"
class FakeMetadataRepository : Repository<DatabaseMetadata>, MetadataRepository {
var metadata = DatabaseMetadata(salt = TEST_SALT)
override fun runMigration(toVersion: Int) {
metadata = metadata.copy(version = toVersion)
}
override suspend fun findAll(ids: List<String>?): List<DatabaseMetadata> = listOf(metadata)
override suspend fun delete(item: DatabaseMetadata): Boolean = false
override suspend fun save(item: DatabaseMetadata): DatabaseMetadata {
metadata = item
return metadata
}
}

View file

@ -0,0 +1,6 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.PasswordResetToken
import com.wbrawner.twigs.storage.PasswordResetRepository
class FakePasswordResetRepository : FakeRepository<PasswordResetToken>(), PasswordResetRepository

View file

@ -0,0 +1,26 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.UserPermission
import com.wbrawner.twigs.storage.PermissionRepository
class FakePermissionRepository : PermissionRepository {
val permissions: MutableList<UserPermission> = mutableListOf()
override suspend fun findAll(budgetIds: List<String>?, userId: String?): List<UserPermission> =
permissions.filter { userPermission ->
budgetIds?.contains(userPermission.budgetId) ?: true
&& userId?.let { it == userPermission.userId } ?: true
}
override suspend fun findAll(ids: List<String>?): List<UserPermission> {
throw UnsupportedOperationException("UserPermission requires a userId and budgetId")
}
override suspend fun save(item: UserPermission): UserPermission {
permissions.removeIf { it.budgetId == item.budgetId && it.userId == item.userId }
permissions.add(item)
return item
}
override suspend fun delete(item: UserPermission): Boolean =
permissions.removeIf { it.budgetId == item.budgetId && it.userId == item.userId }
}

View file

@ -4,7 +4,7 @@ import com.wbrawner.twigs.model.RecurringTransaction
import com.wbrawner.twigs.storage.RecurringTransactionRepository import com.wbrawner.twigs.storage.RecurringTransactionRepository
import java.time.Instant import java.time.Instant
class FakeRecurringTransactionsRepository : FakeRepository<RecurringTransaction>(), RecurringTransactionRepository { class FakeRecurringTransactionRepository : FakeRepository<RecurringTransaction>(), RecurringTransactionRepository {
override suspend fun findAll(now: Instant): List<RecurringTransaction> = entities.filter { override suspend fun findAll(now: Instant): List<RecurringTransaction> = entities.filter {
(it.start == now || it.start.isBefore(now)) && it.finish?.isAfter(now) ?: true (it.start == now || it.start.isBefore(now)) && it.finish?.isAfter(now) ?: true
} }

View file

@ -4,7 +4,7 @@ import com.wbrawner.twigs.Identifiable
import com.wbrawner.twigs.storage.Repository import com.wbrawner.twigs.storage.Repository
abstract class FakeRepository<T : Identifiable> : Repository<T> { abstract class FakeRepository<T : Identifiable> : Repository<T> {
val entities = mutableListOf<T>() open val entities = mutableListOf<T>()
override suspend fun findAll(ids: List<String>?): List<T> = if (ids == null) { override suspend fun findAll(ids: List<String>?): List<T> = if (ids == null) {
entities entities

View file

@ -0,0 +1,15 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.Session
import com.wbrawner.twigs.storage.SessionRepository
import java.util.function.Predicate
class FakeSessionRepository : FakeRepository<Session>(), SessionRepository {
var expirationPredicate: Predicate<in Session> = Predicate { false }
override fun findAll(token: String): List<Session> = entities.filter { it.token == token }
override fun deleteExpired() {
entities.removeIf(expirationPredicate)
}
}

View file

@ -0,0 +1,37 @@
package com.wbrawner.twigs.test.helpers.repository
import com.wbrawner.twigs.model.User
import com.wbrawner.twigs.storage.UserRepository
class FakeUserRepository : FakeRepository<User>(), UserRepository {
override val entities: MutableList<User> = mutableListOf(TEST_USER, OTHER_USER)
override fun findAll(nameOrEmail: String, password: String?): List<User> {
return entities.filter { user ->
(user.name.equals(nameOrEmail, ignoreCase = true) || user.email.equals(
nameOrEmail,
ignoreCase = true
)) && password?.let { user.password == it } ?: true
}
}
override fun findAll(nameLike: String): List<User> {
return entities.filter { it.name.contains(nameLike, ignoreCase = true) }
}
companion object {
val TEST_USER = User(
id = "id-test-user",
name = "testuser",
email = "test@example.com",
password = "testpass"
)
val OTHER_USER = User(
id = "id-other-user",
name = "otheruser",
email = "other@example.com",
password = "otherpass"
)
}
}

View file

@ -1,53 +1,18 @@
import java.util.*
plugins { plugins {
kotlin("jvm")
`java-library` `java-library`
alias(libs.plugins.kotlin.jvm)
} }
val ktorVersion: String by rootProject.extra
dependencies { dependencies {
implementation(kotlin("stdlib")) implementation(kotlin("stdlib"))
api("io.ktor:ktor-server-core:$ktorVersion") implementation(project(":core"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.2") implementation(project(":service"))
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine") api(libs.ktor.server.core)
api(libs.ktor.server.mustache)
testImplementation(libs.junit.jupiter.api)
testRuntimeOnly(libs.junit.jupiter.engine)
} }
tasks.getByName<Test>("test") { tasks.getByName<Test>("test") {
useJUnitPlatform() useJUnitPlatform()
} }
// TODO: Replace this hack with either a git submodule or an internal Kotlin-based UI
tasks.register("package") {
doLast {
val built = File(rootProject.rootDir.parent, "twigs-web/dist/twigs")
if (built.exists()) {
built.deleteRecursively()
}
val dest = File(project.projectDir, "src/main/resources/twigs")
if (dest.exists()) {
dest.deleteRecursively()
}
var command = listOf(
"cd", "../../twigs-web", ";",
"npm", "i", ";",
"npm", "run", "package"
)
command = if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows")) {
listOf("powershell", "-Command") + command
} else {
listOf("bash", "-c", "\"${command.joinToString(" ")}\"")
}
exec {
commandLine(command)
}
if (!built.copyRecursively(dest, true) || !dest.isDirectory) {
throw GradleException("Failed to copy files from ${built.absolutePath} to ${dest.absolutePath}")
}
}
}
//tasks.getByName("processResources") {
// dependsOn.add("package")
//}

View file

@ -0,0 +1,28 @@
package com.wbrawner.twigs.web
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.service.user.UserResponse
interface Page {
val title: String
val error: String?
}
interface AuthenticatedPage : Page {
val user: UserResponse
val budgets: List<BudgetListItem>
}
data class BudgetListItem(val id: String, val name: String, val description: String, val selected: Boolean)
fun BudgetResponse.toBudgetListItem(selectedId: String? = null) = BudgetListItem(
id = id,
name = name.orEmpty(),
description = description.orEmpty(),
selected = id == selectedId
)
object NotFoundPage : Page {
override val title: String = "404 Not Found"
override val error: String? = null
}

View file

@ -1,24 +1,52 @@
package com.wbrawner.twigs.web package com.wbrawner.twigs.web
import io.ktor.application.* import com.wbrawner.twigs.model.CookieSession
import io.ktor.http.content.* import com.wbrawner.twigs.service.HttpException
import io.ktor.request.* import com.wbrawner.twigs.service.budget.BudgetService
import io.ktor.response.* import com.wbrawner.twigs.service.category.CategoryService
import io.ktor.routing.* import com.wbrawner.twigs.service.transaction.TransactionService
import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.web.budget.budgetWebRoutes
import com.wbrawner.twigs.web.category.categoryWebRoutes
import com.wbrawner.twigs.web.transaction.transactionWebRoutes
import com.wbrawner.twigs.web.user.userWebRoutes
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.mustache.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
fun Application.webRoutes() { fun Application.webRoutes(
budgetService: BudgetService,
categoryService: CategoryService,
transactionService: TransactionService,
userService: UserService
) {
routing { routing {
static { staticResources("/", "static")
resources("twigs") get("/") {
default("index.html") call.sessions.get(CookieSession::class)
} ?.let {
intercept(ApplicationCallPipeline.Setup) { try {
if (!call.request.path().startsWith("/api") && !call.request.path().matches(Regex(".*\\.\\w+$"))) { userService.session(it.token)
call.resolveResource("twigs/index.html")?.let { } catch (e: HttpException) {
call.respond(it) application.environment.log.debug("Failed to retrieve session for user", e)
return@intercept finish() null
}
} }
} ?.let { session ->
application.environment.log.info("Session found!")
budgetService.budgetsForUser(session.userId)
.firstOrNull()
?.let { budget ->
call.respondRedirect("/budgets/${budget.id}")
} ?: call.respondRedirect("/budgets")
} ?: call.respond(MustacheContent("index.mustache", null))
} }
} }
budgetWebRoutes(budgetService, categoryService, transactionService, userService)
categoryWebRoutes(budgetService, categoryService, transactionService, userService)
transactionWebRoutes(budgetService, categoryService, transactionService, userService)
userWebRoutes(userService)
} }

View file

@ -0,0 +1,33 @@
package com.wbrawner.twigs.web
import io.ktor.http.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DateFormat
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*
val currencyFormat = NumberFormat.getCurrencyInstance(Locale.US)
val decimalFormat = DecimalFormat.getNumberInstance(Locale.US).apply {
with(this as DecimalFormat) {
decimalFormatSymbols = decimalFormatSymbols.apply {
currencySymbol = ""
isGroupingUsed = false
}
}
}
val shortDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US)
fun Parameters.getAmount() = decimalFormat.parse(get("amount"))
?.toDouble()
?.toBigDecimal()
?.times(BigDecimal(100))
?.toLong()
?: 0L
fun Long?.toDecimalString(): String {
if (this == null) return ""
return decimalFormat.format(toBigDecimal().divide(BigDecimal(100), 2, RoundingMode.HALF_UP))
}

View file

@ -0,0 +1,44 @@
package com.wbrawner.twigs.web.budget
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.service.user.UserResponse
import com.wbrawner.twigs.web.AuthenticatedPage
import com.wbrawner.twigs.web.BudgetListItem
import com.wbrawner.twigs.web.category.CategoryWithBalanceResponse
data class BudgetListPage(
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = "Budgets"
}
data class BudgetDetailsPage(
val budget: BudgetResponse,
val balances: BudgetBalances,
val incomeCategories: List<CategoryWithBalanceResponse>,
val expenseCategories: List<CategoryWithBalanceResponse>,
val archivedIncomeCategories: List<CategoryWithBalanceResponse>,
val archivedExpenseCategories: List<CategoryWithBalanceResponse>,
val transactionCount: String,
val monthAndYear: String,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = budget.name.orEmpty()
}
data class BudgetFormPage(
val budget: BudgetResponse,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = if (budget.id.isBlank()) {
"New Budget"
} else {
"Edit Budget"
}
}

View file

@ -0,0 +1,242 @@
package com.wbrawner.twigs.web.budget
import com.wbrawner.twigs.endOfMonth
import com.wbrawner.twigs.firstOfMonth
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.budget.BudgetRequest
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.service.budget.BudgetService
import com.wbrawner.twigs.service.category.CategoryService
import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.service.transaction.TransactionService
import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.toInstantOrNull
import com.wbrawner.twigs.web.NotFoundPage
import com.wbrawner.twigs.web.category.CategoryWithBalanceResponse
import com.wbrawner.twigs.web.toBudgetListItem
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.mustache.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.text.NumberFormat
import java.time.YearMonth
import java.time.format.DateTimeFormatter
import java.util.*
import kotlin.math.abs
fun Application.budgetWebRoutes(
budgetService: BudgetService,
categoryService: CategoryService,
transactionService: TransactionService,
userService: UserService
) {
routing {
authenticate(TWIGS_SESSION_COOKIE) {
route("/budgets") {
get {
val user = userService.user(requireSession().userId)
val budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() }
call.respond(MustacheContent("budgets.mustache", BudgetListPage(budgets, user)))
}
route("/new") {
get {
val user = userService.user(requireSession().userId)
call.respond(
MustacheContent(
"budget-form.mustache",
BudgetFormPage(
budget = BudgetResponse(
id = "",
name = "",
description = "",
users = listOf()
),
budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() },
user = user
)
)
)
}
post {
val user = userService.user(requireSession().userId)
try {
val request = call.receiveParameters().toBudgetRequest()
val budget = budgetService.save(request, user.id)
call.respondRedirect("/budgets/${budget.id}")
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent(
"budget-form.mustache",
BudgetFormPage(
budget = BudgetResponse(
id = "",
name = call.parameters["name"].orEmpty(),
description = call.parameters["description"].orEmpty(),
users = listOf()
),
budgets = budgetService.budgetsForUser(user.id).map { it.toBudgetListItem() },
user = user,
error = e.message
)
)
)
}
}
}
route("/{id}") {
get {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("id")
val budgets = budgetService.budgetsForUser(userId = user.id).toMutableList()
val budget = budgets.firstOrNull { it.id == budgetId }
?: run {
call.respond(MustacheContent("404.mustache", NotFoundPage))
return@get
}
val numberFormat = NumberFormat.getCurrencyInstance(Locale.US)
val categories = categoryService.categories(budgetIds = listOf(budget.id), userId = user.id)
.map { category ->
val categoryBalance =
abs(transactionService.sum(categoryId = category.id, userId = user.id))
CategoryWithBalanceResponse(
category = category,
amountLabel = category.amount.toCurrencyString(numberFormat),
balance = categoryBalance,
balanceLabel = categoryBalance.toCurrencyString(numberFormat),
remainingAmountLabel = (category.amount - categoryBalance).toCurrencyString(
numberFormat
)
)
}
.toMutableSet()
val incomeCategories = categories.extractIf { !it.category.expense && !it.category.archived }
val archivedIncomeCategories =
categories.extractIf { !it.category.expense && it.category.archived }
val expenseCategories = categories.extractIf { it.category.expense && !it.category.archived }
val archivedExpenseCategories =
categories.extractIf { it.category.expense && it.category.archived }
val transactions = transactionService.transactions(
budgetIds = listOf(budget.id),
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
userId = user.id
)
// TODO: Allow user-configurable locale
val budgetBalance = transactionService.sum(budgetId = budget.id, userId = user.id)
.toCurrencyString(numberFormat)
val expectedIncome = incomeCategories.sumOf { it.category.amount }
val actualIncome = transactions.sumOf { if (it.expense == false) it.amount ?: 0L else 0L }
val expectedExpenses = expenseCategories.sumOf { it.category.amount }
val actualExpenses = transactions.sumOf { if (it.expense == true) it.amount ?: 0L else 0L }
val balances = BudgetBalances(
cashFlow = budgetBalance,
expectedIncome = expectedIncome,
expectedIncomeLabel = expectedIncome.toCurrencyString(numberFormat),
actualIncome = actualIncome,
actualIncomeLabel = actualIncome.toCurrencyString(numberFormat),
expectedExpenses = expectedExpenses,
expectedExpensesLabel = expectedExpenses.toCurrencyString(numberFormat),
actualExpenses = actualExpenses,
actualExpensesLabel = actualExpenses.toCurrencyString(numberFormat),
)
call.respond(
MustacheContent(
"budget-details.mustache", BudgetDetailsPage(
budget = budget,
balances = balances,
incomeCategories = incomeCategories,
expenseCategories = expenseCategories,
archivedIncomeCategories = archivedIncomeCategories,
archivedExpenseCategories = archivedExpenseCategories,
transactionCount = NumberFormat.getNumberInstance(Locale.US)
.format(transactions.size),
monthAndYear = YearMonth.now().format(DateTimeFormatter.ofPattern("MMMM yyyy")),
budgets = budgets.map { it.toBudgetListItem(budgetId) }.sortedBy { it.name },
user = user
)
)
)
}
route("/edit") {
get {
val user = userService.user(requireSession().userId)
val budget = budgetService.budget(
budgetId = call.parameters.getOrFail("id"),
userId = user.id
)
call.respond(
MustacheContent(
"budget-form.mustache",
BudgetFormPage(
budget = budget,
budgets = budgetService.budgetsForUser(user.id)
.map { it.toBudgetListItem(budget.id) },
user = user
)
)
)
}
}
route("/delete") {
post {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("id")
budgetService.delete(budgetId = budgetId, userId = user.id)
call.respondRedirect("/")
}
}
}
}
}
}
}
data class BudgetBalances(
val cashFlow: String,
val expectedIncome: Long,
val expectedIncomeLabel: String,
val actualIncome: Long,
val actualIncomeLabel: String,
val expectedExpenses: Long,
val expectedExpensesLabel: String,
val actualExpenses: Long,
val actualExpensesLabel: String,
) {
val maxProgressBarValue: Long = maxOf(expectedExpenses, expectedIncome, actualIncome, actualExpenses)
}
private fun Parameters.toBudgetRequest() = BudgetRequest(
name = get("name"),
description = get("description"),
users = setOf() // TODO: Enable adding users at budget creation
)
private fun <T> MutableCollection<T>.extractIf(predicate: (T) -> Boolean): List<T> {
val extracted = mutableListOf<T>()
val iterator = iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (predicate(item)) {
extracted.add(item)
iterator.remove()
}
}
return extracted
}
fun Long.toCurrencyString(formatter: NumberFormat): String = formatter.format(
this.toBigDecimal().divide(BigDecimal(100), 2, RoundingMode.HALF_UP)
)

View file

@ -0,0 +1,67 @@
package com.wbrawner.twigs.web.category
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.service.category.CategoryResponse
import com.wbrawner.twigs.service.transaction.TransactionResponse
import com.wbrawner.twigs.service.user.UserResponse
import com.wbrawner.twigs.web.AuthenticatedPage
import com.wbrawner.twigs.web.BudgetListItem
import com.wbrawner.twigs.web.budget.toCurrencyString
import java.text.NumberFormat
data class CategoryDetailsPage(
val category: CategoryWithBalanceResponse,
val budget: BudgetResponse,
val transactionCount: String,
val transactions: List<Map.Entry<String, List<TransactionListItem>>>,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = category.category.title
}
data class TransactionListItem(
val id: String,
val title: String,
val description: String,
val budgetId: String,
val expenseClass: String,
val amountLabel: String
)
fun TransactionResponse.toListItem(numberFormat: NumberFormat) = TransactionListItem(
id,
title.orEmpty(),
description.orEmpty(),
budgetId,
if (expense != false) "expense" else "income",
(amount ?: 0L).toCurrencyString(numberFormat)
)
data class CategoryFormPage(
val category: CategoryResponse,
val amountLabel: String,
val budget: BudgetResponse,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = if (category.id.isBlank()) {
"New Category"
} else {
"Edit Category"
}
val expenseChecked: String = if (category.expense) "checked" else ""
val incomeChecked: String = if (!category.expense) "checked" else ""
val archivedChecked: String = if (category.archived) "checked" else ""
}
data class CategoryWithBalanceResponse(
val category: CategoryResponse,
val amountLabel: String,
val balance: Long,
val balanceLabel: String,
val remainingAmountLabel: String,
)

View file

@ -0,0 +1,245 @@
package com.wbrawner.twigs.web.category
import com.wbrawner.twigs.endOfMonth
import com.wbrawner.twigs.firstOfMonth
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.budget.BudgetService
import com.wbrawner.twigs.service.category.CategoryRequest
import com.wbrawner.twigs.service.category.CategoryResponse
import com.wbrawner.twigs.service.category.CategoryService
import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.service.transaction.TransactionService
import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.toInstant
import com.wbrawner.twigs.toInstantOrNull
import com.wbrawner.twigs.web.*
import com.wbrawner.twigs.web.budget.toCurrencyString
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.mustache.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import io.ktor.util.date.*
import java.text.NumberFormat
import java.util.*
import kotlin.math.abs
fun Application.categoryWebRoutes(
budgetService: BudgetService,
categoryService: CategoryService,
transactionService: TransactionService,
userService: UserService
) {
routing {
authenticate(TWIGS_SESSION_COOKIE) {
route("/budgets/{budgetId}/categories") {
get {
val budgetId = call.parameters.getOrFail("budgetId")
call.respondRedirect("/budgets/$budgetId")
}
route("/new") {
get {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == budgetId }
call.respond(
MustacheContent(
"category-form.mustache",
CategoryFormPage(
CategoryResponse(
id = "",
title = "",
description = "",
amount = 0,
budgetId = budgetId,
expense = call.request.queryParameters["expense"]?.toBoolean() ?: true,
archived = false,
),
amountLabel = 0L.toDecimalString(),
budget = budget,
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user
)
)
)
}
post {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == budgetId }
try {
val request = call.receiveParameters().toCategoryRequest(budgetId)
val category = categoryService.save(request, user.id)
call.respondRedirect("/budgets/${category.budgetId}/categories/${category.id}")
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent(
"category-form.mustache",
CategoryFormPage(
CategoryResponse(
id = "",
title = call.parameters["title"].orEmpty(),
description = call.parameters["description"].orEmpty(),
amount = 0L,
expense = call.parameters["expense"]?.toBoolean() ?: false,
archived = call.parameters["archived"]?.toBoolean() ?: false,
budgetId = budgetId
),
amountLabel = call.parameters["amount"]?.toLongOrNull().toDecimalString(),
budget = budget,
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user,
error = e.message
)
)
)
}
}
}
route("/{id}") {
get {
val user = userService.user(requireSession().userId)
val categoryId = call.parameters.getOrFail("id")
try {
val category = categoryService.category(categoryId = categoryId, userId = user.id)
val categoryBalance =
abs(transactionService.sum(categoryId = category.id, userId = user.id))
val categoryWithBalance = CategoryWithBalanceResponse(
category = category,
amountLabel = category.amount.toCurrencyString(currencyFormat),
balance = categoryBalance,
balanceLabel = categoryBalance.toCurrencyString(currencyFormat),
remainingAmountLabel = (category.amount - categoryBalance).toCurrencyString(
currencyFormat
)
)
val transactions = transactionService.transactions(
budgetIds = listOf(category.budgetId),
categoryIds = listOf(category.id),
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
userId = user.id
)
val transactionCount = NumberFormat.getNumberInstance(Locale.US)
.format(transactions.size)
val transactionsByDate = transactions.groupBy {
shortDateFormat.format(it.date.toInstant().toGMTDate().toJvmDate())
}
.mapValues { (_, transactions) -> transactions.map { it.toListItem(currencyFormat) } }
.entries
.sortedByDescending { it.key }
val budgets = budgetService.budgetsForUser(user.id)
val budgetId = call.parameters.getOrFail("budgetId")
val budget = budgets.first { it.id == budgetId }
call.respond(
MustacheContent(
"category-details.mustache", CategoryDetailsPage(
category = categoryWithBalance,
transactions = transactionsByDate,
transactionCount = transactionCount,
budgets = budgets.map { it.toBudgetListItem(budgetId) },
budget = budget,
user = user
)
)
)
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent("404.mustache", NotFoundPage)
)
}
}
route("/edit") {
get {
val user = userService.user(requireSession().userId)
val category = categoryService.category(
categoryId = call.parameters.getOrFail("id"),
userId = user.id
)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
call.respond(
MustacheContent(
"category-form.mustache",
CategoryFormPage(
category = category,
amountLabel = category.amount.toDecimalString(),
budget = budgets.first { it.id == budgetId },
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user
)
)
)
}
post {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val categoryId = call.parameters.getOrFail("id")
try {
val request = call.receiveParameters().toCategoryRequest(budgetId)
val category = categoryService.save(request, userId = user.id, categoryId = categoryId)
call.respondRedirect("/budgets/${category.budgetId}/categories/${category.id}")
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent(
"category-form.mustache",
CategoryFormPage(
CategoryResponse(
id = "",
title = call.parameters["title"].orEmpty(),
description = call.parameters["description"].orEmpty(),
amount = 0L,
expense = call.parameters["expense"]?.toBoolean() ?: false,
archived = call.parameters["archived"]?.toBoolean() ?: false,
budgetId = budgetId
),
amountLabel = call.parameters["amount"]?.toLongOrNull().toDecimalString(),
budget = budgets.first { it.id == budgetId },
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user,
error = e.message
)
)
)
}
}
}
route("/delete") {
post {
val user = userService.user(requireSession().userId)
val categoryId = call.parameters.getOrFail("id")
categoryService.delete(categoryId = categoryId, userId = user.id)
val budgetId = call.parameters.getOrFail("budgetId")
call.respondRedirect("/budgets/$budgetId")
}
}
}
}
}
}
}
private fun Parameters.toCategoryRequest(budgetId: String) = CategoryRequest(
title = get("title"),
description = get("description"),
amount = getAmount(),
expense = get("expense")?.toBoolean(),
archived = get("archived") == "on",
budgetId = budgetId
)

View file

@ -0,0 +1,66 @@
package com.wbrawner.twigs.web.transaction
import com.wbrawner.twigs.service.budget.BudgetResponse
import com.wbrawner.twigs.service.category.CategoryResponse
import com.wbrawner.twigs.service.transaction.TransactionResponse
import com.wbrawner.twigs.service.user.UserResponse
import com.wbrawner.twigs.web.AuthenticatedPage
import com.wbrawner.twigs.web.BudgetListItem
import com.wbrawner.twigs.web.category.TransactionListItem
data class TransactionListPage(
val budget: BudgetResponse,
val transactions: List<Map.Entry<String, List<TransactionListItem>>>,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = "Transactions"
}
data class TransactionDetailsPage(
val transaction: TransactionResponse,
val category: CategoryResponse?,
val budget: BudgetResponse,
val amountLabel: String,
val dateLabel: String,
val createdBy: UserResponse,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = transaction.title.orEmpty()
}
data class TransactionFormPage(
val transaction: TransactionResponse,
val amountLabel: String,
val budget: BudgetResponse,
val categoryOptions: List<CategoryOption>,
override val budgets: List<BudgetListItem>,
override val user: UserResponse,
override val error: String? = null
) : AuthenticatedPage {
override val title: String = if (transaction.id.isBlank()) {
"New Transaction"
} else {
"Edit Transaction"
}
data class CategoryOption(
val id: String,
val title: String,
val isSelected: Boolean = false,
val isDisabled: Boolean = false
) {
val selected: String
get() = if (isSelected) "selected" else ""
val disabled: String
get() = if (isDisabled) "disabled" else ""
}
}
fun CategoryResponse.asOption(selectedCategoryId: String) =
TransactionFormPage.CategoryOption(id, title, id == selectedCategoryId)

View file

@ -0,0 +1,362 @@
package com.wbrawner.twigs.web.transaction
import com.wbrawner.twigs.endOfMonth
import com.wbrawner.twigs.firstOfMonth
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.budget.BudgetService
import com.wbrawner.twigs.service.category.CategoryService
import com.wbrawner.twigs.service.requireSession
import com.wbrawner.twigs.service.transaction.TransactionRequest
import com.wbrawner.twigs.service.transaction.TransactionResponse
import com.wbrawner.twigs.service.transaction.TransactionService
import com.wbrawner.twigs.service.user.UserResponse
import com.wbrawner.twigs.service.user.UserService
import com.wbrawner.twigs.toInstant
import com.wbrawner.twigs.toInstantOrNull
import com.wbrawner.twigs.web.*
import com.wbrawner.twigs.web.budget.toCurrencyString
import com.wbrawner.twigs.web.category.toListItem
import com.wbrawner.twigs.web.user.TWIGS_SESSION_COOKIE
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.mustache.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*
import io.ktor.util.date.*
import java.time.Instant
import java.time.ZoneOffset.UTC
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
fun Application.transactionWebRoutes(
budgetService: BudgetService,
categoryService: CategoryService,
transactionService: TransactionService,
userService: UserService
) {
routing {
authenticate(TWIGS_SESSION_COOKIE) {
route("/budgets/{budgetId}/transactions") {
get {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val transactions = transactionService.transactions(
budgetIds = listOf(budgetId),
from = call.parameters["from"]?.toInstantOrNull() ?: firstOfMonth,
to = call.parameters["to"]?.toInstantOrNull() ?: endOfMonth,
userId = user.id
)
val transactionsByDate = transactions.groupBy {
shortDateFormat.format(it.date.toInstant().toGMTDate().toJvmDate())
}
.mapValues { (_, transactions) -> transactions.map { it.toListItem(currencyFormat) } }
.entries
.sortedByDescending { it.key }
call.respond(
MustacheContent(
"budget-transactions.mustache",
TransactionListPage(
budgets = budgets.map { it.toBudgetListItem(budgetId) },
budget = budgets.first { it.id == budgetId },
transactions = transactionsByDate,
user = user
)
)
)
}
route("/new") {
get {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == budgetId }
val categoryId = call.request.queryParameters["categoryId"]
val transaction = TransactionResponse(
id = "",
title = "",
description = "",
amount = 0,
budgetId = budgetId,
expense = true,
date = Instant.now().toHtmlInputString(),
categoryId = categoryId,
createdBy = user.id
)
call.respond(
MustacheContent(
"transaction-form.mustache",
TransactionFormPage(
transaction = transaction,
amountLabel = 0L.toDecimalString(),
budget = budget,
categoryOptions = categoryOptions(
transaction = transaction,
categoryService = categoryService,
budgetId = budgetId,
user = user
),
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user
)
)
)
}
post {
val user = userService.user(requireSession().userId)
val urlBudgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == urlBudgetId }
try {
val request = call.receiveParameters().toTransactionRequest()
.run {
copy(
date = "$date:00Z",
expense = categoryService.category(
categoryId = requireNotNull(categoryId),
userId = user.id
).expense,
budgetId = urlBudgetId
)
}
val transaction = transactionService.save(request, user.id)
call.respondRedirect("/budgets/${transaction.budgetId}/transactions/${transaction.id}")
} catch (e: HttpException) {
val transaction = TransactionResponse(
id = "",
title = call.parameters["title"],
description = call.parameters["description"],
amount = 0L,
budgetId = urlBudgetId,
expense = call.parameters["expense"]?.toBoolean() ?: true,
date = call.parameters["date"].orEmpty(),
categoryId = call.parameters["categoryId"],
createdBy = user.id
)
call.respond(
status = e.statusCode,
MustacheContent(
"transaction-form.mustache",
TransactionFormPage(
transaction = transaction,
amountLabel = call.parameters["amount"].orEmpty(),
budget = budget,
categoryOptions = categoryOptions(
transaction,
categoryService,
urlBudgetId,
user
),
budgets = budgets.map { it.toBudgetListItem(urlBudgetId) },
user = user,
error = e.message
)
)
)
}
}
}
route("/{id}") {
get {
val user = userService.user(requireSession().userId)
val transactionId = call.parameters.getOrFail("id")
val budgetId = call.parameters.getOrFail("budgetId")
// TODO: Allow user-configurable locale
try {
val transaction = transactionService.transaction(
transactionId = transactionId,
userId = user.id
)
check(transaction.budgetId == budgetId) {
// TODO: redirect instead of error?
"Attempted to fetch transaction from wrong budget"
}
val category = transaction.categoryId?.let {
categoryService.category(categoryId = it, userId = user.id)
}
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == budgetId }
val dateFormat = DateTimeFormatter.ofPattern("H:mm a 'on' MMMM d, yyyy")
val transactionInstant = transaction.date.toInstant()
val transactionOffset = transactionInstant.atOffset(UTC)
val dateLabel = transactionOffset.format(dateFormat)
call.respond(
MustacheContent(
"transaction-details.mustache", TransactionDetailsPage(
transaction = transaction,
category = category,
budget = budget,
budgets = budgets.map { it.toBudgetListItem(budgetId) },
amountLabel = transaction.amount?.toCurrencyString(currencyFormat).orEmpty(),
dateLabel = dateLabel,
createdBy = userService.user(transaction.createdBy),
user = user
)
)
)
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent("404.mustache", NotFoundPage)
)
}
}
route("/edit") {
get {
val user = userService.user(requireSession().userId)
val budgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == budgetId }
val transaction = transactionService.transaction(
transactionId = call.parameters.getOrFail("id"),
userId = user.id
)
call.respond(
MustacheContent(
"transaction-form.mustache",
TransactionFormPage(
transaction = transaction.copy(
date = transaction.date.toInstant().toHtmlInputString()
),
amountLabel = transaction.amount.toDecimalString(),
budget = budget,
categoryOptions = categoryOptions(transaction, categoryService, budgetId, user),
budgets = budgets.map { it.toBudgetListItem(budgetId) },
user = user
)
)
)
}
post {
val user = userService.user(requireSession().userId)
val transactionId = call.parameters.getOrFail("id")
val urlBudgetId = call.parameters.getOrFail("budgetId")
val budgets = budgetService.budgetsForUser(user.id)
val budget = budgets.first { it.id == urlBudgetId }
try {
val request = call.receiveParameters().toTransactionRequest()
.run {
copy(
date = "$date:00Z",
expense = categoryService.category(
categoryId = requireNotNull(categoryId),
userId = user.id
).expense,
budgetId = urlBudgetId
)
}
val transaction =
transactionService.save(request, userId = user.id, transactionId = transactionId)
call.respondRedirect("/budgets/${transaction.budgetId}/transactions/${transaction.id}")
} catch (e: HttpException) {
val transaction = TransactionResponse(
id = transactionId,
title = call.parameters["title"],
description = call.parameters["description"],
amount = 0L,
budgetId = urlBudgetId,
expense = call.parameters["expense"]?.toBoolean() ?: true,
date = call.parameters["date"].orEmpty(),
categoryId = call.parameters["categoryId"],
createdBy = user.id
)
call.respond(
status = e.statusCode,
MustacheContent(
"transaction-form.mustache",
TransactionFormPage(
transaction = transaction,
amountLabel = call.parameters["amount"].orEmpty(),
budget = budget,
categoryOptions = categoryOptions(
transaction,
categoryService,
urlBudgetId,
user
),
budgets = budgets.map { it.toBudgetListItem(urlBudgetId) },
user = user,
error = e.message
)
)
)
}
}
}
route("/delete") {
post {
val user = userService.user(requireSession().userId)
val transactionId = call.parameters.getOrFail("id")
val urlBudgetId = call.parameters.getOrFail("budgetId")
transactionService.delete(transactionId = transactionId, userId = user.id)
call.respondRedirect("/budgets/${urlBudgetId}")
}
}
}
}
}
}
}
private suspend fun categoryOptions(
transaction: TransactionResponse,
categoryService: CategoryService,
budgetId: String,
user: UserResponse
): List<TransactionFormPage.CategoryOption> {
val selectedCategoryId = transaction.categoryId.orEmpty()
val categoryOptions = listOf(
TransactionFormPage.CategoryOption(
"",
"Select a category",
isSelected = transaction.categoryId.isNullOrBlank(),
isDisabled = true
),
TransactionFormPage.CategoryOption("income", "Income", isDisabled = true),
)
.plus(
categoryService.categories(
budgetIds = listOf(budgetId),
userId = user.id,
expense = false,
archived = false
).map { category ->
category.asOption(selectedCategoryId)
}
)
.plus(
TransactionFormPage.CategoryOption("expense", "Expense", isDisabled = true),
)
.plus(
categoryService.categories(
budgetIds = listOf(budgetId),
userId = user.id,
expense = true,
archived = false
).map { category ->
category.asOption(selectedCategoryId)
}
)
return categoryOptions
}
private fun Parameters.toTransactionRequest() = TransactionRequest(
title = get("title"),
description = get("description"),
amount = getAmount(),
expense = false,
date = get("date"),
categoryId = get("categoryId"),
budgetId = get("budgetId"),
)
private fun Instant.toHtmlInputString() = truncatedTo(ChronoUnit.MINUTES).toString().substringBefore(":00Z")

View file

@ -0,0 +1,11 @@
package com.wbrawner.twigs.web.user
import com.wbrawner.twigs.web.Page
data class LoginPage(val username: String = "", override val error: String? = null) : Page {
override val title: String = "Login"
}
data class RegisterPage(val username: String = "", val email: String = "", override val error: String? = null) : Page {
override val title: String = "Register"
}

View file

@ -0,0 +1,94 @@
package com.wbrawner.twigs.web.user
import com.wbrawner.twigs.model.CookieSession
import com.wbrawner.twigs.service.HttpException
import com.wbrawner.twigs.service.user.LoginRequest
import com.wbrawner.twigs.service.user.UserRequest
import com.wbrawner.twigs.service.user.UserService
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.mustache.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*
import io.ktor.server.util.*
const val TWIGS_SESSION_COOKIE = "twigsSession"
fun Application.userWebRoutes(userService: UserService) {
routing {
route("/login") {
get {
call.respond(MustacheContent("login.mustache", LoginPage()))
}
post {
val request = call.receiveParameters().toLoginRequest()
try {
val session = userService.login(request)
call.sessions.set(CookieSession(session.token))
call.respondRedirect("/")
} catch (e: Throwable) {
e.printStackTrace()
call.respond(
status = (e as? HttpException)?.statusCode ?: HttpStatusCode.InternalServerError,
MustacheContent("login.mustache", LoginPage(username = request.username, error = e.message))
)
}
}
}
route("/logout") {
post {
call.sessions.clear<CookieSession>()
call.respondRedirect("/")
}
}
route("/register") {
get {
call.respond(MustacheContent("register.mustache", RegisterPage()))
}
post {
val request = call.receiveParameters()
val userRequest = request.toUserRequest()
val confirmPassword = request.getOrFail("confirmPassword")
if (userRequest.password != confirmPassword) {
call.respond(
HttpStatusCode.BadRequest,
MustacheContent(
"register.mustache",
userRequest.toPage("passwords don't match")
)
)
return@post
}
try {
userService.register(userRequest)
val session = userService.login(
LoginRequest(
requireNotNull(userRequest.username),
requireNotNull(userRequest.password)
)
)
call.sessions.set(CookieSession(session.token))
call.respondRedirect("/")
} catch (e: HttpException) {
call.respond(
status = e.statusCode,
MustacheContent("register.mustache", userRequest.toPage(error = e.message))
)
}
}
}
}
}
private fun Parameters.toLoginRequest() = LoginRequest(get("username").orEmpty(), get("password").orEmpty())
private fun Parameters.toUserRequest() = UserRequest(get("username").orEmpty(), get("password").orEmpty(), get("email"))
private fun UserRequest.toPage(error: String? = null) =
RegisterPage(username = username.orEmpty(), email = email.orEmpty(), error = error)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 969 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

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