Compare commits

...

97 Commits
0.9.5 ... main

Author SHA1 Message Date
24c503385e Merge pull request 'Version 3.4' (#78) from 3.4 into main
Reviewed-on: #78
2024-06-07 23:37:08 +00:00
b393a86bb5 Configure id field 2024-06-07 19:35:17 -04:00
8ee3c6b483 Add documentation and handler (#77) 2024-06-07 12:04:00 -04:00
b07532ab50 Update Dockerfile to .NET 8 (#75)
- Update deps
- Implement newer doc library
2024-06-06 23:07:57 -04:00
b3f62c2586 WIP on update to .NET 8 (#75) 2024-06-06 22:49:57 -04:00
20dcaf6e1b Remove LiteDB/PostgreSQL migration util 2023-10-09 22:19:34 -04:00
b9d81fb7aa
Convert Data Storage to PostgreSQL Documents (#74) 2023-10-09 22:15:38 -04:00
3df5c71d81 Update deps; move to .NET 7
- Update local htmx to v1.9.2
- Get version from assembly
2023-05-23 21:14:08 -04:00
c697001736
Merge pull request #73 from bit-badger/dependabot/nuget/src/MyPrayerJournal/LiteDB-5.0.13
Bump LiteDB from 5.0.12 to 5.0.13 in /src/MyPrayerJournal
2023-05-23 20:11:51 -04:00
dependabot[bot]
6c28cfc1ec
Bump LiteDB from 5.0.12 to 5.0.13 in /src/MyPrayerJournal
Bumps [LiteDB](https://github.com/mbdavid/LiteDB) from 5.0.12 to 5.0.13.
- [Release notes](https://github.com/mbdavid/LiteDB/releases)
- [Commits](https://github.com/mbdavid/LiteDB/compare/v5.0.12...v5.0.13)

---
updated-dependencies:
- dependency-name: LiteDB
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-24 16:37:59 +00:00
8702723e01 Fix request ID generation (#72)
- Bump version
2022-08-23 08:36:17 -04:00
d621ede7bb
Version 3.1 (#71)
- Fix request sorting
- Send time zone, so request actions are displayed in local time
- Make recurrence a true DU
- Tweak the data store representation of a few other fields
2022-07-30 17:02:58 -04:00
a826275510 Add NuGet packages for htmx extensions 2021-11-11 19:17:14 -05:00
2a86e41fe3 Add JetBrains link
Also fix typo
2021-11-03 10:52:42 -04:00
babc77bbd0 Remove v2/v3 migration project 2021-10-26 19:50:51 -04:00
997279783f
Version 3 (#67) 2021-10-26 19:39:58 -04:00
77c85f516c Version 3 2021-10-26 19:38:45 -04:00
ca622aa4b7 Merge branch 'master' of https://github.com/bit-badger/myPrayerJournal 2021-10-26 19:22:54 -04:00
cce4f17cd8 Update to .NET 5 (#48); update deps 2021-06-19 14:08:49 -04:00
0bf73e49c9
Merge pull request #61 from bit-badger/dependabot/npm_and_yarn/src/app/yargs-parser-5.0.1
Bump yargs-parser from 5.0.0 to 5.0.1 in /src/app
2021-06-19 13:29:57 -04:00
a84d54c095
Merge pull request #60 from bit-badger/dependabot/npm_and_yarn/src/app/ws-6.2.2
Bump ws from 6.2.1 to 6.2.2 in /src/app
2021-06-19 13:29:28 -04:00
dependabot[bot]
68f4a1b9b2
Bump ws from 6.2.1 to 6.2.2 in /src/app
Bumps [ws](https://github.com/websockets/ws) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/commits)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-19 17:29:13 +00:00
23ccd3ac67
Merge pull request #59 from bit-badger/dependabot/npm_and_yarn/src/app/dns-packet-1.3.4
Bump dns-packet from 1.3.1 to 1.3.4 in /src/app
2021-06-19 13:28:26 -04:00
d4823c15f7
Merge pull request #58 from bit-badger/dependabot/npm_and_yarn/src/app/browserslist-4.16.6
Bump browserslist from 4.11.1 to 4.16.6 in /src/app
2021-06-19 13:27:51 -04:00
fc01e79337
Merge pull request #57 from bit-badger/dependabot/npm_and_yarn/src/app/hosted-git-info-2.8.9
Bump hosted-git-info from 2.8.8 to 2.8.9 in /src/app
2021-06-19 13:27:15 -04:00
fa9c902af7
Merge pull request #56 from bit-badger/dependabot/npm_and_yarn/src/app/url-parse-1.5.1
Bump url-parse from 1.4.7 to 1.5.1 in /src/app
2021-06-19 13:26:34 -04:00
dependabot[bot]
ed762ea03e
Bump yargs-parser from 5.0.0 to 5.0.1 in /src/app
Bumps [yargs-parser](https://github.com/yargs/yargs-parser) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/yargs/yargs-parser/releases)
- [Changelog](https://github.com/yargs/yargs-parser/blob/v5.0.1/CHANGELOG.md)
- [Commits](https://github.com/yargs/yargs-parser/compare/v5.0.0...v5.0.1)

---
updated-dependencies:
- dependency-name: yargs-parser
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-19 17:26:25 +00:00
3675af3dca
Merge pull request #55 from bit-badger/dependabot/npm_and_yarn/src/app/y18n-3.2.2
Bump y18n from 3.2.1 to 3.2.2 in /src/app
2021-06-19 13:25:41 -04:00
dependabot[bot]
1830e01ad6
Bump dns-packet from 1.3.1 to 1.3.4 in /src/app
Bumps [dns-packet](https://github.com/mafintosh/dns-packet) from 1.3.1 to 1.3.4.
- [Release notes](https://github.com/mafintosh/dns-packet/releases)
- [Changelog](https://github.com/mafintosh/dns-packet/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mafintosh/dns-packet/compare/v1.3.1...v1.3.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-27 07:41:55 +00:00
dependabot[bot]
ffe057d7ee
Bump browserslist from 4.11.1 to 4.16.6 in /src/app
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.11.1 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.11.1...4.16.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-24 23:59:12 +00:00
dependabot[bot]
bafdfb1af5
Bump hosted-git-info from 2.8.8 to 2.8.9 in /src/app
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-09 23:16:11 +00:00
dependabot[bot]
3d907e9569
Bump url-parse from 1.4.7 to 1.5.1 in /src/app
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.4.7 to 1.5.1.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.4.7...1.5.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-07 10:02:02 +00:00
dependabot[bot]
c8ef6e8714
Bump y18n from 3.2.1 to 3.2.2 in /src/app
Bumps [y18n](https://github.com/yargs/y18n) from 3.2.1 to 3.2.2.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-30 13:23:51 +00:00
266243423c Update deps 2021-03-09 11:45:54 -05:00
92a493251a
Merge pull request #50 from bit-badger/dependabot/npm_and_yarn/src/app/axios-0.21.1
Bump axios from 0.19.2 to 0.21.1 in /src/app
2021-03-09 10:46:35 -05:00
c7c63d01f8
Merge pull request #54 from bit-badger/dependabot/npm_and_yarn/src/app/lodash-4.17.21
Bump lodash from 4.17.15 to 4.17.21 in /src/app
2021-03-09 10:45:19 -05:00
dependabot[bot]
62a18a8b09
Bump axios from 0.19.2 to 0.21.1 in /src/app
Bumps [axios](https://github.com/axios/axios) from 0.19.2 to 0.21.1.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v0.21.1/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v0.19.2...v0.21.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:45:18 +00:00
d1a9eb62c3
Merge pull request #49 from bit-badger/dependabot/npm_and_yarn/src/app/highlight.js-9.18.5
Bump highlight.js from 9.18.1 to 9.18.5 in /src/app
2021-03-09 10:44:11 -05:00
407222d06a
Merge pull request #47 from bit-badger/dependabot/npm_and_yarn/src/app/node-fetch-2.6.1
Bump node-fetch from 2.6.0 to 2.6.1 in /src/app
2021-03-09 10:43:29 -05:00
044283709c
Merge pull request #46 from bit-badger/dependabot/npm_and_yarn/src/app/http-proxy-1.18.1
Bump http-proxy from 1.18.0 to 1.18.1 in /src/app
2021-03-09 10:43:04 -05:00
dependabot[bot]
be86fbfcba
Bump highlight.js from 9.18.1 to 9.18.5 in /src/app
Bumps [highlight.js](https://github.com/highlightjs/highlight.js) from 9.18.1 to 9.18.5.
- [Release notes](https://github.com/highlightjs/highlight.js/releases)
- [Changelog](https://github.com/highlightjs/highlight.js/blob/9.18.5/CHANGES.md)
- [Commits](https://github.com/highlightjs/highlight.js/compare/9.18.1...9.18.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:42:51 +00:00
dependabot[bot]
63b3037ede
Bump lodash from 4.17.15 to 4.17.21 in /src/app
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:42:15 +00:00
d239b16d33
Merge pull request #43 from bit-badger/dependabot/npm_and_yarn/src/app/websocket-extensions-0.1.4
Bump websocket-extensions from 0.1.3 to 0.1.4 in /src/app
2021-03-09 10:41:56 -05:00
a9ab0446c4
Merge pull request #52 from bit-badger/dependabot/npm_and_yarn/src/app/pug-3.0.1
Bump pug from 2.0.4 to 3.0.1 in /src/app
2021-03-09 10:39:59 -05:00
366ed2ed2f
Merge pull request #53 from bit-badger/dependabot/npm_and_yarn/src/app/elliptic-6.5.4
Bump elliptic from 6.5.2 to 6.5.4 in /src/app
2021-03-09 10:39:29 -05:00
dependabot[bot]
fb304c26b6
Bump elliptic from 6.5.2 to 6.5.4 in /src/app
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.2 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.2...v6.5.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 00:56:03 +00:00
dependabot[bot]
7b11e70e76
Bump pug from 2.0.4 to 3.0.1 in /src/app
Bumps [pug](https://github.com/pugjs/pug) from 2.0.4 to 3.0.1.
- [Release notes](https://github.com/pugjs/pug/releases)
- [Commits](https://github.com/pugjs/pug/compare/pug@2.0.4...pug@3.0.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-03 02:54:57 +00:00
dependabot[bot]
f50a8ae83e
Bump node-fetch from 2.6.0 to 2.6.1 in /src/app
Bumps [node-fetch](https://github.com/bitinn/node-fetch) from 2.6.0 to 2.6.1.
- [Release notes](https://github.com/bitinn/node-fetch/releases)
- [Changelog](https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/bitinn/node-fetch/compare/v2.6.0...v2.6.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-12 05:25:20 +00:00
dependabot[bot]
aa0864416f
Bump http-proxy from 1.18.0 to 1.18.1 in /src/app
Bumps [http-proxy](https://github.com/http-party/node-http-proxy) from 1.18.0 to 1.18.1.
- [Release notes](https://github.com/http-party/node-http-proxy/releases)
- [Changelog](https://github.com/http-party/node-http-proxy/blob/master/CHANGELOG.md)
- [Commits](https://github.com/http-party/node-http-proxy/compare/1.18.0...1.18.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-07 11:51:40 +00:00
dependabot[bot]
05a1b7adda
Bump websocket-extensions from 0.1.3 to 0.1.4 in /src/app
Bumps [websocket-extensions](https://github.com/faye/websocket-extensions-node) from 0.1.3 to 0.1.4.
- [Release notes](https://github.com/faye/websocket-extensions-node/releases)
- [Changelog](https://github.com/faye/websocket-extensions-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/faye/websocket-extensions-node/compare/0.1.3...0.1.4)

Signed-off-by: dependabot[bot] <support@github.com>
2020-06-06 13:17:04 +00:00
Daniel J. Summers
f833598cdd Fix progress bar style 2020-05-21 08:05:03 -05:00
Daniel J. Summers
dfd1c59554 Fix tryJournalById function (#42)
Also update .NET deps
2020-04-23 10:07:23 -05:00
Daniel J. Summers
83b70073e9 Update deps 2020-04-11 08:51:14 -05:00
dependabot[bot]
11025cc39a
Bump auth0-js from 9.12.2 to 9.13.2 in /src/app (#40) 2020-04-11 13:37:32 +00:00
Daniel J. Summers
fb908a1cef Update to .NET Core 3.1 (#39)
Also catch dependencies up to latest
2020-03-07 18:30:21 -06:00
Daniel J. Summers
6a6f7b35c7 Reverse notes ordering, make scrollable (#32) 2019-10-14 10:50:50 -05:00
715df08cbe
Migrate API to .NET Core 3.0 (#31)
Migrate API to .NET Core 3.0 (fixes #30)
2019-09-28 08:42:58 -05:00
Daniel J. Summers
ac8b39fff9 Update version 2019-09-26 21:22:14 -05:00
Daniel J. Summers
2bf54136ca Fix journal ordering fix (#28 again) 2019-09-26 20:46:08 -05:00
Daniel J. Summers
0709cabea1 Fix journal ordering (#28) 2019-09-10 06:08:19 -05:00
Daniel J. Summers
cbd9114599 Update deps
fixes security for eslint-utils, which isn't part of the published package; no same-day point-plusone release required
2019-09-02 19:39:51 -05:00
Daniel J. Summers
097ee2deb4 Remove v2 migration program 2019-09-02 19:07:51 -05:00
fa78e86de6
myPrayerJournal v2 (#27)
App changes:
* Move to Vue Material for UI components
* Convert request cards to true material design cards, separating the "pray" button from the others and improved highlighting of the current request
* Centralize Auth0 integration in one place; modify the Vuex store to rely on it entirely, and add a Vue mixin to make it accessible by any component

API changes:
* Change backing data store to RavenDB
* Evolve domain models (using F# discriminated unions, and JSON converters for storage) to make invalid states unrepresentable
* Incorporate the FunctionalCuid library
* Create a functional pipeline for app configuration instead of chaining `IWebHostBuilder` calls

Bug fixes:
* Set showAfter to 0 for immediately recurring requests (#26)
2019-09-02 19:01:26 -05:00
Daniel J. Summers
ce588b6a43 dep update for lodash CVE 2019-07-12 19:34:26 -05:00
Daniel J. Summers
57cd17c734 Fixed broken pray button 2019-07-07 07:08:42 -05:00
Daniel J. Summers
42615dae82 Update recurrence before status (#25); version bump 2019-07-05 20:34:38 -05:00
Daniel J. Summers
68b650e31d Updated dependencies 2019-05-31 20:29:57 -05:00
Daniel J. Summers
d738321dc0 Use FSharpLu for JSON serialization (#24) 2019-02-23 13:59:32 -06:00
Daniel J. Summers
8995097d68 Updated to .NET Core 2.2 (#23)
Also updated API and app deps
2019-02-23 10:59:23 -06:00
Daniel J. Summers
4310fb91fa Updated deps 2019-01-29 20:52:38 -06:00
Daniel J. Summers
c0def7623f Updated docs link to new subdomain 2018-09-09 21:08:22 -05:00
Daniel J. Summers
ab8fab51c5 Create CNAME 2018-09-07 17:43:59 -05:00
Daniel J. Summers
96717ae7c4 Delete CNAME 2018-09-07 17:43:43 -05:00
Daniel J. Summers
b11ff0ff3d Create CNAME 2018-09-07 16:41:38 -05:00
Daniel J. Summers
6486763297 Delete CNAME 2018-09-07 16:41:23 -05:00
Daniel J. Summers
e94e28880b Create CNAME 2018-09-07 16:39:43 -05:00
Daniel J. Summers
16c3a9fd44 Updated docs for 1.0! 2018-08-21 20:53:44 -05:00
Daniel J. Summers
473359c645 Sort journal by appearance time (#21) 2018-08-21 20:44:39 -05:00
Daniel J. Summers
334710065c
Upgrade to Vue CLI 3 / Webpack 4 (#22)
Fixes #19
2018-08-21 20:39:41 -05:00
Daniel J. Summers
ee9326d7a5 Updated docs for recurrence (#16) 2018-08-18 20:12:30 -05:00
Daniel J. Summers
2c34650ceb Completed recurrence work (#16)
Requests can now:
- be entered with recurrence
- be updated with recurrence
- manually skip recurrence period

Also did an app-wide clean-up to ensure that everything is done the same way in all places
2018-08-18 19:32:48 -05:00
Daniel J. Summers
9f1e258180 Added recurrence to new request add/edit page (#16)
still need to get the actual non-immediate recurrence stuff to work correctly
2018-08-18 13:46:03 -05:00
Daniel J. Summers
0c21e6c1c0 Unsnooze works; #20 is complete
also:
- wrapped up some other stylings
- snoozed requests still show in the journal; this logic will change with recurrence work, so that bug is deferred
2018-08-18 11:07:30 -05:00
Daniel J. Summers
a6144f67ec Converted notes modal (#20) 2018-08-18 09:13:38 -05:00
Daniel J. Summers
e351fe5b56 Active request page (#16)
Also:
- refactored snoozed and answered list pages to use a common list format
- reworked the URLs to make them more consistent
- eliminated current "full" API endpoint, and renamed existing "complete" endpoint to "full"
2018-08-17 22:12:14 -05:00
Daniel J. Summers
d3aff4a110 Add/Edit request works
No longer a modal (#20)
2018-08-17 20:59:57 -05:00
Daniel J. Summers
c0dd6b5dd6 A few more minor tweaks 2018-08-16 22:09:39 -05:00
Daniel J. Summers
5bba499251 -BootstrapVue -VueAwesome
- All non-modals no longer reference Bootstrap or Font Awesome (#20)
- Removed "full request" button from journal page (#16)
- Added role attributes in many places
2018-08-16 21:57:54 -05:00
Daniel J. Summers
96f2f2f7e0 Added recurrence SQL; updated API
API should support recurrence (#16); also updated for new F# match! statement
2018-08-14 21:01:21 -05:00
Daniel J. Summers
2bf3bc4865 Working toward hosting
Seeing different behavior when this is sitting behind nginx; working toward a solution
2018-08-07 08:17:56 -05:00
Daniel J. Summers
95175d2c57 Merge branch 'master' of https://github.com/bit-badger/myPrayerJournal 2018-08-06 21:30:45 -05:00
Daniel J. Summers
3f71d75a99 Restoring ignored file changes
Also deleted a file I missed
2018-08-06 21:30:11 -05:00
Daniel J. Summers
8becb8cea4
F# API (#18)
- API is now F# / Giraffe / EF Core
- Snoozed requests are complete #17
- Updated doc links in preparation for transfer to Bit Badger Solutions organization's repository
2018-08-06 21:21:28 -05:00
Daniel J. Summers
d1fd5f68e7 Added snooze icon to journal
#17
2018-06-18 21:05:04 -05:00
Daniel J. Summers
d0ea7cf3c6 Added "snoozedUntil" column to API
Also added a "snooze" route (working on #17 )
2018-06-18 20:25:00 -05:00
Daniel J. Summers
05990d537a Version bump 2018-06-14 18:31:51 -05:00
Daniel J. Summers
67cdd5a9b0 Update tooltip on date changed
Bound long date to computed property (addresses #15 )
2018-06-14 18:21:14 -05:00
91 changed files with 2522 additions and 10697 deletions

11
.gitignore vendored
View File

@ -252,10 +252,7 @@ paket-files/
.idea/
*.sln.iml
# Compiled files / application
src/api/build
src/public/index.html
src/public/static
src/config.json
/build
src/*.exe
# Ionide VSCode extension
.ionide
src/environment.txt

View File

@ -4,8 +4,13 @@
Journaling has a long history; it helps people remember what happened, and the act of writing helps people think about what happened and process it. A prayer journal is not a new concept; it helps you keep track of the requests for which you've prayed, you can use it to pray over things repeatedly, and you can write the result when the answer comes _(or it was "no")_.
myPrayerJournal was borne of out of a personal desire I (Daniel) had to have something that would help me with my prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
myPrayerJournal was borne of out of a personal desire [Daniel](https://github.com/danieljsummers) had to have something that would help him with his prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
## Futher Reading
## Further Reading
The documentation for the site is at <https://danieljsummers.github.io/myPrayerJournal/>.
The documentation for the site is at <https://bit-badger.github.io/myPrayerJournal/>.
---
_Thanks to [JetBrains](https://jb.gg/OpenSource) for licensing their awesome toolset to this project._
[<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main) logo" width="100" height="100">](https://jb.gg/OpenSource)

1
docs/CNAME Normal file
View File

@ -0,0 +1 @@
docs.prayerjournal.me

View File

@ -4,7 +4,7 @@
Journaling has a long history; it helps people remember what happened, and the act of writing helps people think about what happened and process it. A prayer journal is not a new concept; it helps you keep track of the requests for which you've prayed, you can use it to pray over things repeatedly, and you can write the result when the answer comes _(or it was "no")_.
myPrayerJournal was borne of out of a personal desire I (Daniel) had to have something that would help me with my prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
myPrayerJournal was borne of out of a personal desire [Daniel](https://github.com/danieljsummers) had to have something that would help him with his prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
## Finding the Site
@ -16,15 +16,19 @@ myPrayerJournal uses login services using Google or Microsoft accounts. The only
## Your Prayer Journal
Your current requests will be presented in three columns (or two or one, depending on the size of your screen or device). Each request is in its own card, and the buttons at the top of each card apply to that request. The last line of each request also tells you how long it has been since anything has been done on that request. Any time you see something like "a few minutes ago," you can hover over that to see the actual date/time the action was taken.
Your current requests will be presented in columns (usually three, but it could be more or less, depending on the size of your screen or device). Each request is in its own card, and the buttons at the top of each card apply to that request. The last line of each request also tells you how long it has been since anything has been done on that request. Any time you see something like "a few minutes ago," you can hover over that to see the actual date/time the action was taken.
## Adding a Request
To add a request, click the "Add a New Request" button at the top of your journal. Then, enter the text of the request as you see fit; there is no right or wrong way, and you are the only person who will see the text you enter. When you save the request, it will go to the bottom of the list of requests.
## Setting Request Recurrence
When you add or update a request, you can choose whether requests go to the bottom of the journal once they have been marked "Prayed" or whether they will reappear after a delay. You can set recurrence in terms of hours, days, or weeks, but it cannot be longer than 365 days. If you decide you want a request to reappear sooner, you can skip the current delay; click the "Active" menu link, find the request in the list (likely near the bottom), and click the "Show Now" button.
## Praying for Requests
The first button for each request has a checkmark icon; clicking this button will mark the request as "Prayed" and move it to the bottom of the list. This allows you, if you're praying through your requests, to start at the top left (with the request that it's been the longest since you've prayed) and click the button as you pray; when the request goes to the bottom of the list, the next-least-recently-prayed request will take the top spot.
The first button for each request has a checkmark icon; clicking this button will mark the request as "Prayed" and move it to the bottom of the list (or off, if you've set a recurrence period for the request). This allows you, if you're praying through your requests, to start at the top left (with the request that it's been the longest since you've prayed) and click the button as you pray; when the request move below or away, the next-least-recently-prayed request will take the top spot.
## Editing Requests
@ -32,18 +36,20 @@ The second button for each request has a pencil icon. This allows you to edit th
## Adding Notes
The third button for each request has an icon that looks like a piece of paper with writing; this lets you record notes about the request. If there is something you want to record that doesn't change the text of the request, this is the place to do it. For example, you may be praying for a long-term health issue, and that person tells you that their status is the same; or, you may want to record something God said to you while you were praying for that request.
The third button for each request has an icon that looks like a speech bubble with lines on it; this lets you record notes about the request. If there is something you want to record that doesn't change the text of the request, this is the place to do it. For example, you may be praying for a long-term health issue, and that person tells you that their status is the same; or, you may want to record something God said to you while you were praying for that request.
## Snoozing Requests
There may be a time where a request does not need to appear. The fourth button, with the clock icon, allows you to snooze requests until the day you specify. Additionally, if you have any snoozed requests, a "Snoozed" menu item will appear next to the "Journal" one; this page allows you to see what requests are snoozed, and return them to your journal by canceling the snooze.
## Viewing a Request and Its History
myPrayerJournal tracks all of the actions related to a request; the fourth button, with the magnifying glass icon, will show you the entire history, including the text as it changed, and all the times "Prayed" was recorded.
myPrayerJournal tracks all of the actions related to a request; from the "Active" and "Answered" menu links (and "Snoozed", if it's showing), there is a "View Full Request" button. That page will show the current text of the request; how many times it has been marked as prayed; how long it has been an active request; and a log of all updates, prayers, and notes you have recorded. That log is listed from most recent to least recent; if you want to read it chronologically, just press the "End" key on your keyboard and read it from the bottom up.
## Answered Requests
Next to "Journal" on the top navigation is the word "Answered." This page lists all answered requests, from most recent to least recent, along with the text of the request at the time it was marked as answered. It will also show you when it was marked answered. The button at the bottom of each request, with the magnifying glass and the words "Show Full Request", link to a page that shows that request's complete history and notes, along with a few statistics about that request. The history and notes are listed from most recent to least recent; if you want to read it chronologically, just press the "End" key on your keyboard and read it from the bottom up.
The "Active" link will show all requests that have not yet been marked answered, including snoozed and recurring requests. If requests are snoozed, or in a recurrence period off the journal, there will be a button where you can return the request to the list (either "Cancel Snooze" or "Show Now"). The "Answered" link shows all requests that have been marked answered. The "Snoozed" link just shows snoozed requests.
## Final Notes
- myPrayerJournal is currently in public beta. If you encounter errors, please [file an issue on GitHub](https://github.com/danieljsummers/myPrayerJournal/issues) with as much detail as possible. You can also browse the list of issues to see what has been done and what is still left to do.
- If you encounter errors, please [file an issue on GitHub](https://github.com/bit-badger/myPrayerJournal/issues) with as much detail as possible. You can also provide suggestions, or browse the list of currently open issues.
- Prayer requests and their history are securely backed up nightly along with other Bit Badger Solutions data.
- Prayer changes things - most of all, the one doing the praying. I pray that this tool enables you to deepen and strengthen your prayer life.

3
publish.ps1 Executable file
View File

@ -0,0 +1,3 @@
#!/snap/bin/pwsh
Set-Location src/MyPrayerJournal
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false --nologo

17
src/Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
WORKDIR /mpj
COPY ./MyPrayerJournal/MyPrayerJournal.fsproj ./
RUN dotnet restore
COPY ./MyPrayerJournal ./
RUN dotnet publish -c Release -r linux-x64
RUN rm bin/Release/net8.0/linux-x64/publish/appsettings.*.json || true
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine as final
WORKDIR /app
RUN apk add --no-cache icu-libs
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
COPY --from=build /mpj/bin/Release/net8.0/linux-x64/publish/ ./
EXPOSE 80
CMD [ "dotnet", "/app/MyPrayerJournal.dll" ]

26
src/MyPrayerJournal.sln Normal file
View File

@ -0,0 +1,26 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MyPrayerJournal", "MyPrayerJournal\MyPrayerJournal.fsproj", "{6BD5A3C8-F859-42A0-ACD7-A5819385E828}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Release|Any CPU.Build.0 = Release|Any CPU
{72B57736-8721-4636-A309-49FA4222416E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72B57736-8721-4636-A309-49FA4222416E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72B57736-8721-4636-A309-49FA4222416E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72B57736-8721-4636-A309-49FA4222416E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

2
src/MyPrayerJournal/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
## Development settings
appsettings.Development.json

202
src/MyPrayerJournal/Data.fs Normal file
View File

@ -0,0 +1,202 @@
module MyPrayerJournal.Data
/// Table(!) used by myPrayerJournal
module Table =
/// Requests
[<Literal>]
let Request = "mpj.request"
/// JSON serialization customizations
[<RequireQualifiedAccess>]
module Json =
open System.Text.Json.Serialization
/// Convert a wrapped DU to/from its string representation
type WrappedJsonConverter<'T>(wrap : string -> 'T, unwrap : 'T -> string) =
inherit JsonConverter<'T>()
override _.Read(reader, _, _) =
wrap (reader.GetString())
override _.Write(writer, value, _) =
writer.WriteStringValue(unwrap value)
open System.Text.Json
open NodaTime.Serialization.SystemTextJson
/// JSON serializer options to support the target domain
let options =
let opts = JsonSerializerOptions()
[ WrappedJsonConverter(Recurrence.ofString, Recurrence.toString) :> JsonConverter
WrappedJsonConverter(RequestAction.ofString, RequestAction.toString)
WrappedJsonConverter(RequestId.ofString, RequestId.toString)
WrappedJsonConverter(UserId, UserId.toString)
JsonFSharpConverter() ]
|> List.iter opts.Converters.Add
let _ = opts.ConfigureForNodaTime NodaTime.DateTimeZoneProviders.Tzdb
opts.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase
opts.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingNull
opts
open BitBadger.Documents.Postgres
/// Connection
[<RequireQualifiedAccess>]
module Connection =
open BitBadger.Documents
open Microsoft.Extensions.Configuration
open Npgsql
open System.Text.Json
/// Ensure the database is ready to use
let private ensureDb () = backgroundTask {
do! Custom.nonQuery "CREATE SCHEMA IF NOT EXISTS mpj" []
do! Definition.ensureTable Table.Request
do! Definition.ensureDocumentIndex Table.Request Optimized
}
/// Set up the data environment
let setUp (cfg : IConfiguration) = backgroundTask {
let builder = NpgsqlDataSourceBuilder (cfg.GetConnectionString "mpj")
let _ = builder.UseNodaTime()
Configuration.useDataSource (builder.Build())
Configuration.useIdField "id"
Configuration.useSerializer
{ new IDocumentSerializer with
member _.Serialize<'T>(it : 'T) = JsonSerializer.Serialize(it, Json.options)
member _.Deserialize<'T>(it : string) = JsonSerializer.Deserialize<'T>(it, Json.options)
}
do! ensureDb ()
}
/// Data access functions for requests
[<RequireQualifiedAccess>]
module Request =
open NodaTime
/// Add a request
let add req =
insert<Request> Table.Request req
/// Does a request exist for the given request ID and user ID?
let existsById (reqId : RequestId) (userId : UserId) =
Exists.byContains Table.Request {| Id = reqId; UserId = userId |}
/// Retrieve a request by its ID and user ID
let tryById reqId userId = backgroundTask {
match! Find.byId<string, Request> Table.Request (RequestId.toString reqId) with
| Some req when req.UserId = userId -> return Some req
| _ -> return None
}
/// Update recurrence for a request
let updateRecurrence reqId userId (recurType : Recurrence) = backgroundTask {
let dbId = RequestId.toString reqId
match! existsById reqId userId with
| true -> do! Patch.byId Table.Request dbId {| Recurrence = recurType |}
| false -> invalidOp $"Request ID {dbId} not found"
}
/// Update the show-after time for a request
let updateShowAfter reqId userId (showAfter : Instant option) = backgroundTask {
let dbId = RequestId.toString reqId
match! existsById reqId userId with
| true -> do! Patch.byId Table.Request dbId {| ShowAfter = showAfter |}
| false -> invalidOp $"Request ID {dbId} not found"
}
/// Update the snoozed and show-after values for a request
let updateSnoozed reqId userId (until : Instant option) = backgroundTask {
let dbId = RequestId.toString reqId
match! existsById reqId userId with
| true -> do! Patch.byId Table.Request dbId {| SnoozedUntil = until; ShowAfter = until |}
| false -> invalidOp $"Request ID {dbId} not found"
}
/// Specific manipulation of history entries
[<RequireQualifiedAccess>]
module History =
/// Add a history entry
let add reqId userId hist = backgroundTask {
let dbId = RequestId.toString reqId
match! Request.tryById reqId userId with
| Some req ->
do! Patch.byId Table.Request dbId {| History = (hist :: req.History) |> List.sortByDescending (_.AsOf) |}
| None -> invalidOp $"Request ID {dbId} not found"
}
/// Data access functions for journal-style requests
[<RequireQualifiedAccess>]
module Journal =
/// Retrieve a user's answered requests
let answered (userId : UserId) = backgroundTask {
let! reqs =
Custom.list
$"""{Query.Find.byContains Table.Request} AND {Query.whereJsonPathMatches "@stat"}"""
[ jsonParam "@criteria" {| UserId = userId |}
"@stat", Sql.string """$.history[0].status ? (@ == "Answered")""" ]
fromData<Request>
return
reqs
|> Seq.ofList
|> Seq.map JournalRequest.ofRequestLite
|> Seq.filter (fun it -> it.LastStatus = Answered)
|> Seq.sortByDescending (_.AsOf)
|> List.ofSeq
}
/// Retrieve a user's current prayer journal (includes snoozed and non-immediate recurrence)
let forUser (userId : UserId) = backgroundTask {
let! reqs =
Custom.list
$"""{Query.Find.byContains Table.Request} AND {Query.whereJsonPathMatches "@stat"}"""
[ jsonParam "@criteria" {| UserId = userId |}
"@stat", Sql.string """$.history[0].status ? (@ <> "Answered")""" ]
fromData<Request>
return
reqs
|> Seq.ofList
|> Seq.map JournalRequest.ofRequestLite
|> Seq.filter (fun it -> it.LastStatus <> Answered)
|> Seq.sortBy (_.AsOf)
|> List.ofSeq
}
/// Does the user's journal have any snoozed requests?
let hasSnoozed userId now = backgroundTask {
let! jrnl = forUser userId
return jrnl |> List.exists (fun r -> defaultArg (r.SnoozedUntil |> Option.map (fun it -> it > now)) false)
}
let tryById reqId userId = backgroundTask {
let! req = Request.tryById reqId userId
return req |> Option.map JournalRequest.ofRequestLite
}
/// Specific manipulation of note entries
[<RequireQualifiedAccess>]
module Note =
/// Add a note
let add reqId userId note = backgroundTask {
let dbId = RequestId.toString reqId
match! Request.tryById reqId userId with
| Some req ->
do! Patch.byId Table.Request dbId {| Notes = (note :: req.Notes) |> List.sortByDescending (_.AsOf) |}
| None -> invalidOp $"Request ID {dbId} not found"
}
/// Retrieve notes for a request by the request ID
let byRequestId reqId userId = backgroundTask {
match! Request.tryById reqId userId with Some req -> return req.Notes | None -> return []
}

View File

@ -0,0 +1,76 @@
/// Date formatting helpers
// Many thanks to date-fns (https://date-fns.org) for this logic
module MyPrayerJournal.Dates
open NodaTime
type internal FormatDistanceToken =
| LessThanXMinutes
| XMinutes
| AboutXHours
| XHours
| XDays
| AboutXWeeks
| XWeeks
| AboutXMonths
| XMonths
| AboutXYears
| XYears
| OverXYears
| AlmostXYears
let internal locales =
let format = PrintfFormat<int -> string, unit, string, string>
Map.ofList [
"en-US", Map.ofList [
LessThanXMinutes, ("less than a minute", format "less than %i minutes")
XMinutes, ("a minute", format "%i minutes")
AboutXHours, ("about an hour", format "about %i hours")
XHours, ("an hour", format "%i hours")
XDays, ("a day", format "%i days")
AboutXWeeks, ("about a week", format "about %i weeks")
XWeeks, ("a week", format "%i weeks")
AboutXMonths, ("about a month", format "about %i months")
XMonths, ("a month", format "%i months")
AboutXYears, ("about a year", format "about %i years")
XYears, ("a year", format "%i years")
OverXYears, ("over a year", format "over %i years")
AlmostXYears, ("almost a year", format "almost %i years")
]
]
let aDay = 1_440.
let almost2Days = 2_520.
let aMonth = 43_200.
let twoMonths = 86_400.
open System
/// Format the distance between two instants in approximate English terms
let formatDistance (startOn : Instant) (endOn : Instant) =
let format (token, number) locale =
let labels = locales |> Map.find locale
match number with 1 -> fst labels[token] | _ -> sprintf (snd labels[token]) number
let round (it : float) = Math.Round it |> int
let diff = startOn - endOn
let minutes = Math.Abs diff.TotalMinutes
let formatToken =
let months = minutes / aMonth |> round
let years = months / 12
match true with
| _ when minutes < 1. -> LessThanXMinutes, 1
| _ when minutes < 45. -> XMinutes, round minutes
| _ when minutes < 90. -> AboutXHours, 1
| _ when minutes < aDay -> AboutXHours, round (minutes / 60.)
| _ when minutes < almost2Days -> XDays, 1
| _ when minutes < aMonth -> XDays, round (minutes / aDay)
| _ when minutes < twoMonths -> AboutXMonths, round (minutes / aMonth)
| _ when months < 12 -> XMonths, round (minutes / aMonth)
| _ when months % 12 < 3 -> AboutXYears, years
| _ when months % 12 < 9 -> OverXYears, years
| _ -> AlmostXYears, years + 1
format formatToken "en-US"
|> match startOn > endOn with true -> sprintf "%s ago" | false -> sprintf "in %s"

View File

@ -0,0 +1,279 @@
/// The data model for myPrayerJournal
[<AutoOpen>]
module MyPrayerJournal.Domain
open System
open Cuid
open NodaTime
/// An identifier for a request
type RequestId = RequestId of Cuid
/// Functions to manipulate request IDs
module RequestId =
/// The string representation of the request ID
let toString = function RequestId x -> Cuid.toString x
/// Create a request ID from a string representation
let ofString = Cuid >> RequestId
/// The identifier of a user (the "sub" part of the JWT)
type UserId = UserId of string
/// Functions to manipulate user IDs
module UserId =
/// The string representation of the user ID
let toString = function UserId x -> x
/// How frequently a request should reappear after it is marked "Prayed"
type Recurrence =
/// A request should reappear immediately at the bottom of the list
| Immediate
/// A request should reappear in the given number of hours
| Hours of int16
/// A request should reappear in the given number of days
| Days of int16
/// A request should reappear in the given number of weeks (7-day increments)
| Weeks of int16
/// Functions to manipulate recurrences
module Recurrence =
/// Create a string representation of a recurrence
let toString =
function
| Immediate -> "Immediate"
| Hours h -> $"{h} Hours"
| Days d -> $"{d} Days"
| Weeks w -> $"{w} Weeks"
/// Create a recurrence value from a string
let ofString =
function
| "Immediate" -> Immediate
| it when it.Contains " " ->
let parts = it.Split " "
let length = Convert.ToInt16 parts[0]
match parts[1] with
| "Hours" -> Hours length
| "Days" -> Days length
| "Weeks" -> Weeks length
| _ -> invalidOp $"{parts[1]} is not a valid recurrence"
| it -> invalidOp $"{it} is not a valid recurrence"
/// An hour's worth of seconds
let private oneHour = 3_600L
/// The duration of the recurrence (in milliseconds)
let duration =
function
| Immediate -> 0L
| Hours h -> int64 h * oneHour
| Days d -> int64 d * oneHour * 24L
| Weeks w -> int64 w * oneHour * 24L * 7L
/// The action taken on a request as part of a history entry
type RequestAction =
| Created
| Prayed
| Updated
| Answered
/// Functions to manipulate request actions
module RequestAction =
/// Create a string representation of an action
let toString =
function
| Created -> "Created"
| Prayed -> "Prayed"
| Updated -> "Updated"
| Answered -> "Answered"
/// Create a RequestAction from a string
let ofString =
function
| "Created" -> Created
| "Prayed" -> Prayed
| "Updated" -> Updated
| "Answered" -> Answered
| it -> invalidOp $"Bad request action {it}"
/// History is a record of action taken on a prayer request, including updates to its text
[<CLIMutable; NoComparison; NoEquality>]
type History =
{ /// The time when this history entry was made
AsOf : Instant
/// The status for this history entry
Status : RequestAction
/// The text of the update, if applicable
Text : string option
}
/// Functions to manipulate history entries
module History =
/// Determine if a history's status is `Created`
let isCreated hist = hist.Status = Created
/// Determine if a history's status is `Prayed`
let isPrayed hist = hist.Status = Prayed
/// Determine if a history's status is `Answered`
let isAnswered hist = hist.Status = Answered
/// Note is a note regarding a prayer request that does not result in an update to its text
[<CLIMutable; NoComparison; NoEquality>]
type Note =
{ /// The time when this note was made
AsOf : Instant
/// The text of the notes
Notes : string
}
/// Request is the identifying record for a prayer request
[<CLIMutable; NoComparison; NoEquality>]
type Request =
{ /// The ID of the request
Id : RequestId
/// The time this request was initially entered
EnteredOn : Instant
/// The ID of the user to whom this request belongs ("sub" from the JWT)
UserId : UserId
/// The time at which this request should reappear in the user's journal by manual user choice
SnoozedUntil : Instant option
/// The time at which this request should reappear in the user's journal by recurrence
ShowAfter : Instant option
/// The recurrence for this request
Recurrence : Recurrence
/// The history entries for this request
History : History list
/// The notes for this request
Notes : Note list
}
/// Functions to support requests
module Request =
/// An empty request
let empty =
{ Id = Cuid.generate () |> RequestId
EnteredOn = Instant.MinValue
UserId = UserId ""
SnoozedUntil = None
ShowAfter = None
Recurrence = Immediate
History = []
Notes = []
}
/// JournalRequest is the form of a prayer request returned for the request journal display. It also contains
/// properties that may be filled for history and notes.
[<NoComparison; NoEquality>]
type JournalRequest =
{ /// The ID of the request (just the CUID part)
RequestId : RequestId
/// The ID of the user to whom the request belongs
UserId : UserId
/// The current text of the request
Text : string
/// The last time action was taken on the request
AsOf : Instant
/// The last time a request was marked as prayed
LastPrayed : Instant option
/// The last status for the request
LastStatus : RequestAction
/// The time that this request should reappear in the user's journal
SnoozedUntil : Instant option
/// The time after which this request should reappear in the user's journal by configured recurrence
ShowAfter : Instant option
/// The recurrence for this request
Recurrence : Recurrence
/// History entries for the request
History : History list
/// Note entries for the request
Notes : Note list
}
/// Functions to manipulate journal requests
module JournalRequest =
/// Convert a request to the form used for the journal (precomputed values, no notes or history)
let ofRequestLite (req : Request) =
let history = Seq.ofList req.History
let lastHistory = Seq.tryHead history
// Requests are sorted by the "as of" field in this record; for sorting to work properly, we will put the
// largest of the last prayed date, the "snoozed until". or the "show after" date; if none of those are filled,
// we will use the last activity date. This will mean that:
// - Immediately shown requests will be at the top of the list, in order from least recently prayed to most.
// - Non-immediate requests will enter the list as if they were marked as prayed at that time; this will put
// them at the bottom of the list.
// - Snoozed requests will reappear at the bottom of the list when they return.
// - New requests will go to the bottom of the list, but will rise as others are marked as prayed.
let lastActivity = lastHistory |> Option.map (_.AsOf) |> Option.defaultValue Instant.MinValue
let showAfter = defaultArg req.ShowAfter Instant.MinValue
let snoozedUntil = defaultArg req.SnoozedUntil Instant.MinValue
let lastPrayed =
history
|> Seq.filter History.isPrayed
|> Seq.tryHead
|> Option.map (_.AsOf)
|> Option.defaultValue Instant.MinValue
let asOf = List.max [ lastPrayed; showAfter; snoozedUntil ]
{ RequestId = req.Id
UserId = req.UserId
Text = history
|> Seq.filter (fun it -> Option.isSome it.Text)
|> Seq.tryHead
|> Option.map (fun h -> Option.get h.Text)
|> Option.defaultValue ""
AsOf = if asOf > Instant.MinValue then asOf else lastActivity
LastPrayed = if lastPrayed = Instant.MinValue then None else Some lastPrayed
LastStatus = match lastHistory with Some h -> h.Status | None -> Created
SnoozedUntil = req.SnoozedUntil
ShowAfter = req.ShowAfter
Recurrence = req.Recurrence
History = []
Notes = []
}
/// Same as `ofRequestLite`, but with notes and history
let ofRequestFull req =
{ ofRequestLite req with
History = req.History
Notes = req.Notes
}

View File

@ -0,0 +1,570 @@
/// HTTP handlers for the myPrayerJournal API
[<RequireQualifiedAccess>]
module MyPrayerJournal.Handlers
open Giraffe
open Giraffe.Htmx
open System
/// Helper function to be able to split out log on
[<AutoOpen>]
module private LogOnHelpers =
open Microsoft.AspNetCore.Authentication
/// Log on, optionally specifying a redirected URL once authentication is complete
let logOn url : HttpHandler = fun next ctx -> task {
match url with
| Some it ->
do! ctx.ChallengeAsync("Auth0", AuthenticationProperties(RedirectUri = it))
return! next ctx
| None -> return! challenge "Auth0" next ctx
}
/// Handlers for error conditions
module Error =
open Microsoft.Extensions.Logging
/// Handle errors
let error (ex : Exception) (log : ILogger) =
log.LogError (EventId (), ex, "An unhandled exception has occurred while executing the request.")
clearResponse
>=> setStatusCode 500
>=> setHttpHeader "X-Toast" $"error|||{ex.GetType().Name}: {ex.Message}"
>=> text ex.Message
/// Handle unauthorized actions, redirecting to log on for GETs, otherwise returning a 401 Not Authorized response
let notAuthorized : HttpHandler = fun next ctx ->
(if ctx.Request.Method = "GET" then logOn None next else setStatusCode 401 earlyReturn) ctx
/// Handle 404s from the API, sending known URL paths to the Vue app so that they can be handled there
let notFound : HttpHandler =
setStatusCode 404 >=> text "Not found"
open System.Security.Claims
open Microsoft.AspNetCore.Http
open NodaTime
/// Extensions on the HTTP context
type HttpContext with
/// The "sub" for the current user (None if no user is authenticated)
member this.CurrentUser =
this.User
|> Option.ofObj
|> Option.map (fun user -> user.Claims |> Seq.tryFind (fun u -> u.Type = ClaimTypes.NameIdentifier))
|> Option.flatten
|> Option.map (_.Value)
/// The current user's ID
// NOTE: this may raise if you don't run the request through the requireUser handler first
member this.UserId = UserId this.CurrentUser.Value
/// The system clock
member this.Clock = this.GetService<IClock>()
/// Get the current instant from the system clock
member this.Now = this.Clock.GetCurrentInstant
/// Get the time zone from the X-Time-Zone header (default UTC)
member this.TimeZone =
match this.TryGetRequestHeader "X-Time-Zone" with
| Some tz ->
match this.GetService<IDateTimeZoneProvider>().GetZoneOrNull tz with
| null -> DateTimeZone.Utc
| zone -> zone
| None -> DateTimeZone.Utc
open MyPrayerJournal.Data
/// Handler helpers
[<AutoOpen>]
module private Helpers =
open Microsoft.Extensions.Logging
open Microsoft.Net.Http.Headers
/// Require a user to be logged on
let requireUser : HttpHandler =
requiresAuthentication Error.notAuthorized
/// Debug logger
let debug (ctx : HttpContext) message =
let fac = ctx.GetService<ILoggerFactory>()
let log = fac.CreateLogger "Debug"
log.LogInformation message
/// Return a 201 CREATED response
let created =
setStatusCode 201
/// Return a 201 CREATED response with the location header set for the created resource
let createdAt url : HttpHandler = fun next ctx ->
Successful.CREATED
($"{ctx.Request.Scheme}://{ctx.Request.Host.Value}{url}" |> setHttpHeader HeaderNames.Location) next ctx
/// Return a 303 SEE OTHER response (forces a GET on the redirected URL)
let seeOther (url : string) =
noResponseCaching >=> setStatusCode 303 >=> setHttpHeader "Location" url
/// Render a component result
let renderComponent nodes : HttpHandler =
noResponseCaching
>=> fun _ ctx -> backgroundTask {
return! ctx.WriteHtmlStringAsync(ViewEngine.RenderView.AsString.htmlNodes nodes)
}
open Views.Layout
open System.Threading.Tasks
/// Create a page rendering context
let pageContext (ctx : HttpContext) pageTitle content = backgroundTask {
let! hasSnoozed =
match ctx.CurrentUser with
| Some _ -> Journal.hasSnoozed ctx.UserId (ctx.Now())
| None -> Task.FromResult false
return
{ IsAuthenticated = Option.isSome ctx.CurrentUser
HasSnoozed = hasSnoozed
CurrentUrl = ctx.Request.Path.Value
PageTitle = pageTitle
Content = content
}
}
/// Composable handler to write a view to the output
let writeView view : HttpHandler = fun _ ctx -> backgroundTask {
return! ctx.WriteHtmlViewAsync view
}
/// Hold messages across redirects
module Messages =
/// The messages being held
let mutable private messages : Map<UserId, string * string> = Map.empty
/// Locked update to prevent updates by multiple threads
let private upd8 = obj ()
/// Push a new message into the list
let push (ctx : HttpContext) message url = lock upd8 (fun () ->
messages <- messages.Add(ctx.UserId, (message, url)))
/// Add a success message header to the response
let pushSuccess ctx message url =
push ctx $"success|||%s{message}" url
/// Pop the messages for the given user
let pop userId = lock upd8 (fun () ->
let msg = messages.TryFind userId
msg |> Option.iter (fun _ -> messages <- messages.Remove userId)
msg)
/// Send a partial result if this is not a full page load (does not append no-cache headers)
let partialStatic (pageTitle : string) content : HttpHandler = fun next ctx -> task {
let isPartial = ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh
let! pageCtx = pageContext ctx pageTitle content
let view = (match isPartial with true -> partial | false -> view) pageCtx
return!
(next, ctx)
||> match ctx.CurrentUser with
| Some _ ->
match Messages.pop ctx.UserId with
| Some (msg, url) -> setHttpHeader "X-Toast" msg >=> withHxPushUrl url >=> writeView view
| None -> writeView view
| None -> writeView view
}
/// Send an explicitly non-cached result, rendering as a partial if this is not a full page load
let partial pageTitle content =
noResponseCaching >=> partialStatic pageTitle content
/// Add a success message header to the response
let withSuccessMessage : string -> HttpHandler =
sprintf "success|||%s" >> setHttpHeader "X-Toast"
/// Hide a modal window when the response is sent
let hideModal (name : string) : HttpHandler =
setHttpHeader "X-Hide-Modal" name
/// Strongly-typed models for post requests
module Models =
/// An additional note
[<CLIMutable; NoComparison; NoEquality>]
type NoteEntry =
{ /// The notes being added
notes : string
}
/// A prayer request
[<CLIMutable; NoComparison; NoEquality>]
type Request =
{ /// The ID of the request
requestId : string
/// Where to redirect after saving
returnTo : string
/// The text of the request
requestText : string
/// The additional status to record
status : string option
/// The recurrence type
recurType : string
/// The recurrence count
recurCount : int16 option
/// The recurrence interval
recurInterval : string option
}
/// The date until which a request should not appear in the journal
[<CLIMutable; NoComparison; NoEquality>]
type SnoozeUntil =
{ /// The date (YYYY-MM-DD) at which the request should reappear
until : string
}
open NodaTime.Text
/// Handlers for less-than-full-page HTML requests
module Components =
// GET /components/journal-items
let journalItems : HttpHandler = requireUser >=> fun next ctx -> task {
let now = ctx.Now ()
let shouldBeShown (req : JournalRequest) =
match req.SnoozedUntil, req.ShowAfter with
| None, None -> true
| Some snooze, Some hide when snooze < now && hide < now -> true
| Some snooze, _ when snooze < now -> true
| _, Some hide when hide < now -> true
| _, _ -> false
let! journal = Journal.forUser ctx.UserId
let shown = journal |> List.filter shouldBeShown
return! renderComponent [ Views.Journal.journalItems now ctx.TimeZone shown ] next ctx
}
// GET /components/request-item/[req-id]
let requestItem reqId : HttpHandler = requireUser >=> fun next ctx -> task {
match! Journal.tryById (RequestId.ofString reqId) ctx.UserId with
| Some req -> return! renderComponent [ Views.Request.reqListItem (ctx.Now()) ctx.TimeZone req ] next ctx
| None -> return! Error.notFound next ctx
}
// GET /components/request/[req-id]/add-notes
let addNotes requestId : HttpHandler =
requireUser >=> renderComponent (Views.Journal.notesEdit (RequestId.ofString requestId))
// GET /components/request/[req-id]/notes
let notes requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let! notes = Note.byRequestId (RequestId.ofString requestId) ctx.UserId
return! renderComponent (Views.Request.notes (ctx.Now()) ctx.TimeZone notes) next ctx
}
// GET /components/request/[req-id]/snooze
let snooze requestId : HttpHandler =
requireUser >=> renderComponent [ RequestId.ofString requestId |> Views.Journal.snooze ]
/// / URL and documentation
module Home =
// GET /
let home : HttpHandler =
partialStatic "Welcome!" Views.Layout.home
// GET /docs
let docs : HttpHandler =
partialStatic "Documentation" Views.Docs.index
/// /journal URL
module Journal =
// GET /journal
let journal : HttpHandler = requireUser >=> fun next ctx -> task {
let usr =
ctx.User.Claims
|> Seq.tryFind (fun c -> c.Type = ClaimTypes.GivenName)
|> Option.map (_.Value)
|> Option.defaultValue "Your"
let title = usr |> match usr with "Your" -> sprintf "%s" | _ -> sprintf "%s&rsquo;s"
return! partial $"{title} Prayer Journal" (Views.Journal.journal usr) next ctx
}
/// /legal URLs
module Legal =
// GET /legal/privacy-policy
let privacyPolicy : HttpHandler =
partialStatic "Privacy Policy" Views.Legal.privacyPolicy
// GET /legal/terms-of-service
let termsOfService : HttpHandler =
partialStatic "Terms of Service" Views.Legal.termsOfService
/// /api/request and /request(s) URLs
module Request =
open Cuid
// GET /request/[req-id]/edit
let edit requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let returnTo =
match ctx.Request.Headers.Referer[0] with
| it when it.EndsWith "/active" -> "active"
| it when it.EndsWith "/snoozed" -> "snoozed"
| _ -> "journal"
match requestId with
| "new" ->
return! partial "Add Prayer Request"
(Views.Request.edit (JournalRequest.ofRequestLite Request.empty) returnTo true) next ctx
| _ ->
match! Journal.tryById (RequestId.ofString requestId) ctx.UserId with
| Some req ->
debug ctx "Found - sending view"
return! partial "Edit Prayer Request" (Views.Request.edit req returnTo false) next ctx
| None ->
debug ctx "Not found - uh oh..."
return! Error.notFound next ctx
}
// PATCH /request/[req-id]/prayed
let prayed requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let userId = ctx.UserId
let reqId = RequestId.ofString requestId
match! Journal.tryById reqId userId with
| Some req ->
let now = ctx.Now ()
do! History.add reqId userId { AsOf = now; Status = Prayed; Text = None }
let nextShow =
match Recurrence.duration req.Recurrence with
| 0L -> None
| duration -> Some <| now.Plus (Duration.FromSeconds duration)
do! Request.updateShowAfter reqId userId nextShow
return! (withSuccessMessage "Request marked as prayed" >=> Components.journalItems) next ctx
| None -> return! Error.notFound next ctx
}
// POST /request/[req-id]/note
let addNote requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let userId = ctx.UserId
let reqId = RequestId.ofString requestId
match! Request.existsById reqId userId with
| true ->
let! notes = ctx.BindFormAsync<Models.NoteEntry>()
do! Note.add reqId userId { AsOf = ctx.Now(); Notes = notes.notes }
return! (withSuccessMessage "Added Notes" >=> hideModal "notes" >=> created) next ctx
| false -> return! Error.notFound next ctx
}
// GET /requests/active
let active : HttpHandler = requireUser >=> fun next ctx -> task {
let! reqs = Journal.forUser ctx.UserId
return! partial "Active Requests" (Views.Request.active (ctx.Now()) ctx.TimeZone reqs) next ctx
}
// GET /requests/snoozed
let snoozed : HttpHandler = requireUser >=> fun next ctx -> task {
let! reqs = Journal.forUser ctx.UserId
let now = ctx.Now()
let snoozed = reqs
|> List.filter (fun it -> defaultArg (it.SnoozedUntil |> Option.map (fun it -> it > now)) false)
return! partial "Snoozed Requests" (Views.Request.snoozed now ctx.TimeZone snoozed) next ctx
}
// GET /requests/answered
let answered : HttpHandler = requireUser >=> fun next ctx -> task {
let! reqs = Journal.answered ctx.UserId
return! partial "Answered Requests" (Views.Request.answered (ctx.Now()) ctx.TimeZone reqs) next ctx
}
// GET /request/[req-id]/full
let getFull requestId : HttpHandler = requireUser >=> fun next ctx -> task {
match! Request.tryById (RequestId.ofString requestId) ctx.UserId with
| Some req -> return! partial "Prayer Request" (Views.Request.full ctx.Clock ctx.TimeZone req) next ctx
| None -> return! Error.notFound next ctx
}
// PATCH /request/[req-id]/show
let show requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let userId = ctx.UserId
let reqId = RequestId.ofString requestId
match! Request.existsById reqId userId with
| true ->
do! Request.updateShowAfter reqId userId None
return! (withSuccessMessage "Request now shown" >=> Components.requestItem requestId) next ctx
| false -> return! Error.notFound next ctx
}
// PATCH /request/[req-id]/snooze
let snooze requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let userId = ctx.UserId
let reqId = RequestId.ofString requestId
match! Request.existsById reqId userId with
| true ->
let! until = ctx.BindFormAsync<Models.SnoozeUntil>()
let date =
LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(until.until).Value
.AtStartOfDayInZone(DateTimeZone.Utc)
.ToInstant()
do! Request.updateSnoozed reqId userId (Some date)
return!
(withSuccessMessage $"Request snoozed until {until.until}"
>=> hideModal "snooze"
>=> Components.journalItems) next ctx
| false -> return! Error.notFound next ctx
}
// PATCH /request/[req-id]/cancel-snooze
let cancelSnooze requestId : HttpHandler = requireUser >=> fun next ctx -> task {
let userId = ctx.UserId
let reqId = RequestId.ofString requestId
match! Request.existsById reqId userId with
| true ->
do! Request.updateSnoozed reqId userId None
return! (withSuccessMessage "Request unsnoozed" >=> Components.requestItem requestId) next ctx
| false -> return! Error.notFound next ctx
}
/// Derive a recurrence from its representation in the form
let private parseRecurrence (form : Models.Request) =
match form.recurInterval with Some x -> $"{defaultArg form.recurCount 0s} {x}" | None -> "Immediate"
|> Recurrence.ofString
// POST /request
let add : HttpHandler = requireUser >=> fun next ctx -> task {
let! form = ctx.BindModelAsync<Models.Request>()
let userId = ctx.UserId
let now = ctx.Now()
let req =
{ Request.empty with
Id = Cuid.generate () |> RequestId
UserId = userId
EnteredOn = now
ShowAfter = None
Recurrence = parseRecurrence form
History = [
{ AsOf = now
Status = Created
Text = Some form.requestText
}
]
}
do! Request.add req
Messages.pushSuccess ctx "Added prayer request" "/journal"
return! seeOther "/journal" next ctx
}
// PATCH /request
let update : HttpHandler = requireUser >=> fun next ctx -> task {
let! form = ctx.BindModelAsync<Models.Request>()
let userId = ctx.UserId
// TODO: update the instance and save rather than all these little updates
match! Journal.tryById (RequestId.ofString form.requestId) userId with
| Some req ->
// update recurrence if changed
let recur = parseRecurrence form
match recur = req.Recurrence with
| true -> ()
| false ->
do! Request.updateRecurrence req.RequestId userId recur
match recur with
| Immediate -> do! Request.updateShowAfter req.RequestId userId None
| _ -> ()
// append history
let upd8Text = form.requestText.Trim()
let text = if upd8Text = req.Text then None else Some upd8Text
do! History.add req.RequestId userId
{ AsOf = ctx.Now(); Status = (Option.get >> RequestAction.ofString) form.status; Text = text }
let nextUrl =
match form.returnTo with
| "active" -> "/requests/active"
| "snoozed" -> "/requests/snoozed"
| _ (* "journal" *) -> "/journal"
Messages.pushSuccess ctx "Prayer request updated successfully" nextUrl
return! seeOther nextUrl next ctx
| None -> return! Error.notFound next ctx
}
/// Handlers for /user URLs
module User =
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies
// GET /user/log-on
let logOn : HttpHandler =
logOn (Some "/journal")
// GET /user/log-off
let logOff : HttpHandler = requireUser >=> fun next ctx -> task {
do! ctx.SignOutAsync("Auth0", AuthenticationProperties (RedirectUri = "/"))
do! ctx.SignOutAsync CookieAuthenticationDefaults.AuthenticationScheme
return! next ctx
}
open Giraffe.EndpointRouting
/// The routes for myPrayerJournal
let routes = [
GET_HEAD [ route "/" Home.home ]
subRoute "/components/" [
GET_HEAD [
route "journal-items" Components.journalItems
routef "request/%s/add-notes" Components.addNotes
routef "request/%s/item" Components.requestItem
routef "request/%s/notes" Components.notes
routef "request/%s/snooze" Components.snooze
]
]
GET_HEAD [ route "/docs" Home.docs ]
GET_HEAD [ route "/journal" Journal.journal ]
subRoute "/legal/" [
GET_HEAD [
route "privacy-policy" Legal.privacyPolicy
route "terms-of-service" Legal.termsOfService
]
]
subRoute "/request" [
GET_HEAD [
routef "/%s/edit" Request.edit
routef "/%s/full" Request.getFull
route "s/active" Request.active
route "s/answered" Request.answered
route "s/snoozed" Request.snoozed
]
PATCH [
route "" Request.update
routef "/%s/cancel-snooze" Request.cancelSnooze
routef "/%s/prayed" Request.prayed
routef "/%s/show" Request.show
routef "/%s/snooze" Request.snooze
]
POST [
route "" Request.add
routef "/%s/note" Request.addNote
]
]
subRoute "/user/" [
GET_HEAD [
route "log-off" User.logOff
route "log-on" User.logOn
]
]
]

View File

@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Version>3.4</Version>
<DebugType>embedded</DebugType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<PublishSingleFile>false</PublishSingleFile>
<SelfContained>false</SelfContained>
</PropertyGroup>
<ItemGroup>
<Compile Include="Domain.fs" />
<Compile Include="Data.fs" />
<Compile Include="Dates.fs" />
<Compile Include="Views/Helpers.fs" />
<Compile Include="Views/Journal.fs" />
<Compile Include="Views/Layout.fs" />
<Compile Include="Views/Legal.fs" />
<Compile Include="Views/Request.fs" />
<Compile Include="Views\Docs.fs" />
<Compile Include="Handlers.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BitBadger.Documents.Postgres" Version="3.1.0" />
<PackageReference Include="FSharp.SystemTextJson" Version="1.3.13" />
<PackageReference Include="FunctionalCuid" Version="1.0.0" />
<PackageReference Include="Giraffe" Version="6.4.0" />
<PackageReference Include="Giraffe.Htmx" Version="1.9.12" />
<PackageReference Include="Giraffe.ViewEngine.Htmx" Version="1.9.12" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="8.0.6" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.2.0" />
<PackageReference Include="Npgsql.NodaTime" Version="8.0.3" />
<PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,111 @@
module MyPrayerJournal.Api
open Microsoft.AspNetCore.Http
let sameSite (opts : CookieOptions) =
match opts.SameSite, opts.Secure with
| SameSiteMode.None, false -> opts.SameSite <- SameSiteMode.Unspecified
| _, _ -> ()
open Giraffe
open Giraffe.EndpointRouting
open Microsoft.AspNetCore.Authentication.Cookies
open Microsoft.AspNetCore.Authentication.OpenIdConnect
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.HttpOverrides
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Microsoft.Extensions.Logging
open Microsoft.IdentityModel.Protocols.OpenIdConnect
open MyPrayerJournal.Data
open NodaTime
open System
open System.Text.Json
open System.Threading.Tasks
[<EntryPoint>]
let main args =
//use host = Configure.webHost [| "wwwroot" |] (Directory.GetCurrentDirectory ())
//host.Run ()
let builder = WebApplication.CreateBuilder args
let _ = builder.Configuration.AddEnvironmentVariables "MPJ_"
let svc = builder.Services
let cfg = svc.BuildServiceProvider().GetRequiredService<IConfiguration>()
let _ = svc.AddRouting()
let _ = svc.AddGiraffe()
let _ = svc.AddSingleton<IClock> SystemClock.Instance
let _ = svc.AddSingleton<IDateTimeZoneProvider> DateTimeZoneProviders.Tzdb
let _ = svc.Configure<ForwardedHeadersOptions>(fun (opts : ForwardedHeadersOptions) ->
opts.ForwardedHeaders <- ForwardedHeaders.XForwardedFor ||| ForwardedHeaders.XForwardedProto)
let _ =
svc.Configure<CookiePolicyOptions>(fun (opts : CookiePolicyOptions) ->
opts.MinimumSameSitePolicy <- SameSiteMode.Unspecified
opts.OnAppendCookie <- fun ctx -> sameSite ctx.CookieOptions
opts.OnDeleteCookie <- fun ctx -> sameSite ctx.CookieOptions)
let _ =
svc.AddAuthentication(fun opts ->
opts.DefaultAuthenticateScheme <- CookieAuthenticationDefaults.AuthenticationScheme
opts.DefaultSignInScheme <- CookieAuthenticationDefaults.AuthenticationScheme
opts.DefaultChallengeScheme <- CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddOpenIdConnect("Auth0", fun opts ->
// Configure OIDC with Auth0 options from configuration
let auth0 = cfg.GetSection "Auth0"
opts.Authority <- $"""https://{auth0["Domain"]}/"""
opts.ClientId <- auth0["Id"]
opts.ClientSecret <- auth0["Secret"]
opts.ResponseType <- OpenIdConnectResponseType.Code
opts.Scope.Clear()
opts.Scope.Add "openid"
opts.Scope.Add "profile"
opts.CallbackPath <- PathString "/user/log-on/success"
opts.ClaimsIssuer <- "Auth0"
opts.SaveTokens <- true
opts.Events <- OpenIdConnectEvents()
opts.Events.OnRedirectToIdentityProviderForSignOut <- fun ctx ->
let returnTo =
match ctx.Properties.RedirectUri with
| it when isNull it || it = "" -> ""
| redirUri ->
let finalRedirUri =
match redirUri.StartsWith "/" with
| true ->
// transform to absolute
let request = ctx.Request
$"{request.Scheme}://{request.Host.Value}{request.PathBase.Value}{redirUri}"
| false -> redirUri
Uri.EscapeDataString $"&returnTo={finalRedirUri}"
ctx.Response.Redirect $"""https://{auth0["Domain"]}/v2/logout?client_id={auth0["Id"]}{returnTo}"""
ctx.HandleResponse()
Task.CompletedTask
opts.Events.OnRedirectToIdentityProvider <- fun ctx ->
let uri = UriBuilder ctx.ProtocolMessage.RedirectUri
uri.Scheme <- auth0["Scheme"]
uri.Port <- int auth0["Port"]
ctx.ProtocolMessage.RedirectUri <- string uri
Task.CompletedTask)
let _ = svc.AddSingleton<JsonSerializerOptions> Json.options
let _ = svc.AddSingleton<Json.ISerializer>(SystemTextJson.Serializer Json.options)
let _ = Connection.setUp cfg |> Async.AwaitTask |> Async.RunSynchronously
if builder.Environment.IsDevelopment() then builder.Logging.AddFilter(fun l -> l > LogLevel.Information) |> ignore
let _ = builder.Logging.AddConsole().AddDebug() |> ignore
use app = builder.Build()
let _ = app.UseStaticFiles()
let _ = app.UseCookiePolicy()
let _ = app.UseRouting()
let _ = app.UseAuthentication()
let _ = app.UseGiraffeErrorHandler Handlers.Error.error
let _ = app.UseEndpoints(fun e -> e.MapGiraffeEndpoints Handlers.routes)
app.Run()
0

View File

@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61905",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MyPrayerJournal.Api": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,184 @@
module MyPrayerJournal.Views.Docs
open Giraffe.ViewEngine
/// The "About myPrayerJournal" section
let private about = [
h3 [ _class "mb-3 mt-4" ] [ rawText "About myPrayerJournal" ]
p [] [
rawText "Journaling has a long history; it helps people remember what happened, and the act of writing helps "
rawText "people think about what happened and process it. A prayer journal is not a new concept; it helps you "
rawText "keep track of the requests for which you've prayed, you can use it to pray over things repeatedly, "
rawText "and you can write the result when the answer comes "; em [] [ rawText "(or it was &ldquo;no&rdquo;)" ]
rawText "."
]
p [] [
rawText "myPrayerJournal was borne of out of a personal desire "
a [ _href "https://daniel.summershome.org"; _target "_blank"; _rel "noopener" ] [ rawText "Daniel" ]
rawText " had to have something that would help him with his prayer life. When it&rsquo;s time to pray, "
rawText "it&rsquo;s not really time to use an app, so the design goal here is to keep it simple and "
rawText "unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not "
rawText "remembering whether you&rsquo;ve prayed for a request, or running out of room to write another update "
rawText "on one."
]
]
/// The "Signing Up" section
let private signUp = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Signing Up" ]
p [] [
rawText "myPrayerJournal uses login services using Google or Microsoft accounts. The only information the "
rawText "application stores in its database is your user Id token it receives from these services, so there "
rawText "are no permissions you should have to accept from these provider other than establishing that you can "
rawText "log on with that account. Because of this, you&rsquo;ll want to pick the same one each time; the "
rawText "tokens between the two accounts are different, even if you use the same e-mail address to log on to "
rawText "both."
]
]
/// The "Your Prayer Journal" section
let private yourJournal = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Your Prayer Journal" ]
p [] [
rawText "Your current requests will be presented in columns (usually three, but it could be more or less, "
rawText "depending on the size of your screen or device). Each request is in its own card, and the buttons at "
rawText "the top of each card apply to that request. The last line of each request also tells you how long it "
rawText "has been since anything has been done on that request. Any time you see something like &ldquo;a few "
rawText "minutes ago,&rdquo; you can hover over that to see the actual date/time the action was taken."
]
]
/// The "Adding a Request" section
let private addRequest = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Adding a Request" ]
p [] [
rawText "To add a request, click the &ldquo;Add a New Request&rdquo; button at the top of your journal. Then, "
rawText "enter the text of the request as you see fit; there is no right or wrong way, and you are the only "
rawText "person who will see the text you enter. When you save the request, it will go to the bottom of the "
rawText "list of requests."
]
]
/// The "Setting Request Recurrence" section
let private setRecurrence = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Setting Request Recurrence" ]
p [] [
rawText "When you add or update a request, you can choose whether requests go to the bottom of the journal "
rawText "once they have been marked &ldquo;Prayed&rdquo; or whether they will reappear after a delay. You can "
rawText "set recurrence in terms of hours, days, or weeks, but it cannot be longer than 365 days. If you "
rawText "decide you want a request to reappear sooner, you can skip the current delay; click the "
rawText "&ldquo;Active&rdquo; menu link, find the request in the list (likely near the bottom), and click the "
rawText "&ldquo;Show Now&rdquo; button."
]
]
/// The "Praying for Requests" section
let private praying = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Praying for Requests" ]
p [] [
rawText "The first button for each request has a checkmark icon; clicking this button will mark the request as "
rawText "&ldquo;Prayed&rdquo; and move it to the bottom of the list (or off, if you&rsquo;ve set a recurrence "
rawText "period for the request). This allows you, if you&rsquo;re praying through your requests, to start at "
rawText "the top left (with the request that it&rsquo;s been the longest since you&rsquo;ve prayed) and click "
rawText "the button as you pray; when the request move below or away, the next-least-recently-prayed request "
rawText "will take the top spot."
]
]
/// The "Editing Requests" section
let private editing = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Editing Requests" ]
p [] [
rawText "The second button for each request has a pencil icon. This allows you to edit the text of the "
rawText "request, pretty much the same way you entered it; it starts with the current text, and you can add to "
rawText "it, modify it, or completely replace it. By default, updates will go in with an &ldquo;Updated&rdquo; "
rawText "status; you have the option to also mark this update as &ldquo;Prayed&rdquo; or "
rawText "&ldquo;Answered&rdquo;. Answered requests will drop off the journal list."
]
]
/// The "Adding Notes" section
let private addNotes = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Adding Notes" ]
p [] [
rawText "The third button for each request has an icon that looks like a speech bubble with lines on it; this "
rawText "lets you record notes about the request. If there is something you want to record that doesn&rsquo;t "
rawText "change the text of the request, this is the place to do it. For example, you may be praying for a "
rawText "long-term health issue, and that person tells you that their status is the same; or, you may want to "
rawText "record something God said to you while you were praying for that request."
]
]
/// The "Snoozing Requests" section
let private snoozing = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Snoozing Requests" ]
p [] [
rawText "There may be a time where a request does not need to appear. The fourth button, with the clock icon, "
rawText "allows you to snooze requests until the day you specify. Additionally, if you have any snoozed "
rawText "requests, a &ldquo;Snoozed&rdquo; menu item will appear next to the &ldquo;Journal&rdquo; one; this "
rawText "page allows you to see what requests are snoozed, and return them to your journal by canceling the "
rawText "snooze."
]
]
/// The "Viewing a Request and Its History" section
let private viewing = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Viewing a Request and Its History" ]
p [] [
rawText "myPrayerJournal tracks all of the actions related to a request; from the &ldquo;Active&rdquo; and "
rawText "&ldquo;Answered&rdquo; menu links (and &ldquo;Snoozed&rdquo;, if it&rsquo;s showing), there is a "
rawText "&ldquo;View Full Request&rdquo; button. That page will show the current text of the request; how many "
rawText "times it has been marked as prayed; how long it has been an active request; and a log of all updates, "
rawText "prayers, and notes you have recorded. That log is listed from most recent to least recent; if you "
rawText "want to read it chronologically, press the &ldquo;End&rdquo; key on your keyboard and read it from "
rawText "the bottom up."
]
p [] [
rawText "The &ldquo;Active&rdquo; link will show all requests that have not yet been marked answered, "
rawText "including snoozed and recurring requests. If requests are snoozed, or in a recurrence period off the "
rawText "journal, there will be a button where you can return the request to the list (either &ldquo;Cancel "
rawText "Snooze&rdquo; or &ldquo;Show Now&rdquo;). The &ldquo;Answered&rdquo; link shows all requests that "
rawText "have been marked answered. The &ldquo;Snoozed&rdquo; link only shows snoozed requests."
]
]
/// The "Final Notes" section
let private finalNotes = [
h3 [ _class "mb-3 mt-4" ] [ rawText "Final Notes" ]
ul [] [
li [] [
rawText "If you encounter errors, please "
a [ _href "https://git.bitbadger.solutions/bit-badger/myPrayerJournal/issues"; _target "_blank" ] [
rawText "file an issue"
]; rawText " (or "
a [ _href "mailto:daniel@bitbadger.solutions?subject=myPrayerJournal+Issue" ] [ rawText "e-mail Daniel" ]
rawText " if you do not have an account on that server) with as much detail as possible. You can also "
rawText "provide suggestions, or browse the list of currently open issues."
]
li [] [
rawText "Prayer requests and their history are securely backed up nightly along with other Bit Badger "
rawText "Solutions data."
]
li [] [
rawText "Prayer changes things - most of all, the one doing the praying. I pray that this tool enables you "
rawText "to deepen and strengthen your prayer life."
]
]
]
/// The documentation page
let index =
article [ _class "container mt-3" ] [
h2 [ _class "mb-3" ] [ rawText "Documentation" ]
yield! about
yield! signUp
yield! yourJournal
yield! addRequest
yield! setRecurrence
yield! praying
yield! editing
yield! addNotes
yield! snoozing
yield! viewing
yield! finalNotes
]

View File

@ -0,0 +1,42 @@
/// Internal partial views
[<AutoOpen>]
module private MyPrayerJournal.Views.Helpers
open Giraffe.Htmx
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Htmx
open MyPrayerJournal
open NodaTime
/// Create a link that targets the `#top` element and pushes a URL to history
let pageLink href attrs =
attrs
|> List.append [ _href href; _hxBoost; _hxTarget "#top"; _hxSwap HxSwap.InnerHtml; _hxPushUrl "true" ]
|> a
/// Create a Material icon
let icon name = span [ _class "material-icons" ] [ str name ]
/// Create a card when there are no results found
let noResults heading link buttonText text =
div [ _class "card" ] [
h5 [ _class "card-header"] [ str heading ]
div [ _class "card-body text-center" ] [
p [ _class "card-text" ] text
pageLink link [ _class "btn btn-primary" ] [ str buttonText ]
]
]
/// Create a date with a span tag, displaying the relative date with the full date/time in the tooltip
let relativeDate (date : Instant) now (tz : DateTimeZone) =
span [ _title (date.InZone(tz).ToDateTimeOffset().ToString("f", null)) ] [ Dates.formatDistance now date |> str ]
/// The version of myPrayerJournal
let version =
let v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version
seq {
string v.Major
if v.Minor > 0 then
$".{v.Minor}"
if v.Revision > 0 then $".{v.Revision}"
} |> Seq.reduce (+)

View File

@ -0,0 +1,180 @@
/// Views for journal pages and components
module MyPrayerJournal.Views.Journal
open Giraffe.Htmx
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
open Giraffe.ViewEngine.Htmx
open MyPrayerJournal
/// Display a card for this prayer request
let journalCard now tz req =
let reqId = RequestId.toString req.RequestId
let spacer = span [] [ rawText "&nbsp;" ]
div [ _class "col" ] [
div [ _class "card h-100" ] [
div [ _class "card-header p-0 d-flex"; _roleToolBar ] [
pageLink $"/request/{reqId}/edit" [ _class "btn btn-secondary"; _title "Edit Request" ] [ icon "edit" ]
spacer
button [ _type "button"
_class "btn btn-secondary"
_title "Add Notes"
_data "bs-toggle" "modal"
_data "bs-target" "#notesModal"
_hxGet $"/components/request/{reqId}/add-notes"
_hxTarget "#notesBody"
_hxSwap HxSwap.InnerHtml ] [
icon "comment"
]
spacer
button [ _type "button"
_class "btn btn-secondary"
_title "Snooze Request"
_data "bs-toggle" "modal"
_data "bs-target" "#snoozeModal"
_hxGet $"/components/request/{reqId}/snooze"
_hxTarget "#snoozeBody"
_hxSwap HxSwap.InnerHtml ] [
icon "schedule"
]
div [ _class "flex-grow-1" ] []
button [ _type "button"
_class "btn btn-success w-25"
_hxPatch $"/request/{reqId}/prayed"
_title "Mark as Prayed" ] [
icon "done"
]
]
div [ _class "card-body" ] [
p [ _class "request-text" ] [ str req.Text ]
]
div [ _class "card-footer text-end text-muted px-1 py-0" ] [
em [] [
match req.LastPrayed with
| Some dt -> str "last prayed "; relativeDate dt now tz
| None -> str "last activity "; relativeDate req.AsOf now tz
]
]
]
]
/// The journal loading page
let journal user =
article [ _class "container-fluid mt-3" ] [
h2 [ _class "pb-3" ] [
str user
match user with "Your" -> () | _ -> rawText "&rsquo;s"
str " Prayer Journal"
]
p [ _class "pb-3 text-center" ] [
pageLink "/request/new/edit" [ _class "btn btn-primary "] [ icon "add_box"; str " Add a Prayer Request" ]
]
p [ _hxGet "/components/journal-items"; _hxSwap HxSwap.OuterHtml; _hxTrigger HxTrigger.Load ] [
rawText "Loading your prayer journal&hellip;"
]
div [ _id "notesModal"
_class "modal fade"
_tabindex "-1"
_ariaLabelledBy "nodesModalLabel"
_ariaHidden "true" ] [
div [ _class "modal-dialog modal-dialog-scrollable" ] [
div [ _class "modal-content" ] [
div [ _class "modal-header" ] [
h5 [ _class "modal-title"; _id "nodesModalLabel" ] [ str "Add Notes to Prayer Request" ]
button [ _type "button"; _class "btn-close"; _data "bs-dismiss" "modal"; _ariaLabel "Close" ] []
]
div [ _class "modal-body"; _id "notesBody" ] [ ]
div [ _class "modal-footer" ] [
button [ _type "button"
_id "notesDismiss"
_class "btn btn-secondary"
_data "bs-dismiss" "modal" ] [
str "Close"
]
]
]
]
]
div [ _id "snoozeModal"
_class "modal fade"
_tabindex "-1"
_ariaLabelledBy "snoozeModalLabel"
_ariaHidden "true" ] [
div [ _class "modal-dialog modal-sm" ] [
div [ _class "modal-content" ] [
div [ _class "modal-header" ] [
h5 [ _class "modal-title"; _id "snoozeModalLabel" ] [ str "Snooze Prayer Request" ]
button [ _type "button"; _class "btn-close"; _data "bs-dismiss" "modal"; _ariaLabel "Close" ] []
]
div [ _class "modal-body"; _id "snoozeBody" ] [ ]
div [ _class "modal-footer" ] [
button [ _type "button"
_id "snoozeDismiss"
_class "btn btn-secondary"
_data "bs-dismiss" "modal" ] [
str "Close"
]
]
]
]
]
]
/// The journal items
let journalItems now tz items =
match items |> List.isEmpty with
| true ->
noResults "No Active Requests" "/request/new/edit" "Add a Request" [
rawText "You have no requests to be shown; see the &ldquo;Active&rdquo; link above for snoozed or deferred "
rawText "requests, and the &ldquo;Answered&rdquo; link for answered requests"
]
| false ->
items
|> List.map (journalCard now tz)
|> section [ _id "journalItems"
_class "row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-3"
_hxTarget "this"
_hxSwap HxSwap.OuterHtml
_ariaLabel "Prayer Requests" ]
/// The notes edit modal body
let notesEdit requestId =
let reqId = RequestId.toString requestId
[ form [ _hxPost $"/request/{reqId}/note" ] [
div [ _class "form-floating pb-3" ] [
textarea [ _id "notes"
_name "notes"
_class "form-control"
_style "min-height: 8rem;"
_placeholder "Notes"
_autofocus; _required ] [ ]
label [ _for "notes" ] [ str "Notes" ]
]
p [ _class "text-end" ] [ button [ _type "submit"; _class "btn btn-primary" ] [ str "Add Notes" ] ]
]
hr [ _style "margin: .5rem -1rem" ]
div [ _id "priorNotes" ] [
p [ _class "text-center pt-3" ] [
button [ _type "button"
_class "btn btn-secondary"
_hxGet $"/components/request/{reqId}/notes"
_hxSwap HxSwap.OuterHtml
_hxTarget "#priorNotes" ] [
str "Load Prior Notes"
]
]
]
]
/// The snooze edit form
let snooze requestId =
let today = System.DateTime.Today.ToString "yyyy-MM-dd"
form [ _hxPatch $"/request/{RequestId.toString requestId}/snooze"
_hxTarget "#journalItems"
_hxSwap HxSwap.OuterHtml ] [
div [ _class "form-floating pb-3" ] [
input [ _type "date"; _id "until"; _name "until"; _class "form-control"; _min today; _required ]
label [ _for "until" ] [ str "Until" ]
]
p [ _class "text-end mb-0" ] [ button [ _type "submit"; _class "btn btn-primary" ] [ str "Snooze" ] ]
]

View File

@ -0,0 +1,125 @@
/// Layout / home views
module MyPrayerJournal.Views.Layout
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
/// The data needed to render a page-level view
type PageRenderContext =
{ /// Whether the user is authenticated
IsAuthenticated: bool
/// Whether the user has snoozed requests
HasSnoozed: bool
/// The current URL
CurrentUrl: string
/// The title for the page to be rendered
PageTitle: string
/// The content of the page
Content: XmlNode }
/// The home page
let home =
article [ _class "container mt-3" ]
[ p [] [ rawText "&nbsp;" ]
p []
[ str "myPrayerJournal is a place where individuals can record their prayer requests, record that they "
str "prayed for them, update them as God moves in the situation, and record a final answer received on "
str "that request. It also allows individuals to review their answered prayers." ]
p []
[ str "This site is open and available to the general public. To get started, simply click the "
rawText "&ldquo;Log On&rdquo; link above, and log on with either a Microsoft or Google account. You can "
rawText "also learn more about the site at the &ldquo;Docs&rdquo; link, also above." ] ]
/// The default navigation bar, which will load the items on page load, and whenever a refresh event occurs
let private navBar ctx =
nav [ _class "navbar navbar-dark"; _roleNavigation ]
[ div [ _class "container-fluid" ]
[ pageLink
"/" [ _class "navbar-brand" ]
[ span [ _class "m" ] [ str "my" ]
span [ _class "p" ] [ str "Prayer" ]
span [ _class "j" ] [ str "Journal" ] ]
seq {
let navLink (matchUrl : string) =
match ctx.CurrentUrl.StartsWith matchUrl with true -> [ _class "is-active-route" ] | false -> []
|> pageLink matchUrl
if ctx.IsAuthenticated then
li [ _class "nav-item" ] [ navLink "/journal" [ str "Journal" ] ]
li [ _class "nav-item" ] [ navLink "/requests/active" [ str "Active" ] ]
if ctx.HasSnoozed then li [ _class "nav-item" ] [ navLink "/requests/snoozed" [ str "Snoozed" ] ]
li [ _class "nav-item" ] [ navLink "/requests/answered" [ str "Answered" ] ]
li [ _class "nav-item" ] [ a [ _href "/user/log-off" ] [ str "Log Off" ] ]
else li [ _class "nav-item"] [ a [ _href "/user/log-on" ] [ str "Log On" ] ]
li [ _class "nav-item" ] [ navLink "/docs" [ str "Docs" ] ]
}
|> List.ofSeq
|> ul [ _class "navbar-nav me-auto d-flex flex-row" ] ] ]
/// The title tag with the application name appended
let titleTag ctx =
title [] [ rawText ctx.PageTitle; rawText " &#xab; myPrayerJournal" ]
/// The HTML `head` element
let htmlHead ctx =
head [ _lang "en" ]
[ meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
meta [ _name "description"; _content "Online prayer journal - free w/Google or Microsoft account" ]
titleTag ctx
link [ _href "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
_rel "stylesheet"
_integrity "sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
_crossorigin "anonymous" ]
link [ _href "https://fonts.googleapis.com/icon?family=Material+Icons"; _rel "stylesheet" ]
link [ _href "/style/style.css"; _rel "stylesheet" ] ]
/// Element used to display toasts
let toaster =
div [ _ariaLive "polite"; _ariaAtomic "true"; _id "toastHost" ]
[ div [ _class "toast-container position-absolute p-3 bottom-0 end-0"; _id "toasts" ] [] ]
/// The page's `footer` element
let htmlFoot =
footer [ _class "container-fluid" ]
[ p [ _class "text-muted text-end" ]
[ str $"myPrayerJournal {version}"
br []
em []
[ small []
[ pageLink "/legal/privacy-policy" [] [ str "Privacy Policy" ]
rawText " &bull; "
pageLink "/legal/terms-of-service" [] [ str "Terms of Service" ]
rawText " &bull; "
a [ _href "https://git.bitbadger.solutions/bit-badger/myPrayerJournal"
_target "_blank"
_rel "noopener" ] [ str "Developed" ]
str " and hosted by "
a [ _href "https://bitbadger.solutions"; _target "_blank"; _rel "noopener" ]
[ str "Bit Badger Solutions" ] ] ] ]
Htmx.Script.minified
script [] [ rawText "if (!htmx) document.write('<script src=\"/script/htmx.min.js\"><\/script>')" ]
script [ _async
_src "https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
_integrity "sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
_crossorigin "anonymous" ] []
script []
[ rawText "setTimeout(function () { "
rawText "if (!bootstrap) document.write('<script src=\"/script/bootstrap.bundle.min.js\"><\/script>') "
rawText "}, 2000)" ]
script [ _src "/script/mpj.js" ] [] ]
/// Create the full view of the page
let view ctx =
html [ _lang "en" ]
[ htmlHead ctx
body []
[ section [ _id "top"; _ariaLabel "Top navigation" ] [ navBar ctx; main [ _roleMain ] [ ctx.Content ] ]
toaster
htmlFoot ] ]
/// Create a partial view
let partial ctx =
html [ _lang "en" ] [ head [] [ titleTag ctx ]; body [] [ navBar ctx; main [ _roleMain ] [ ctx.Content ] ] ]

View File

@ -0,0 +1,162 @@
/// Views for legal pages
module MyPrayerJournal.Views.Legal
open Giraffe.ViewEngine
/// View for the "Privacy Policy" page
let privacyPolicy =
article [ _class "container mt-3" ] [
h2 [ _class "mb-2" ] [ str "Privacy Policy" ]
h6 [ _class "text-muted pb-3" ] [ str "as of May 21"; sup [] [ str "st"]; str ", 2018" ]
p [] [
str "The nature of the service is one where privacy is a must. The items below will help you understand "
str "the data we collect, access, and store on your behalf as you use this service."
]
div [ _class "card" ] [
div [ _class "list-group list-group-flush" ] [
div [ _class "list-group-item"] [
h3 [] [ str "Third Party Services" ]
p [ _class "card-text" ] [
str "myPrayerJournal utilizes a third-party authentication and identity provider. You should "
str "familiarize yourself with the privacy policy for "
a [ _href "https://auth0.com/privacy"; _target "_blank" ] [ str "Auth0" ]
str ", as well as your chosen provider ("
a [ _href "https://privacy.microsoft.com/en-us/privacystatement"; _target "_blank" ] [
str "Microsoft"
]
str " or "
a [ _href "https://policies.google.com/privacy"; _target "_blank" ] [ str "Google" ]
str ")."
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "What We Collect" ]
h4 [] [ str "Identifying Data" ]
ul [] [
li [] [
str "The only identifying data myPrayerJournal stores is the subscriber "
rawText "(&ldquo;sub&rdquo;) field from the token we receive from Auth0, once you have "
str "signed in through their hosted service. All information is associated with you via "
str "this field."
]
li [] [
str "While you are signed in, within your browser, the service has access to your first "
str "and last names, along with a URL to the profile picture (provided by your selected "
str "identity provider). This information is not transmitted to the server, and is removed "
rawText "when &ldquo;Log Off&rdquo; is clicked."
]
]
h4 [] [ str "User Provided Data" ]
ul [ _class "mb-0" ] [
li [] [
str "myPrayerJournal stores the information you provide, including the text of prayer "
str "requests, updates, and notes; and the date/time when certain actions are taken."
]
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "How Your Data Is Accessed / Secured" ]
ul [ _class "mb-0" ] [
li [] [
str "Your provided data is returned to you, as required, to display your journal or your "
str "answered requests. On the server, it is stored in a controlled-access database."
]
li [] [
str "Your data is backed up, along with other Bit Badger Solutions hosted systems, in a "
str "rolling manner; backups are preserved for the prior 7 days, and backups from the 1"
sup [] [ str "st" ]
str " and 15"
sup [] [ str "th" ]
str " are preserved for 3 months. These backups are stored in a private cloud data "
str "repository."
]
li [] [
str "The data collected and stored is the absolute minimum necessary for the functionality "
rawText "of the service. There are no plans to &ldquo;monetize&rdquo; this service, and "
str "storing the minimum amount of information means that the data we have is not "
str "interesting to purchasers (or those who may have more nefarious purposes)."
]
li [] [
str "Access to servers and backups is strictly controlled and monitored for unauthorized "
str "access attempts."
]
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "Removing Your Data" ]
p [ _class "card-text" ] [
str "At any time, you may choose to discontinue using this service. Both Microsoft and Google "
str "provide ways to revoke access from this application. However, if you want your data "
str "removed from the database, please contact daniel at bitbadger.solutions (via e-mail, "
str "replacing at with @) prior to doing so, to ensure we can determine which subscriber ID "
str "belongs to you."
]
]
]
]
]
/// View for the "Terms of Service" page
let termsOfService =
article [ _class "container mt-3" ] [
h2 [ _class "mb-2" ] [ str "Terms of Service" ]
h6 [ _class "text-muted pb-3"] [ str "as of May 21"; sup [] [ str "st" ]; str ", 2018" ]
div [ _class "card" ] [
div [ _class "list-group list-group-flush" ] [
div [ _class "list-group-item" ] [
h3 [] [ str "1. Acceptance of Terms" ]
p [ _class "card-text" ] [
str "By accessing this web site, you are agreeing to be bound by these Terms and Conditions, "
str "and that you are responsible to ensure that your use of this site complies with all "
str "applicable laws. Your continued use of this site implies your acceptance of these terms."
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "2. Description of Service and Registration" ]
p [ _class "card-text" ] [
str "myPrayerJournal is a service that allows individuals to enter and amend their prayer "
str "requests. It requires no registration by itself, but access is granted based on a "
str "successful login with an external identity provider. See "
pageLink "/legal/privacy-policy" [] [ str "our privacy policy" ]
str " for details on how that information is accessed and stored."
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "3. Third Party Services" ]
p [ _class "card-text" ] [
str "This service utilizes a third-party service provider for identity management. Review the "
str "terms of service for "
a [ _href "https://auth0.com/terms"; _target "_blank" ] [ str "Auth0"]
str ", as well as those for the selected authorization provider ("
a [ _href "https://www.microsoft.com/en-us/servicesagreement"; _target "_blank" ] [
str "Microsoft"
]
str " or "
a [ _href "https://policies.google.com/terms"; _target "_blank" ] [ str "Google" ]
str ")."
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "4. Liability" ]
p [ _class "card-text" ] [
rawText "This service is provided &ldquo;as is&rdquo;, and no warranty (express or implied) "
str "exists. The service and its developers may not be held liable for any damages that may "
str "arise through the use of this service."
]
]
div [ _class "list-group-item" ] [
h3 [] [ str "5. Updates to Terms" ]
p [ _class "card-text" ] [
str "These terms and conditions may be updated at any time, and this service does not have the "
str "capability to notify users when these change. The date at the top of the page will be "
str "updated when any of the text of these terms is updated."
]
]
]
]
p [ _class "pt-3" ] [
str "You may also wish to review our "
pageLink "/legal/privacy-policy" [] [ str "privacy policy" ]
str " to learn how we handle your data."
]
]

View File

@ -0,0 +1,273 @@
/// Views for request pages and components
module MyPrayerJournal.Views.Request
open Giraffe.Htmx
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Htmx
open MyPrayerJournal
open NodaTime
/// Create a request within the list
let reqListItem now tz req =
let isFuture instant = defaultArg (instant |> Option.map (fun it -> it > now)) false
let reqId = RequestId.toString req.RequestId
let isAnswered = req.LastStatus = Answered
let isSnoozed = isFuture req.SnoozedUntil
let isPending = (not isSnoozed) && isFuture req.ShowAfter
let btnClass = _class "btn btn-light mx-2"
let restoreBtn (link : string) title =
button [ btnClass; _hxPatch $"/request/{reqId}/{link}"; _title title ] [ icon "restore" ]
div [ _class "list-group-item px-0 d-flex flex-row align-items-start"
_hxTarget "this"
_hxSwap HxSwap.OuterHtml ] [
pageLink $"/request/{reqId}/full" [ btnClass; _title "View Full Request" ] [ icon "description" ]
if not isAnswered then pageLink $"/request/{reqId}/edit" [ btnClass; _title "Edit Request" ] [ icon "edit" ]
if isSnoozed then restoreBtn "cancel-snooze" "Cancel Snooze"
elif isPending then restoreBtn "show" "Show Now"
p [ _class "request-text mb-0" ] [
str req.Text
if isSnoozed || isPending || isAnswered then
br []
small [ _class "text-muted" ] [
if isSnoozed then [ str "Snooze expires "; relativeDate req.SnoozedUntil.Value now tz ]
elif isPending then [ str "Request appears next "; relativeDate req.ShowAfter.Value now tz ]
else (* isAnswered *) [ str "Answered "; relativeDate req.AsOf now tz ]
|> em []
]
]
]
/// Create a list of requests
let reqList now tz reqs =
reqs
|> List.map (reqListItem now tz)
|> div [ _class "list-group" ]
/// View for Active Requests page
let active now tz reqs =
article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Active Requests" ]
if List.isEmpty reqs then
noResults "No Active Requests" "/journal" "Return to your journal"
[ str "Your prayer journal has no active requests" ]
else reqList now tz reqs
]
/// View for Answered Requests page
let answered now tz reqs =
article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Answered Requests" ]
if List.isEmpty reqs then
noResults "No Answered Requests" "/journal" "Return to your journal" [
str "Your prayer journal has no answered requests; once you have marked one as "
rawText "&ldquo;Answered&rdquo;, it will appear here"
]
else reqList now tz reqs
]
/// View for Snoozed Requests page
let snoozed now tz reqs =
article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Snoozed Requests" ]
reqList now tz reqs
]
/// View for Full Request page
let full (clock : IClock) tz (req : Request) =
let now = clock.GetCurrentInstant()
let answered =
req.History
|> Seq.ofList
|> Seq.filter History.isAnswered
|> Seq.tryHead
|> Option.map (_.AsOf)
let prayed = (req.History |> List.filter History.isPrayed |> List.length).ToString "N0"
let daysOpen =
let asOf = defaultArg answered now
((asOf - (req.History |> List.filter History.isCreated |> List.head).AsOf).TotalDays |> int).ToString "N0"
let lastText =
req.History
|> Seq.ofList
|> Seq.filter (fun h -> Option.isSome h.Text)
|> Seq.sortByDescending (_.AsOf)
|> Seq.map (fun h -> Option.get h.Text)
|> Seq.head
// The history log including notes (and excluding the final entry for answered requests)
let log =
let toDisp (h : History) = {| asOf = h.AsOf; text = h.Text; status = RequestAction.toString h.Status |}
let all =
req.Notes
|> Seq.ofList
|> Seq.map (fun n -> {| asOf = n.AsOf; text = Some n.Notes; status = "Notes" |})
|> Seq.append (req.History |> List.map toDisp)
|> Seq.sortByDescending (_.asOf)
|> List.ofSeq
// Skip the first entry for answered requests; that info is already displayed
match answered with Some _ -> all.Tail | None -> all
article [ _class "container mt-3" ] [
div [_class "card" ] [
h5 [ _class "card-header" ] [ str "Full Prayer Request" ]
div [ _class "card-body" ] [
h6 [ _class "card-subtitle text-muted mb-2"] [
match answered with
| Some date ->
str "Answered "
date.ToDateTimeOffset().ToString("D", null) |> str
str " ("
relativeDate date now tz
rawText ") &bull; "
| None -> ()
rawText $"Prayed %s{prayed} times &bull; Open %s{daysOpen} days"
]
p [ _class "card-text" ] [ str lastText ]
]
log
|> List.map (fun it ->
li [ _class "list-group-item" ] [
p [ _class "m-0" ] [
str it.status
rawText "&nbsp; "
small [] [ em [] [ it.asOf.ToDateTimeOffset().ToString("D", null) |> str ] ]
]
match it.text with
| Some txt -> p [ _class "mt-2 mb-0" ] [ str txt ]
| None -> ()
])
|> ul [ _class "list-group list-group-flush" ]
]
]
/// View for the edit request component
let edit (req : JournalRequest) returnTo isNew =
let cancelLink =
match returnTo with
| "active" -> "/requests/active"
| "snoozed" -> "/requests/snoozed"
| _ (* "journal" *) -> "/journal"
let recurCount =
match req.Recurrence with
| Immediate -> None
| Hours h -> Some h
| Days d -> Some d
| Weeks w -> Some w
|> Option.map string
|> Option.defaultValue ""
article [ _class "container" ] [
h2 [ _class "pb-3" ] [ (match isNew with true -> "Add" | false -> "Edit") |> strf "%s Prayer Request" ]
form [ _hxBoost
_hxTarget "#top"
_hxPushUrl "true"
"/request" |> match isNew with true -> _hxPost | false -> _hxPatch ] [
input [ _type "hidden"
_name "requestId"
_value (match isNew with true -> "new" | false -> RequestId.toString req.RequestId) ]
input [ _type "hidden"; _name "returnTo"; _value returnTo ]
div [ _class "form-floating pb-3" ] [
textarea [ _id "requestText"
_name "requestText"
_class "form-control"
_style "min-height: 8rem;"
_placeholder "Enter the text of the request"
_autofocus; _required ] [ str req.Text ]
label [ _for "requestText" ] [ str "Prayer Request" ]
]
br []
if not isNew then
div [ _class "pb-3" ] [
label [] [ str "Also Mark As" ]
br []
div [ _class "form-check form-check-inline" ] [
input [ _type "radio"
_class "form-check-input"
_id "sU"
_name "status"
_value "Updated"
_checked ]
label [ _for "sU" ] [ str "Updated" ]
]
div [ _class "form-check form-check-inline" ] [
input [ _type "radio"; _class "form-check-input"; _id "sP"; _name "status"; _value "Prayed" ]
label [ _for "sP" ] [ str "Prayed" ]
]
div [ _class "form-check form-check-inline" ] [
input [ _type "radio"; _class "form-check-input"; _id "sA"; _name "status"; _value "Answered" ]
label [ _for "sA" ] [ str "Answered" ]
]
]
div [ _class "row" ] [
div [ _class "col-12 offset-md-2 col-md-8 offset-lg-3 col-lg-6" ] [
p [] [
strong [] [ rawText "Recurrence &nbsp; " ]
em [ _class "text-muted" ] [ rawText "After prayer, request reappears&hellip;" ]
]
div [ _class "d-flex flex-row flex-wrap justify-content-center align-items-center" ] [
div [ _class "form-check mx-2" ] [
input [ _type "radio"
_class "form-check-input"
_id "rI"
_name "recurType"
_value "Immediate"
_onclick "mpj.edit.toggleRecurrence(event)"
match req.Recurrence with Immediate -> _checked | _ -> () ]
label [ _for "rI" ] [ str "Immediately" ]
]
div [ _class "form-check mx-2"] [
input [ _type "radio"
_class "form-check-input"
_id "rO"
_name "recurType"
_value "Other"
_onclick "mpj.edit.toggleRecurrence(event)"
match req.Recurrence with Immediate -> () | _ -> _checked ]
label [ _for "rO" ] [ rawText "Every&hellip;" ]
]
div [ _class "form-floating mx-2"] [
input [ _type "number"
_class "form-control"
_id "recurCount"
_name "recurCount"
_placeholder "0"
_value recurCount
_style "width:6rem;"
_required
match req.Recurrence with Immediate -> _disabled | _ -> () ]
label [ _for "recurCount" ] [ str "Count" ]
]
div [ _class "form-floating mx-2" ] [
select [ _class "form-control"
_id "recurInterval"
_name "recurInterval"
_style "width:6rem;"
_required
match req.Recurrence with Immediate -> _disabled | _ -> () ] [
option [ _value "Hours"; match req.Recurrence with Hours _ -> _selected | _ -> () ] [
str "hours"
]
option [ _value "Days"; match req.Recurrence with Days _ -> _selected | _ -> () ] [
str "days"
]
option [ _value "Weeks"; match req.Recurrence with Weeks _ -> _selected | _ -> () ] [
str "weeks"
]
]
label [ _form "recurInterval" ] [ str "Interval" ]
]
]
]
]
div [ _class "text-end pt-3" ] [
button [ _class "btn btn-primary me-2"; _type "submit" ] [ icon "save"; str " Save" ]
pageLink cancelLink [ _class "btn btn-secondary ms-2" ] [ icon "arrow_back"; str " Cancel" ]
]
]
]
/// Display a list of notes for a request
let notes now tz notes =
let toItem (note : Note) =
p [] [ small [ _class "text-muted" ] [ relativeDate note.AsOf now tz ]; br []; str note.Notes ]
[ p [ _class "text-center" ] [ strong [] [ str "Prior Notes for This Request" ] ]
match notes with
| [] -> p [ _class "text-center text-muted" ] [ str "There are no prior notes for this request" ]
| _ -> yield! notes |> List.map toItem
]

View File

@ -0,0 +1,2 @@
{
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,104 @@
"use strict"
/** myPrayerJournal script */
this.mpj = {
/**
* Show a message via toast
* @param {string} message The message to show
*/
showToast (message) {
const [level, msg] = message.split("|||")
let header
if (level !== "success") {
const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>`
header = document.createElement("div")
header.className = "toast-header"
header.innerHTML = heading(level === "warning" ? level : "error")
const close = document.createElement("button")
close.type = "button"
close.className = "btn-close"
close.setAttribute("data-bs-dismiss", "toast")
close.setAttribute("aria-label", "Close")
header.appendChild(close)
}
const body = document.createElement("div")
body.className = "toast-body"
body.innerText = msg
const toastEl = document.createElement("div")
toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white`
toastEl.setAttribute("role", "alert")
toastEl.setAttribute("aria-live", "assertlive")
toastEl.setAttribute("aria-atomic", "true")
toastEl.addEventListener("hidden.bs.toast", e => e.target.remove())
if (header) toastEl.appendChild(header)
toastEl.appendChild(body)
document.getElementById("toasts").appendChild(toastEl)
new bootstrap.Toast(toastEl, { autohide: level === "success" }).show()
},
/**
* Load local version of Bootstrap CSS if the CDN load failed
*/
ensureCss () {
let loaded = false
for (let i = 0; !loaded && i < document.styleSheets.length; i++) {
loaded = document.styleSheets[i].href.endsWith("bootstrap.min.css")
}
if (!loaded) {
const css = document.createElement("link")
css.rel = "stylesheet"
css.href = "/style/bootstrap.min.css"
document.getElementsByTagName("head")[0].appendChild(css)
}
},
/** Script for the request edit component */
edit: {
/**
* Toggle the recurrence input fields
* @param {Event} e The click event
*/
toggleRecurrence ({ target }) {
const isDisabled = target.value === "Immediate"
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled)
}
},
/**
* The time zone of the current browser
* @type {string}
**/
timeZone: undefined,
/**
* Derive the time zone from the current browser
*/
deriveTimeZone () {
try {
this.timeZone = (new Intl.DateTimeFormat()).resolvedOptions().timeZone
} catch (_) { }
}
}
htmx.on("htmx:afterOnLoad", function (evt) {
const hdrs = evt.detail.xhr.getAllResponseHeaders()
// Show a message if there was one in the response
if (hdrs.indexOf("x-toast") >= 0) {
mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast"))
}
// Hide a modal window if requested
if (hdrs.indexOf("x-hide-modal") >= 0) {
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click()
}
})
htmx.on("htmx:configRequest", function (evt) {
// Send the user's current time zone so that we can display local time
if (mpj.timeZone) {
evt.detail.headers["X-Time-Zone"] = mpj.timeZone
}
})
mpj.deriveTimeZone()

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,57 @@
nav {
background-color: green;
}
nav .m {
font-weight: 100;
}
nav .p {
font-weight: 400;
}
nav .j {
font-weight: 700;
}
.nav-item a:link,
.nav-item a:visited {
padding: .5rem 1rem;
margin: 0 .5rem;
border-radius: .5rem;
color: white;
text-decoration: none;
}
.nav-item a:hover {
cursor: pointer;
background-color: rgba(255, 255, 255, .2);
}
.nav-item a.is-active-route {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-top: solid 4px rgba(255, 255, 255, .3);
}
form {
max-width: 60rem;
margin: auto;
}
.action-cell .material-icons {
font-size: 1.1rem ;
}
.material-icons {
vertical-align: bottom;
}
#toastHost {
position: sticky;
bottom: 0;
}
.request-text {
white-space: pre-line
}
footer {
border-top: solid 1px lightgray;
margin: 1rem -1rem 0;
padding: 0 1rem;
}
footer p {
margin: 0;
}

View File

@ -1,366 +0,0 @@
// Package data contains data access functions for myPrayerJournal.
package data
import (
"database/sql"
"fmt"
"log"
"time"
// Register the PostgreSQL driver.
_ "github.com/lib/pq"
"github.com/lucsky/cuid"
)
const (
currentRequestSQL = `
SELECT "requestId", "text", "asOf", "lastStatus"
FROM mpj.journal`
journalSQL = `
SELECT "requestId", "text", "asOf", "lastStatus"
FROM mpj.journal
WHERE "userId" = $1
AND "lastStatus" <> 'Answered'`
)
// db is a connection to the database for the entire application.
var db *sql.DB
// Settings holds the PostgreSQL configuration for myPrayerJournal.
type Settings struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
DbName string `json:"dbname"`
}
/* Data Access */
// Retrieve a basic request
func retrieveRequest(reqID, userID string) (*Request, bool) {
req := Request{}
err := db.QueryRow(`
SELECT "requestId", "enteredOn"
FROM mpj.request
WHERE "requestId" = $1
AND "userId" = $2`, reqID, userID).Scan(
&req.ID, &req.EnteredOn,
)
if err != nil {
if err != sql.ErrNoRows {
log.Print(err)
}
return nil, false
}
req.UserID = userID
return &req, true
}
// Unix time in JavaScript Date.now() precision.
func jsNow() int64 {
return time.Now().UnixNano() / int64(1000000)
}
// Loop through rows and create journal requests from them.
func makeJournal(rows *sql.Rows, userID string) []JournalRequest {
var out []JournalRequest
for rows.Next() {
req := JournalRequest{}
err := rows.Scan(&req.RequestID, &req.Text, &req.AsOf, &req.LastStatus)
if err != nil {
log.Print(err)
continue
}
out = append(out, req)
}
if rows.Err() != nil {
log.Print(rows.Err())
return nil
}
return out
}
// AddHistory creates a history entry for a prayer request, given the status and updated text.
func AddHistory(userID, reqID, status, text string) int {
if _, ok := retrieveRequest(reqID, userID); !ok {
return 404
}
_, err := db.Exec(`
INSERT INTO mpj.history
("requestId", "asOf", "status", "text")
VALUES
($1, $2, $3, NULLIF($4, ''))`,
reqID, jsNow(), status, text)
if err != nil {
log.Print(err)
return 500
}
return 204
}
// AddNew stores a new prayer request and its initial history record.
func AddNew(userID, text string) (*JournalRequest, bool) {
id := cuid.New()
now := jsNow()
tx, err := db.Begin()
if err != nil {
log.Print(err)
return nil, false
}
defer func() {
if err != nil {
log.Print(err)
tx.Rollback()
} else {
tx.Commit()
}
}()
_, err = tx.Exec(
`INSERT INTO mpj.request ("requestId", "enteredOn", "userId") VALUES ($1, $2, $3)`,
id, now, userID)
if err != nil {
return nil, false
}
_, err = tx.Exec(
`INSERT INTO mpj.history ("requestId", "asOf", "status", "text") VALUES ($1, $2, 'Created', $3)`,
id, now, text)
if err != nil {
return nil, false
}
return &JournalRequest{RequestID: id, Text: text, AsOf: now, LastStatus: `Created`}, true
}
// AddNote adds a note to a prayer request.
func AddNote(userID, reqID, note string) int {
if _, ok := retrieveRequest(reqID, userID); !ok {
return 404
}
_, err := db.Exec(`
INSERT INTO mpj.note
("requestId", "asOf", "notes")
VALUES
($1, $2, $3)`,
reqID, jsNow(), note)
if err != nil {
log.Print(err)
return 500
}
return 204
}
// Answered retrieves all answered requests for the given user.
func Answered(userID string) []JournalRequest {
rows, err := db.Query(currentRequestSQL+
` WHERE "userId" = $1
AND "lastStatus" = 'Answered'
ORDER BY "asOf" DESC`,
userID)
if err != nil {
log.Print(err)
return nil
}
defer rows.Close()
return makeJournal(rows, userID)
}
// ByID retrieves a journal request by its ID.
func ByID(userID, reqID string) (*JournalRequest, bool) {
req := JournalRequest{}
err := db.QueryRow(currentRequestSQL+
` WHERE "requestId" = $1
AND "userId" = $2`,
reqID, userID).Scan(
&req.RequestID, &req.Text, &req.AsOf, &req.LastStatus,
)
if err != nil {
if err == sql.ErrNoRows {
return nil, true
}
log.Print(err)
return nil, false
}
return &req, true
}
// Connect establishes a connection to the database.
func Connect(s *Settings) bool {
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
s.Host, s.Port, s.User, s.Password, s.DbName)
var err error
db, err = sql.Open("postgres", connStr)
if err != nil {
log.Print(err)
return false
}
err = db.Ping()
if err != nil {
log.Print(err)
return false
}
log.Printf("Connected to postgres://%s@%s:%d/%s\n", s.User, s.Host, s.Port, s.DbName)
return true
}
// FullByID retrieves a journal request, including its full history and notes.
func FullByID(userID, reqID string) (*JournalRequest, bool) {
req, ok := ByID(userID, reqID)
if !ok {
return nil, false
}
hRows, err := db.Query(`
SELECT "asOf", "status", COALESCE("text", '') AS "text"
FROM mpj.history
WHERE "requestId" = $1
ORDER BY "asOf"`,
reqID)
if err != nil {
log.Print(err)
return nil, false
}
defer hRows.Close()
for hRows.Next() {
hist := History{}
err = hRows.Scan(&hist.AsOf, &hist.Status, &hist.Text)
if err != nil {
log.Print(err)
continue
}
req.History = append(req.History, hist)
}
if hRows.Err() != nil {
log.Print(hRows.Err())
return nil, false
}
req.Notes, err = NotesByID(userID, reqID)
if err != nil {
log.Print(err)
return nil, false
}
return req, true
}
// Journal retrieves the current user's active prayer journal.
func Journal(userID string) []JournalRequest {
rows, err := db.Query(journalSQL+` ORDER BY "asOf"`, userID)
if err != nil {
log.Print(err)
return nil
}
defer rows.Close()
return makeJournal(rows, userID)
}
// NotesByID retrieves the notes for a given prayer request
func NotesByID(userID, reqID string) ([]Note, error) {
if _, ok := retrieveRequest(reqID, userID); !ok {
return nil, sql.ErrNoRows
}
rows, err := db.Query(`
SELECT "asOf", "notes"
FROM mpj.note
WHERE "requestId" = $1
ORDER BY "asOf" DESC`,
reqID)
if err != nil {
log.Print(err)
return nil, err
}
defer rows.Close()
var notes []Note
for rows.Next() {
note := Note{}
err = rows.Scan(&note.AsOf, &note.Notes)
if err != nil {
log.Print(err)
continue
}
notes = append(notes, note)
}
if rows.Err() != nil {
log.Print(rows.Err())
return nil, err
}
return notes, nil
}
/* DDL */
// EnsureDB makes sure we have a known state of data structures.
func EnsureDB() {
tableSQL := func(table string) string {
return fmt.Sprintf(`SELECT 1 FROM pg_tables WHERE schemaname='mpj' AND tablename='%s'`, table)
}
indexSQL := func(table, index string) string {
return fmt.Sprintf(`SELECT 1 FROM pg_indexes WHERE schemaname='mpj' AND tablename='%s' AND indexname='%s'`,
table, index)
}
check := func(name, test, fix string) {
count := 0
err := db.QueryRow(test).Scan(&count)
if err != nil {
if err == sql.ErrNoRows {
log.Printf("Fixing up %s...\n", name)
_, err = db.Exec(fix)
if err != nil {
log.Fatal(err)
}
} else {
log.Fatal(err)
}
}
}
check(`myPrayerJournal Schema`, `SELECT 1 FROM pg_namespace WHERE nspname='mpj'`,
`CREATE SCHEMA mpj;
COMMENT ON SCHEMA mpj IS 'myPrayerJournal data'`)
if _, err := db.Exec(`SET search_path TO mpj`); err != nil {
log.Fatal(err)
}
check(`request Table`, tableSQL(`request`),
`CREATE TABLE mpj.request (
"requestId" varchar(25) PRIMARY KEY,
"enteredOn" bigint NOT NULL,
"userId" varchar(100) NOT NULL);
COMMENT ON TABLE mpj.request IS 'Requests'`)
check(`history Table`, tableSQL(`history`),
`CREATE TABLE mpj.history (
"requestId" varchar(25) NOT NULL REFERENCES mpj.request,
"asOf" bigint NOT NULL,
"status" varchar(25),
"text" text,
PRIMARY KEY ("requestId", "asOf"));
COMMENT ON TABLE mpj.history IS 'Request update history'`)
check(`note Table`, tableSQL(`note`),
`CREATE TABLE mpj.note (
"requestId" varchar(25) NOT NULL REFERENCES mpj.request,
"asOf" bigint NOT NULL,
"notes" text NOT NULL,
PRIMARY KEY ("requestId", "asOf"));
COMMENT ON TABLE mpj.note IS 'Notes regarding a request'`)
check(`request.userId Index`, indexSQL(`request`, `idx_request_userId`),
`CREATE INDEX "idx_request_userId" ON mpj.request ("userId");
COMMENT ON INDEX "idx_request_userId" IS 'Requests are retrieved by user'`)
check(`journal View`, `SELECT 1 FROM pg_views WHERE schemaname='mpj' AND viewname='journal'`,
`CREATE VIEW mpj.journal AS
SELECT
request."requestId",
request."userId",
(SELECT "text"
FROM mpj.history
WHERE history."requestId" = request."requestId"
AND "text" IS NOT NULL
ORDER BY "asOf" DESC
LIMIT 1) AS "text",
(SELECT "asOf"
FROM mpj.history
WHERE history."requestId" = request."requestId"
ORDER BY "asOf" DESC
LIMIT 1) AS "asOf",
(SELECT "status"
FROM mpj.history
WHERE history."requestId" = request."requestId"
ORDER BY "asOf" DESC
LIMIT 1) AS "lastStatus"
FROM mpj.request;
COMMENT ON VIEW mpj.journal IS 'Requests with latest text'`)
}

View File

@ -1,34 +0,0 @@
package data
// History is a record of action taken on a prayer request, including updates to its text.
type History struct {
RequestID string `json:"requestId"`
AsOf int64 `json:"asOf"`
Status string `json:"status"`
Text string `json:"text"`
}
// Note is a note regarding a prayer request that does not result in an update to its text.
type Note struct {
RequestID string `json:"requestId"`
AsOf int64 `json:"asOf"`
Notes string `json:"notes"`
}
// Request is the identifying record for a prayer request.
type Request struct {
ID string `json:"requestId"`
EnteredOn int64 `json:"enteredOn"`
UserID string `json:"userId"`
}
// JournalRequest is the form of a prayer request returned for the request journal display. It also contains
// properties that may be filled for history and notes.
type JournalRequest struct {
RequestID string `json:"requestId"`
Text string `json:"text"`
AsOf int64 `json:"asOf"`
LastStatus string `json:"lastStatus"`
History []History `json:"history,omitempty"`
Notes []Note `json:"notes,omitempty"`
}

View File

@ -1,182 +0,0 @@
package routes
import (
"database/sql"
"encoding/json"
"errors"
"log"
"net/http"
"strings"
"github.com/danieljsummers/myPrayerJournal/src/api/data"
jwt "github.com/dgrijalva/jwt-go"
routing "github.com/go-ozzo/ozzo-routing"
)
/* Support */
// Set the content type, the HTTP error code, and return the error message.
func sendError(c *routing.Context, err error) error {
w := c.Response
w.Header().Set("Content-Type", "application/json; encoding=UTF-8")
w.WriteHeader(http.StatusInternalServerError)
if err := json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}); err != nil {
log.Print("Error creating error JSON: " + err.Error())
}
return err
}
// Set the content type and return the JSON to the user.
func sendJSON(c *routing.Context, result interface{}) error {
w := c.Response
w.Header().Set("Content-Type", "application/json; encoding=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(result); err != nil {
return sendError(c, err)
}
return nil
}
// Send an HTTP 404 response.
func notFound(c *routing.Context) error {
c.Response.WriteHeader(404)
return nil
}
// Parse the request body as JSON.
func parseJSON(c *routing.Context) (map[string]interface{}, error) {
payload := make(map[string]interface{})
if err := json.NewDecoder(c.Request.Body).Decode(&payload); err != nil {
log.Println("Error decoding JSON:", err)
return payload, err
}
return payload, nil
}
// userID is a convenience function to extract the subscriber ID from the user's JWT.
// NOTE: Do not call this from public routes; there are a lot of type assertions that won't be true if the request
// hasn't gone through the authorization process.
func userID(c *routing.Context) string {
return c.Request.Context().Value("user").(*jwt.Token).Claims.(jwt.MapClaims)["sub"].(string)
}
/* Handlers */
// GET: /api/journal/
func journal(c *routing.Context) error {
reqs := data.Journal(userID(c))
if reqs == nil {
reqs = []data.JournalRequest{}
}
return sendJSON(c, reqs)
}
// POST: /api/request/
func requestAdd(c *routing.Context) error {
payload, err := parseJSON(c)
if err != nil {
return sendError(c, err)
}
result, ok := data.AddNew(userID(c), payload["requestText"].(string))
if !ok {
return sendError(c, errors.New("error adding request"))
}
return sendJSON(c, result)
}
// GET: /api/request/<id>
func requestGet(c *routing.Context) error {
request, ok := data.ByID(userID(c), c.Param("id"))
if !ok {
return sendError(c, errors.New("error retrieving request"))
}
if request == nil {
return notFound(c)
}
return sendJSON(c, request)
}
// GET: /api/request/<id>/complete
func requestGetComplete(c *routing.Context) error {
request, ok := data.FullByID(userID(c), c.Param("id"))
if !ok {
return sendError(c, errors.New("error retrieving request"))
}
var err error
request.Notes, err = data.NotesByID(userID(c), c.Param("id"))
if err != nil {
return sendError(c, err)
}
return sendJSON(c, request)
}
// GET: /api/request/<id>/full
func requestGetFull(c *routing.Context) error {
request, ok := data.FullByID(userID(c), c.Param("id"))
if !ok {
return sendError(c, errors.New("error retrieving request"))
}
return sendJSON(c, request)
}
// POST: /api/request/<id>/history
func requestAddHistory(c *routing.Context) error {
payload, err := parseJSON(c)
if err != nil {
return sendError(c, err)
}
c.Response.WriteHeader(
data.AddHistory(userID(c), c.Param("id"), payload["status"].(string), payload["updateText"].(string)))
return nil
}
// POST: /api/request/<id>/note
func requestAddNote(c *routing.Context) error {
payload, err := parseJSON(c)
if err != nil {
return sendError(c, err)
}
c.Response.WriteHeader(data.AddNote(userID(c), c.Param("id"), payload["notes"].(string)))
return nil
}
// GET: /api/request/<id>/notes
func requestGetNotes(c *routing.Context) error {
notes, err := data.NotesByID(userID(c), c.Param("id"))
if err != nil {
if err == sql.ErrNoRows {
return notFound(c)
}
return sendError(c, err)
}
if notes == nil {
notes = []data.Note{}
}
return sendJSON(c, notes)
}
// GET: /api/request/answered
func requestsAnswered(c *routing.Context) error {
reqs := data.Answered(userID(c))
if reqs == nil {
reqs = []data.JournalRequest{}
}
return sendJSON(c, reqs)
}
// GET: /*
func staticFiles(c *routing.Context) error {
// serve index for known routes handled client-side by the app
r := c.Request
w := c.Response
for _, prefix := range ClientPrefixes {
if strings.HasPrefix(r.URL.Path, prefix) {
w.Header().Add("Content-Type", "text/html")
http.ServeFile(w, r, "./public/index.html")
return nil
}
}
// 404 here is fine; quit hacking, y'all...
http.ServeFile(w, r, "./public"+r.URL.Path)
return nil
}

View File

@ -1,119 +0,0 @@
package routes
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/auth0/go-jwt-middleware"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-ozzo/ozzo-routing"
"github.com/go-ozzo/ozzo-routing/fault"
)
// AuthConfig contains the Auth0 configuration passed from the "auth" JSON object.
type AuthConfig struct {
Domain string `json:"domain"`
ClientID string `json:"id"`
ClientSecret string `json:"secret"`
}
// JWKS is a structure into which the JSON Web Key Set is unmarshaled.
type JWKS struct {
Keys []JWK `json:"keys"`
}
// JWK is a structure into which a single JSON Web Key is unmarshaled.
type JWK struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
X5c []string `json:"x5c"`
}
// authCfg is the Auth0 configuration provided at application startup.
var authCfg *AuthConfig
// jwksBytes is a cache of the JSON Web Key Set for this domain.
var jwksBytes = make([]byte, 0)
// getPEMCert is a function to get the applicable certificate for a JSON Web Token.
func getPEMCert(token *jwt.Token) (string, error) {
cert := ""
if len(jwksBytes) == 0 {
resp, err := http.Get(fmt.Sprintf("https://%s/.well-known/jwks.json", authCfg.Domain))
if err != nil {
return cert, err
}
defer resp.Body.Close()
if jwksBytes, err = ioutil.ReadAll(resp.Body); err != nil {
return cert, err
}
}
jwks := JWKS{}
if err := json.Unmarshal(jwksBytes, &jwks); err != nil {
return cert, err
}
for k, v := range jwks.Keys[0].X5c {
if token.Header["kid"] == jwks.Keys[k].Kid {
cert = fmt.Sprintf("-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----", v)
}
}
if cert == "" {
err := errors.New("unable to find appropriate key")
return cert, err
}
return cert, nil
}
// authZero is an instance of Auth0's JWT middlware. Since it doesn't support the http.HandlerFunc sig, it is wrapped
// below; it's defined outside that function, though, so it does not get recreated every time.
var authZero = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
if checkAud := token.Claims.(jwt.MapClaims).VerifyAudience(authCfg.ClientID, false); !checkAud {
return token, errors.New("invalid audience")
}
iss := fmt.Sprintf("https://%s/", authCfg.Domain)
if checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false); !checkIss {
return token, errors.New("invalid issuer")
}
cert, err := getPEMCert(token)
if err != nil {
panic(err.Error())
}
result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
return result, nil
},
SigningMethod: jwt.SigningMethodRS256,
})
// authMiddleware is a wrapper for the Auth0 middleware above with a signature ozzo-routing recognizes.
func authMiddleware(c *routing.Context) error {
return authZero.CheckJWT(c.Response, c.Request)
}
// NewRouter returns a configured router to handle all incoming requests.
func NewRouter(cfg *AuthConfig) *routing.Router {
authCfg = cfg
router := routing.New()
router.Use(fault.Recovery(log.Printf))
for _, route := range routes {
if route.IsPublic {
router.To(route.Method, route.Pattern, route.Func)
} else {
router.To(route.Method, route.Pattern, authMiddleware, route.Func)
}
}
return router
}

View File

@ -1,99 +0,0 @@
// Package routes contains endpoint handlers for the myPrayerJournal API.
package routes
import (
"net/http"
routing "github.com/go-ozzo/ozzo-routing"
)
// Route is a route served in the application.
type Route struct {
Name string
Method string
Pattern string
Func routing.Handler
IsPublic bool
}
// Routes is the collection of all routes served in the application.
type Routes []Route
// routes is the actual list of routes for the application.
var routes = Routes{
Route{
"Journal",
http.MethodGet,
"/api/journal/",
journal,
false,
},
Route{
"AddNewRequest",
http.MethodPost,
"/api/request/",
requestAdd,
false,
},
// Must be above GetRequestByID
Route{
"GetAnsweredRequests",
http.MethodGet,
"/api/request/answered",
requestsAnswered,
false,
},
Route{
"GetRequestByID",
http.MethodGet,
"/api/request/<id>",
requestGet,
false,
},
Route{
"GetCompleteRequestByID",
http.MethodGet,
"/api/request/<id>/complete",
requestGetComplete,
false,
},
Route{
"GetFullRequestByID",
http.MethodGet,
"/api/request/<id>/full",
requestGetFull,
false,
},
Route{
"AddNewHistoryEntry",
http.MethodPost,
"/api/request/<id>/history",
requestAddHistory,
false,
},
Route{
"AddNewNote",
http.MethodPost,
"/api/request/<id>/note",
requestAddNote,
false,
},
Route{
"GetNotesForRequest",
http.MethodGet,
"/api/request/<id>/notes",
requestGetNotes,
false,
},
// keep this route last
Route{
"StaticFiles",
http.MethodGet,
"/*",
staticFiles,
true,
},
}
// ClientPrefixes is a list of known route prefixes handled by the Vue app.
var ClientPrefixes = []string{"/answered", "/journal", "/user"}

View File

@ -1,18 +0,0 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
}
}

View File

@ -1,9 +0,0 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

View File

@ -1,2 +0,0 @@
build/*.js
config/*.js

View File

@ -1,27 +0,0 @@
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}

19
src/app/.gitignore vendored
View File

@ -1,19 +0,0 @@
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
test/unit/coverage
test/e2e/reports
selenium-debug.log
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
# Auth0 settings
src/auth/auth0-variables.js

View File

@ -1,8 +0,0 @@
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 Daniel J. Summers
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,35 +0,0 @@
require('./check-versions')()
process.env.NODE_ENV = 'production'
var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf')
var spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})

View File

@ -1,48 +0,0 @@
var chalk = require('chalk')
var semver = require('semver')
var packageConfig = require('../package.json')
var shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
var versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
},
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
var warnings = []
for (var i = 0; i < versionRequirements.length; i++) {
var mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (var i = 0; i < warnings.length; i++) {
var warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}

View File

@ -1,9 +0,0 @@
/* eslint-disable */
require('eventsource-polyfill')
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
hotClient.subscribe(function (event) {
if (event.action === 'reload') {
window.location.reload()
}
})

View File

@ -1,92 +0,0 @@
require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = process.env.NODE_ENV === 'testing'
? require('./webpack.prod.conf')
: require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable
var app = express()
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
_resolve()
})
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
}
}

View File

@ -1,71 +0,0 @@
var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
exports.assetsPath = function (_path) {
var assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
var loaders = [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
var output = []
var loaders = exports.cssLoaders(options)
for (var extension in loaders) {
var loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}

View File

@ -1,18 +0,0 @@
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
}
}

View File

@ -1,75 +0,0 @@
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}

View File

@ -1,35 +0,0 @@
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// cheap-module-eval-source-map is faster for development
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})

View File

@ -1,125 +0,0 @@
var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: config.build.env
var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
}),
noParse: [/moment.js/]
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig

View File

@ -1,31 +0,0 @@
// This is the webpack config used for unit tests.
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseConfig = require('./webpack.base.conf')
var webpackConfig = merge(baseConfig, {
// use inline sourcemap for karma-sourcemap-loader
module: {
rules: utils.styleLoaders()
},
devtool: '#inline-source-map',
resolveLoader: {
alias: {
// necessary to to make lang="scss" work in test when using vue-loader's ?inject option
// see discussion at https://github.com/vuejs/vue-loader/issues/724
'scss-loader': 'sass-loader'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/test.env')
})
]
})
// no need for app entry during tests
delete webpackConfig.entry
module.exports = webpackConfig

View File

@ -1,6 +0,0 @@
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})

View File

@ -1,38 +0,0 @@
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../../public/index.html'),
assetsRoot: path.resolve(__dirname, '../../public'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

View File

@ -1,3 +0,0 @@
module.exports = {
NODE_ENV: '"production"'
}

View File

@ -1,6 +0,0 @@
var merge = require('webpack-merge')
var devEnv = require('./dev.env')
module.exports = merge(devEnv, {
NODE_ENV: '"testing"'
})

View File

@ -1,13 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>myPrayerJournal</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View File

@ -1,107 +0,0 @@
{
"name": "my-prayer-journal",
"version": "0.9.5",
"description": "myPrayerJournal - Front End",
"author": "Daniel J. Summers <daniel@bitbadger.solutions>",
"private": true,
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs",
"apistart": "cd .. && go build -o mpj-api.exe && mpj-api.exe",
"vue": "node build/build.js prod && cd .. && go build -o mpj-api.exe && mpj-api.exe"
},
"dependencies": {
"auth0-js": "^9.3.3",
"axios": "^0.18.0",
"bootstrap": "^4.0.0",
"bootstrap-vue": "^1.0.0-beta.9",
"moment": "^2.18.1",
"pug": "^2.0.1",
"vue": "^2.5.15",
"vue-awesome": "^2.3.3",
"vue-progressbar": "^0.7.3",
"vue-router": "^3.0.0",
"vue-toast": "^3.1.0",
"vuex": "^3.0.0"
},
"devDependencies": {
"autoprefixer": "^7.1.4",
"babel-core": "^6.26.0",
"babel-eslint": "^7.1.1",
"babel-loader": "^7.1.2",
"babel-plugin-istanbul": "^4.1.5",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.26.0",
"chai": "^3.5.0",
"chalk": "^2.1.0",
"chromedriver": "^2.32.3",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.0.1",
"cross-env": "^5.0.5",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.7",
"cssnano": "^3.10.0",
"eslint": "^3.19.0",
"eslint-config-standard": "^6.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^3.2.2",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
"eventsource-polyfill": "^0.9.6",
"express": "^4.15.4",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.30.1",
"http-proxy-middleware": "^0.17.3",
"inject-loader": "^3.0.1",
"karma": "^1.7.1",
"karma-coverage": "^1.1.1",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-phantomjs-shim": "^1.4.0",
"karma-sinon-chai": "^1.3.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.31",
"karma-webpack": "^2.0.2",
"lolex": "^1.5.2",
"mocha": "^3.5.3",
"nightwatch": "^0.9.12",
"opn": "^5.1.0",
"optimize-css-assets-webpack-plugin": "^2.0.0",
"ora": "^1.2.0",
"phantomjs-prebuilt": "^2.1.15",
"rimraf": "^2.6.2",
"selenium-server": "^3.5.3",
"semver": "^5.4.1",
"shelljs": "^0.7.6",
"sinon": "^2.4.1",
"sinon-chai": "^2.13.0",
"url-loader": "^0.5.8",
"vue-loader": "^12.1.0",
"vue-style-loader": "^3.0.3",
"vue-template-compiler": "^2.4.4",
"webpack": "^2.6.1",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-middleware": "^1.12.0",
"webpack-hot-middleware": "^2.19.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}

View File

@ -1,72 +0,0 @@
<template lang="pug">
#app
navigation
#content.container
router-view
vue-progress-bar
toast(ref='toast')
footer
p.text-right.text-muted
| myPrayerJournal v{{ version }}
br
em: small.
#[router-link(:to="{ name: 'PrivacyPolicy' }") Privacy Policy] &bull;
#[router-link(:to="{ name: 'TermsOfService' }") Terms of Service] &bull;
#[a(href='https://github.com/danieljsummers/myprayerjournal') Developed] and hosted by
#[a(href='https://bitbadger.solutions') Bit Badger Solutions]
</template>
<script>
'use strict'
import Navigation from './components/Navigation.vue'
import { version } from '../package.json'
export default {
name: 'app',
components: {
Navigation
},
data () {
return { version }
},
mounted () {
this.$refs.toast.setOptions({ position: 'bottom right' })
},
computed: {
toast () {
return this.$refs.toast
}
}
}
</script>
<style>
html, body {
background-color: whitesmoke;
}
body {
padding-top: 60px;
}
footer {
border-top: solid 1px lightgray;
margin-top: 1rem;
padding: 0 1rem;
}
footer p {
margin: 0;
}
a:link, a:visited {
color: #050;
}
.mpj-request-text {
white-space: pre-line;
}
.bg-mpj {
background-image: -webkit-gradient(linear, left top, left bottom, from(#050), to(whitesmoke));
background-image: -webkit-linear-gradient(top, #050, whitesmoke);
background-image: -moz-linear-gradient(top, #050, whitesmoke);
background-image: linear-gradient(to bottom, #050, whitesmoke);
}
</style>

View File

@ -1,78 +0,0 @@
import axios from 'axios'
const http = axios.create({
baseURL: `${location.protocol}//${location.host}/api/`
})
/**
* API access for myPrayerJournal
*/
export default {
/**
* Set the bearer token for all future requests
* @param {string} token The token to use to identify the user to the server
*/
setBearer: token => { http.defaults.headers.common['authorization'] = `Bearer ${token}` },
/**
* Remove the bearer token
*/
removeBearer: () => delete http.defaults.headers.common['authorization'],
/**
* Add a note for a prayer request
* @param {string} requestId The Id of the request to which the note applies
* @param {string} notes The notes to be added
*/
addNote: (requestId, notes) => http.post(`request/${requestId}/note`, { notes }),
/**
* Add a new prayer request
* @param {string} requestText The text of the request to be added
*/
addRequest: requestText => http.post('request/', { requestText }),
/**
* Get all answered requests, along with the text they had when it was answered
*/
getAnsweredRequests: () => http.get('request/answered'),
/**
* Get a prayer request (full; includes all history)
* @param {string} requestId The Id of the request to retrieve
*/
getFullRequest: requestId => http.get(`request/${requestId}/full`),
/**
* Get past notes for a prayer request
* @param {string} requestId The Id of the request for which notes should be retrieved
*/
getNotes: requestId => http.get(`request/${requestId}/notes`),
/**
* Get a prayer request (journal-style; only latest update)
* @param {string} requestId The Id of the request to retrieve
*/
getRequest: requestId => http.get(`request/${requestId}`),
/**
* Get a complete request; equivalent of "full" and "notes" combined
*/
getRequestComplete: requestId => http.get(`request/${requestId}/complete`),
/**
* Get all prayer requests and their most recent updates
*/
journal: () => http.get('journal/'),
/**
* Update a prayer request
* @param request The request (should have requestId, status, and updateText properties)
*/
updateRequest: request => http.post(`request/${request.requestId}/history`, {
status: request.status,
updateText: request.updateText
})
}

View File

@ -1,139 +0,0 @@
'use strict'
import auth0 from 'auth0-js'
import AUTH_CONFIG from './auth0-variables'
import mutations from '@/store/mutation-types'
var tokenRenewalTimeout
export default class AuthService {
constructor () {
this.login = this.login.bind(this)
this.setSession = this.setSession.bind(this)
this.logout = this.logout.bind(this)
this.isAuthenticated = this.isAuthenticated.bind(this)
}
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientId,
redirectUri: AUTH_CONFIG.appDomain + AUTH_CONFIG.callbackUrl,
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
responseType: 'token id_token',
scope: 'openid profile email'
})
login () {
this.auth0.authorize()
}
/**
* Promisified parseHash function
*/
parseHash () {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (err) {
reject(err)
} else {
resolve(authResult)
}
})
})
}
/**
* Promisified userInfo function
*
* @param token The auth token from the login result
*/
userInfo (token) {
return new Promise((resolve, reject) => {
this.auth0.client.userInfo(token, (err, user) => {
if (err) {
reject(err)
} else {
resolve(user)
}
})
})
}
handleAuthentication (store, router) {
this.parseHash()
.then(authResult => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult)
this.userInfo(authResult.accessToken)
.then(user => {
store.commit(mutations.USER_LOGGED_ON, user)
router.replace('/journal')
})
}
})
.catch(err => {
router.replace('/')
console.log(err)
alert(`Error: ${err.error}. Check the console for further details.`)
})
}
scheduleRenewal () {
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
let delay = expiresAt - Date.now()
if (delay > 0) {
tokenRenewalTimeout = setTimeout(() => {
this.renewToken()
}, delay)
}
}
setSession (authResult) {
// Set the time that the access token will expire at
let expiresAt = JSON.stringify(
authResult.expiresIn * 1000 + new Date().getTime()
)
localStorage.setItem('access_token', authResult.accessToken)
localStorage.setItem('id_token', authResult.idToken)
localStorage.setItem('expires_at', expiresAt)
this.scheduleRenewal()
}
renewToken () {
console.log('attempting renewal...')
this.auth0.renewAuth(
{
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
redirectUri: `${AUTH_CONFIG.appDomain}/static/silent.html`,
usePostMessage: true
},
(err, result) => {
if (err) {
console.log(err)
} else {
this.setSession(result)
}
}
)
}
logout (store, router) {
// Clear access token and ID token from local storage
clearTimeout(tokenRenewalTimeout)
localStorage.removeItem('access_token')
localStorage.removeItem('id_token')
localStorage.removeItem('expires_at')
localStorage.setItem('user_profile', JSON.stringify({}))
// navigate to the home route
store.commit(mutations.USER_LOGGED_OFF)
router.replace('/')
}
isAuthenticated () {
// Check whether the current time is past the access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
return new Date().getTime() < expiresAt
}
}

View File

@ -1,63 +0,0 @@
<template lang="pug">
article
page-title(title='Answered Requests')
p(v-if='!loaded') Loading answered requests...
div(v-if='loaded').mpj-answered-list
p.text-center(v-if='requests.length === 0'): em.
No answered requests found; once you have marked one as &ldquo;Answered&rdquo;, it will appear here
p.mpj-request-text(v-for='req in requests' :key='req.requestId')
| {{ req.text }}
br
br
b-btn(:to='{ name: "AnsweredDetail", params: { id: req.requestId }}'
size='sm'
variant='outline-secondary')
icon(name='search')
= ' View Full Request'
small.text-muted: em.
&nbsp; Answered #[date-from-now(:value='req.asOf')]
</template>
<script>
'use static'
import api from '@/api'
export default {
name: 'answered',
data () {
return {
requests: [],
loaded: false
}
},
computed: {
toast () {
return this.$parent.$refs.toast
}
},
async mounted () {
this.$Progress.start()
try {
const reqs = await api.getAnsweredRequests()
this.requests = reqs.data
this.$Progress.finish()
} catch (err) {
console.error(err)
this.toast.showToast('Error loading requests; check console for details', { theme: 'danger' })
this.$Progress.fail()
} finally {
this.loaded = true
}
}
}
</script>
<style>
.mpj-answered-list p {
border-top: solid 1px lightgray;
}
.mpj-answered-list p:first-child {
border-top: none;
}
</style>

View File

@ -1,82 +0,0 @@
<template lang="pug">
article
page-title(title='Answered Request')
p(v-if='!request') Loading request...
template(v-if='request')
p.
Answered {{ formatDate(answered) }} (#[date-from-now(:value='answered')]) &nbsp;
#[small: em.text-muted prayed {{ prayedCount }} times, open {{ openDays }} days]
p.mpj-request-text {{ lastText }}
b-table(small hover :fields='fields' :items='log')
template(slot='action' scope='data').
{{ data.item.status }} on #[span.text-nowrap {{ formatDate(data.item.asOf) }}]
</template>
<script>
'use strict'
import moment from 'moment'
import api from '@/api'
const asOfDesc = (a, b) => b.asOf - a.asOf
export default {
name: 'answer-detail',
props: {
id: {
type: String,
required: true
}
},
data () {
return {
request: null,
fields: [
{ key: 'action', label: 'Action' },
{ key: 'text', label: 'Update / Notes' }
]
}
},
computed: {
answered () {
return this.request.history.find(hist => hist.status === 'Answered').asOf
},
lastText () {
return this.request.history
.filter(hist => hist.text > '')
.sort(asOfDesc)[0].text
},
log () {
return (this.request.notes || [])
.map(note => ({ asOf: note.asOf, text: note.notes, status: 'Notes' }))
.concat(this.request.history)
.sort(asOfDesc)
.slice(1)
},
openDays () {
return Math.floor(
(this.answered - this.request.history.find(hist => hist.status === 'Created').asOf) / 1000 / 60 / 60 / 24)
},
prayedCount () {
return this.request.history.filter(hist => hist.status === 'Prayed').length
}
},
async mounted () {
this.$Progress.start()
try {
const req = await api.getRequestComplete(this.id)
this.request = req.data
this.$Progress.finish()
} catch (e) {
console.log(e)
this.$Progress.fail()
}
},
methods: {
formatDate (asOf) {
return moment(asOf).format('LL')
}
}
}
</script>

View File

@ -1,22 +0,0 @@
<template lang="pug">
article
page-title(title='Welcome!'
hideOnPage='true')
p &nbsp;
p.
myPrayerJournal is a place where individuals can record their prayer requests, record that they prayed for them,
update them as God moves in the situation, and record a final answer received on that request. It will also allow
individuals to review their answered prayers.
p.
This site is currently in beta, but it is open and available to the general public. To get started, simply click
the &ldquo;Log On&rdquo; link above, and log on with either a Microsoft or Google account. You can also learn more
about the site at the &ldquo;Docs&rdquo; link, also above.
</template>
<script>
'use strict'
export default {
name: 'home'
}
</script>

View File

@ -1,69 +0,0 @@
<template lang="pug">
article
page-title(:title='title')
p(v-if='isLoadingJournal') Loading your prayer journal...
template(v-if='!isLoadingJournal')
new-request
br
b-row(v-if='journal.length > 0')
request-card(v-for='request in journal'
:key='request.requestId'
:request='request'
:events='eventBus'
:toast='toast')
p.text-center(v-if='journal.length === 0'): em.
No requests found; click the &ldquo;Add a New Request&rdquo; button to add one
edit-request(:events='eventBus'
:toast='toast')
notes-edit(:events='eventBus'
:toast='toast')
full-request(:events='eventBus')
</template>
<script>
'use strict'
import Vue from 'vue'
import { mapState } from 'vuex'
import chunk from 'lodash/chunk'
import EditRequest from './request/EditRequest'
import FullRequest from './request/FullRequest'
import NewRequest from './request/NewRequest'
import NotesEdit from './request/NotesEdit'
import RequestCard from './request/RequestCard'
import actions from '@/store/action-types'
export default {
name: 'journal',
components: {
EditRequest,
FullRequest,
NewRequest,
NotesEdit,
RequestCard
},
data () {
return {
eventBus: new Vue()
}
},
computed: {
title () {
return `${this.user.given_name}&rsquo;s Prayer Journal`
},
journalCardRows () {
return chunk(this.journal, 3)
},
toast () {
return this.$parent.$refs.toast
},
...mapState(['user', 'journal', 'isLoadingJournal'])
},
async created () {
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
this.toast.showToast(`Loaded ${this.journal.length} prayer requests`, { theme: 'success' })
}
}
</script>

View File

@ -1,49 +0,0 @@
<template lang="pug">
b-navbar(toggleable='sm'
type='dark'
variant='mpj'
fixed='top')
b-nav-toggle(target='nav_collapse')
b-navbar-brand(to='/')
span(style='font-weight:100;') my
span(style='font-weight:600;') Prayer
span(style='font-weight:700;') Journal
b-collapse#nav_collapse(is-nav)
b-navbar-nav
b-nav-item(v-if='isAuthenticated'
to='/journal') Journal
b-nav-item(v-if='isAuthenticated'
to='/answered') Answered
b-nav-item(v-if='isAuthenticated'): a(@click.stop='logOff()') Log Off
b-nav-item(v-if='!isAuthenticated'): a(@click.stop='logOn()') Log On
b-nav-item(href='https://danieljsummers.github.io/myPrayerJournal/'
target='_blank'
@click.stop='') Docs
</template>
<script>
'use strict'
import { mapState } from 'vuex'
import AuthService from '@/auth/AuthService'
export default {
name: 'navigation',
data () {
return {
auth0: new AuthService()
}
},
computed: {
...mapState([ 'isAuthenticated' ])
},
methods: {
logOn () {
this.auth0.login()
},
logOff () {
this.auth0.logout(this.$store, this.$router)
}
}
}
</script>

View File

@ -1,52 +0,0 @@
<script>
'use strict'
import moment from 'moment'
export default {
name: 'date-from-now',
props: {
tag: {
type: String,
default: 'span'
},
value: {
type: Number,
default: 0
},
interval: {
type: Number,
default: 10000
}
},
data () {
const dt = moment(this.value)
return {
fromNow: dt.fromNow(),
actual: dt.format('LLLL'),
intervalId: null
}
},
mounted () {
this.intervalId = setInterval(this.updateFromNow, this.interval)
this.$watch('value', this.updateFromNow)
},
beforeDestroy () {
clearInterval(this.intervalId)
},
methods: {
updateFromNow () {
let newFromNow = moment(this.value).fromNow()
if (newFromNow !== this.fromNow) this.fromNow = newFromNow
}
},
render (createElement) {
return createElement(this.tag, {
domProps: {
title: this.actual,
innerText: this.fromNow
}
})
}
}
</script>

View File

@ -1,35 +0,0 @@
<template lang="pug">
h2.mpj-page-title(v-if='!hideOnPage'
v-html='title')
</template>
<script>
export default {
name: 'page-title',
props: {
title: {
type: String,
required: true
},
hideOnPage: {
type: Boolean,
default: false
}
},
watch: {
title () {
document.title = `${this.title.replace('&rsquo;', "'")} « myPrayerJournal`
}
},
created () {
document.title = `${this.title.replace('&rsquo;', "'")} « myPrayerJournal`
}
}
</script>
<style scoped>
.mpj-page-title {
border-bottom: solid 1px lightgray;
margin-bottom: 20px;
}
</style>

View File

@ -1,54 +0,0 @@
<template lang="pug">
article
page-title(title='Privacy Policy')
p: small: em (as of May 21, 2018)
p.
The nature of the service is one where privacy is a must. The items below will help you understand the data we
collect, access, and store on your behalf as you use this service.
hr
h3 Third Party Services
p.
myPrayerJournal utilizes a third-party authentication and identity provider. You should familiarize yourself with
the privacy policy for #[a(href='https://auth0.com/privacy' target='_blank') Auth0], as well as your chosen provider
(#[a(href='https://privacy.microsoft.com/en-us/privacystatement' target='_blank') Microsoft] or
#[a(href='https://policies.google.com/privacy' target='_blank') Google]).
hr
h3 What We Collect
h4 Identifying Data
ul
li.
The only identifying data myPrayerJournal stores is the subscriber (&ldquo;sub&rdquo;) field from the token we
receive from Auth0, once you have signed in through their hosted service. All information is associated with you
via this field.
li.
While you are signed in, within your browser, the service has access to your first and last names, along with a
URL to the profile picture (provided by your selected identity provider). This information is not transmitted to
the server, and is removed when &ldquo;Log Off&rdquo; is clicked.
h4 User Provided Data
ul
li.
myPrayerJournal stores the information you provide, including the text of prayer requests, updates, and notes;
and the date/time when certain actions are taken.
hr
h3 How Your Data Is Accessed / Secured
ul
li.
Your provided data is returned to you, as required, to display your journal or your answered requests.
On the server, it is stored in a controlled-access database.
li.
Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are
preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months. These backups are
stored in a private cloud data repository.
li.
The data collected and stored is the absolute minimum necessary for the functionality of the service. There are
no plans to &ldquo;monetize&rdquo; this service, and storing the minimum amount of information means that the
data we have is not interesting to purchasers (or those who may have more nefarious purposes).
li Access to servers and backups is strictly controlled and monitored for unauthorized access attempts.
hr
h3 Removing Your Data
p.
At any time, you may choose to discontinue using this service. Both Microsoft and Google provide ways to revoke
access from this application. However, if you want your data removed from the database, please contact daniel at
bitbadger.solutions (via e-mail, replacing at with @) prior to doing so, to ensure we can determine which
subscriber ID belongs to you.
</template>

View File

@ -1,35 +0,0 @@
<template lang="pug">
article
page-title(title='Terms of Service')
p: small: em (as of May 21, 2018)
h3 1. Acceptance of Terms
p.
By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are
responsible to ensure that your use of this site complies with all applicable laws. Your continued use of this
site implies your acceptance of these terms.
h3 2. Description of Service and Registration
p.
myPrayerJournal is a service that allows individuals to enter and amend their prayer requests. It requires no
registration by itself, but access is granted based on a successful login with an external identity provider. See
#[router-link(:to="{ name: 'PrivacyPolicy' }") our privacy policy] for details on how that information is accessed
and stored.
h3 3. Third Party Services
p.
This service utilizes a third-party service provider for identity management. Review the terms of service for
#[a(href='https://auth0.com/terms' target='_blank') Auth0], as well as those for the selected authorization
provider (#[a(href='https://www.microsoft.com/en-us/servicesagreement' target='_blank') Microsoft] or
#[a(href='https://policies.google.com/terms' target='_blank') Google]).
h3 4. Liability
p.
This service is provided "as is", and no warranty (express or implied) exists. The service and its developers may
not be held liable for any damages that may arise through the use of this service.
h3 5. Updates to Terms
p.
These terms and conditions may be updated at any time, and this service does not have the capability to notify
users when these change. The date at the top of the page will be updated when any of the text of these terms is
updated.
hr
p.
You may also wish to review our #[router-link(:to="{ name: 'PrivacyPolicy' }") privacy policy] to learn how we
handle your data.
</template>

View File

@ -1,89 +0,0 @@
<template lang="pug">
b-modal(v-model='editVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Edit Prayer Request'
@edit='openDialog()'
@shows='focusRequestText')
b-form
b-form-group(label='Prayer Request'
label-for='request_text')
b-textarea#request_text(ref='toFocus'
v-model='form.requestText'
:rows='10'
@blur='trimText()')
b-form-group(label='Also Mark As')
b-radio-group(v-model='form.status'
buttons)
b-radio(value='Updated') Updated
b-radio(value='Prayed') Prayed
b-radio(value='Answered') Answered
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveRequest()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'edit-request',
props: {
toast: { required: true },
events: { required: true }
},
data () {
return {
editVisible: false,
form: {
requestId: '',
requestText: '',
status: 'Updated'
}
}
},
created () {
this.events.$on('edit', this.openDialog)
},
methods: {
closeDialog () {
this.form.requestId = ''
this.form.requestText = ''
this.form.status = 'Updated'
this.editVisible = false
},
focusRequestText (e) {
this.$refs.toFocus.focus()
},
openDialog (request) {
this.form.requestId = request.requestId
this.form.requestText = request.text
this.editVisible = true
this.focusRequestText(null)
},
trimText () {
this.form.requestText = this.form.requestText.trim()
},
async saveRequest () {
await this.$store.dispatch(actions.UPDATE_REQUEST, {
progress: this.$Progress,
requestId: this.form.requestId,
updateText: this.form.requestText,
status: this.form.status
})
if (this.form.status === 'Answered') {
this.toast.showToast('Request updated and removed from active journal', { theme: 'success' })
} else {
this.toast.showToast('Request updated', { theme: 'success' })
}
this.closeDialog()
}
}
}
</script>

View File

@ -1,57 +0,0 @@
<template lang="pug">
span
b-modal(v-model='historyVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Prayer Request History'
@shows='focusRequestText')
b-list-group(v-if='null !== full'
flush)
full-request-history(v-for='item in full.history'
:key='item.asOf'
:history='item')
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='closeDialog()') Close
</template>
<script>
'use strict'
import FullRequestHistory from './FullRequestHistory'
import api from '@/api'
export default {
name: 'full-request',
components: {
FullRequestHistory
},
props: {
events: { required: true }
},
data () {
return {
historyVisible: false,
full: null
}
},
created () {
this.events.$on('full', this.openDialog)
},
methods: {
closeDialog () {
this.full = null
this.historyVisible = false
},
async openDialog (requestId) {
this.historyVisible = true
this.$Progress.start()
const req = await api.getFullRequest(requestId)
this.full = req.data
this.$Progress.finish()
}
}
}
</script>

View File

@ -1,28 +0,0 @@
<template lang="pug">
b-list-group-item
| {{ history.status }}
|
small.text-muted {{ asOf }}
div(v-if='hasText').mpj-request-text {{ history.text }}
</template>
<script>
'use strict'
import moment from 'moment'
export default {
name: 'full-request-history',
props: {
history: { required: true }
},
computed: {
asOf () {
return moment(this.history.asOf).fromNow()
},
hasText () {
return this.history.text.length > 0
}
}
}
</script>

View File

@ -1,71 +0,0 @@
<template lang="pug">
div
b-btn(@click='openDialog()' size='sm' variant='primary')
icon(name='plus')
| &nbsp; Add a New Request
b-modal(v-model='showNewVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Add a New Prayer Request'
@shown='focusRequestText')
b-form
b-form-group(label='Prayer Request'
label-for='request_text')
b-textarea#request_text(ref='toFocus'
v-model='form.requestText'
:rows='10'
@blur='trimText()')
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveRequest()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
toast(ref='toast')
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'new-request',
data () {
return {
showNewVisible: false,
form: {
requestText: ''
},
formLabelWidth: '120px'
}
},
mounted () {
this.$refs.toast.setOptions({ position: 'bottom right' })
},
methods: {
closeDialog () {
this.form.requestText = ''
this.showNewVisible = false
},
focusRequestText (e) {
this.$refs.toFocus.focus()
},
openDialog () {
this.showNewVisible = true
},
trimText () {
this.form.requestText = this.form.requestText.trim()
},
async saveRequest () {
await this.$store.dispatch(actions.ADD_REQUEST, {
progress: this.$Progress,
requestText: this.form.requestText
})
this.$refs.toast.showToast('New prayer request added', { theme: 'success' })
this.closeDialog()
}
}
}
</script>

View File

@ -1,116 +0,0 @@
<template lang="pug">
b-modal(v-model='notesVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Add Notes to Prayer Request'
@edit='openDialog()'
@shows='focusNotes')
b-form
b-form-group(label='Notes'
label-for='notes')
b-textarea#notes(ref='toFocus'
v-model='form.notes'
:rows='10'
@blur='trimText()')
div(v-if='hasPriorNotes')
p.text-center: strong Prior Notes for This Request
b-list-group(flush)
b-list-group-item(v-for='note in priorNotes'
:key='note.asOf')
small.text-muted: date-from-now(:value='note.asOf')
br
div.mpj-request-text {{ note.notes }}
div(v-else-if='noPriorNotes').text-center.text-muted There are no prior notes for this request
div(v-else).text-center
b-btn(variant='outline-secondary'
@click='loadNotes()') Load Prior Notes
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveNotes()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
</template>
<script>
'use strict'
import api from '@/api'
export default {
name: 'notes-edit',
props: {
toast: { required: true },
events: { required: true }
},
data () {
return {
notesVisible: false,
form: {
requestId: '',
notes: ''
},
priorNotes: [],
priorNotesLoaded: false
}
},
computed: {
hasPriorNotes () {
return this.priorNotesLoaded && this.priorNotes.length > 0
},
noPriorNotes () {
return this.priorNotesLoaded && this.priorNotes.length === 0
}
},
created () {
this.events.$on('notes', this.openDialog)
},
methods: {
closeDialog () {
this.form.requestId = ''
this.form.notes = ''
this.priorNotes = []
this.priorNotesLoaded = false
this.notesVisible = false
},
focusNotes (e) {
this.$refs.toFocus.focus()
},
async loadNotes () {
this.$Progress.start()
try {
const notes = await api.getNotes(this.form.requestId)
this.priorNotes = notes.data
console.log(this.priorNotes)
this.$Progress.finish()
} catch (e) {
console.error(e)
this.$Progress.fail()
} finally {
this.priorNotesLoaded = true
}
},
openDialog (request) {
this.form.requestId = request.requestId
this.notesVisible = true
this.focusNotes(null)
},
async saveNotes () {
this.$Progress.start()
try {
await api.addNote(this.form.requestId, this.form.notes)
this.$Progress.finish()
this.toast.showToast('Added notes', { theme: 'success' })
this.closeDialog()
} catch (e) {
console.error(e)
this.$Progress.fail()
}
},
trimText () {
this.form.notes = this.form.notes.trim()
}
}
}
</script>

View File

@ -1,59 +0,0 @@
<template lang="pug">
b-col(md='6' lg='4')
.mpj-request-card
b-card-header.text-center.py-1.
#[b-btn(@click='markPrayed()' variant='outline-primary' title='Pray' size='sm'): icon(name='check')]
#[b-btn(@click.stop='showEdit()' variant='outline-secondary' title='Edit' size='sm'): icon(name='pencil')]
#[b-btn(@click.stop='showNotes()' variant='outline-secondary' title='Add Notes' size='sm'): icon(name='file-text-o')]
#[b-btn(@click.stop='showFull()' variant='outline-secondary' title='View Full Request' size='sm'): icon(name='search')]
b-card-body.p-0
p.card-text.mpj-request-text.mb-1.px-3.pt-3
| {{ request.text }}
p.card-text.p-0.pr-1.text-right: small.text-muted: em
= '(last activity '
date-from-now(:value='request.asOf')
| )
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'request-card',
props: {
request: { required: true },
toast: { required: true },
events: { required: true }
},
methods: {
async markPrayed () {
await this.$store.dispatch(actions.UPDATE_REQUEST, {
progress: this.$Progress,
requestId: this.request.requestId,
status: 'Prayed',
updateText: ''
})
this.toast.showToast('Request marked as prayed', { theme: 'success' })
},
showEdit () {
this.events.$emit('edit', this.request)
},
showFull () {
this.events.$emit('full', this.request.requestId)
},
showNotes () {
this.events.$emit('notes', this.request)
}
}
}
</script>
<style>
.mpj-request-card {
border: solid 1px darkgray;
border-radius: 5px;
margin-bottom: 15px;
}
</style>

View File

@ -1,20 +0,0 @@
<template lang="pug">
article
pageTitle(title='Logging On')
p Logging you on...
</template>
<script>
'use strict'
import AuthService from '@/auth/AuthService'
export default {
name: 'log-on',
created () {
this.$Progress.start()
new AuthService().handleAuthentication(this.$store, this.$router)
// Auth service redirects to dashboard, which restarts the progress bar
}
}
</script>

View File

@ -1,52 +0,0 @@
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import Icon from 'vue-awesome/components/Icon'
import VueProgressBar from 'vue-progressbar'
import VueToast from 'vue-toast'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'vue-toast/dist/vue-toast.min.css'
// Only import the icons we need; the whole set is ~500K!
import 'vue-awesome/icons/check'
import 'vue-awesome/icons/file-text-o'
import 'vue-awesome/icons/pencil'
import 'vue-awesome/icons/plus'
import 'vue-awesome/icons/search'
import App from './App'
import router from './router'
import store from './store'
import DateFromNow from './components/common/DateFromNow'
import PageTitle from './components/common/PageTitle'
Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(VueProgressBar, {
color: 'yellow',
failedColor: 'red',
height: '5px',
transition: {
speed: '0.2s',
opacity: '0.6s',
termination: 1000
}
})
Vue.component('icon', Icon)
Vue.component('date-from-now', DateFromNow)
Vue.component('page-title', PageTitle)
Vue.component('toast', VueToast)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})

View File

@ -1,54 +0,0 @@
import Vue from 'vue'
import Router from 'vue-router'
import Answered from '@/components/Answered'
import AnsweredDetail from '@/components/AnsweredDetail'
import Home from '@/components/Home'
import Journal from '@/components/Journal'
import LogOn from '@/components/user/LogOn'
import PrivacyPolicy from '@/components/legal/PrivacyPolicy'
import TermsOfService from '@/components/legal/TermsOfService'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/answered/:id',
name: 'AnsweredDetail',
component: AnsweredDetail,
props: true
},
{
path: '/answered',
name: 'Answered',
component: Answered
},
{
path: '/journal',
name: 'Journal',
component: Journal
},
{
path: '/legal/privacy-policy',
name: 'PrivacyPolicy',
component: PrivacyPolicy
},
{
path: '/legal/terms-of-service',
name: 'TermsOfService',
component: TermsOfService
},
{
path: '/user/log-on',
name: 'LogOn',
component: LogOn
}
]
})

View File

@ -1,10 +0,0 @@
'use strict'
export default {
/** Action to add a prayer request (pass request text) */
ADD_REQUEST: 'add-request',
/** Action to load the user's prayer journal */
LOAD_JOURNAL: 'load-journal',
/** Action to update a request */
UPDATE_REQUEST: 'update-request'
}

View File

@ -1,116 +0,0 @@
import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api'
import AuthService from '@/auth/AuthService'
import mutations from './mutation-types'
import actions from './action-types'
Vue.use(Vuex)
this.auth0 = new AuthService()
const logError = function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request)
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message)
}
console.log(error.config)
}
export default new Vuex.Store({
state: {
user: JSON.parse(localStorage.getItem('user_profile') || '{}'),
isAuthenticated: (() => {
this.auth0.scheduleRenewal()
if (this.auth0.isAuthenticated()) {
api.setBearer(localStorage.getItem('id_token'))
}
return this.auth0.isAuthenticated()
})(),
journal: {},
isLoadingJournal: false
},
mutations: {
[mutations.LOADING_JOURNAL] (state, flag) {
state.isLoadingJournal = flag
},
[mutations.LOADED_JOURNAL] (state, journal) {
state.journal = journal
},
[mutations.REQUEST_ADDED] (state, newRequest) {
state.journal.push(newRequest)
},
[mutations.REQUEST_UPDATED] (state, request) {
let jrnl = state.journal.filter(it => it.requestId !== request.requestId)
if (request.lastStatus !== 'Answered') jrnl.push(request)
state.journal = jrnl
},
[mutations.USER_LOGGED_OFF] (state) {
state.user = {}
api.removeBearer()
state.isAuthenticated = false
},
[mutations.USER_LOGGED_ON] (state, user) {
localStorage.setItem('user_profile', JSON.stringify(user))
state.user = user
api.setBearer(localStorage.getItem('id_token'))
state.isAuthenticated = true
}
},
actions: {
async [actions.ADD_REQUEST] ({ commit }, { progress, requestText }) {
progress.start()
try {
const newRequest = await api.addRequest(requestText)
commit(mutations.REQUEST_ADDED, newRequest.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
}
},
async [actions.LOAD_JOURNAL] ({ commit }, progress) {
commit(mutations.LOADED_JOURNAL, {})
progress.start()
commit(mutations.LOADING_JOURNAL, true)
api.setBearer(localStorage.getItem('id_token'))
try {
const jrnl = await api.journal()
commit(mutations.LOADED_JOURNAL, jrnl.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
} finally {
commit(mutations.LOADING_JOURNAL, false)
}
},
async [actions.UPDATE_REQUEST] ({ commit }, { progress, requestId, status, updateText }) {
progress.start()
try {
await api.updateRequest({ requestId, status, updateText })
const request = await api.getRequest(requestId)
commit(mutations.REQUEST_UPDATED, request.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
}
}
},
getters: {},
modules: {}
})

View File

@ -1,16 +0,0 @@
'use strict'
export default {
/** Mutation for when the user's prayer journal is being loaded */
LOADING_JOURNAL: 'loading-journal',
/** Mutation for when the user's prayer journal has been loaded */
LOADED_JOURNAL: 'journal-loaded',
/** Mutation for adding a new prayer request (pass text) */
REQUEST_ADDED: 'request-added',
/** Mutation to replace a prayer request at the top of the current journal */
REQUEST_UPDATED: 'request-updated',
/** Mutation for logging a user off */
USER_LOGGED_OFF: 'user-logged-off',
/** Mutation for logging a user on (pass user) */
USER_LOGGED_ON: 'user-logged-on'
}

View File

@ -1,22 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.auth0.com/js/auth0/8.9/auth0.min.js"></script>
<script>
var webAuth = new auth0.WebAuth({
domain: 'djs-consulting.auth0.com',
clientID: 'Of2s0RQCQ3mt3dwIkOBY5h85J9sXbF2n',
scope: 'openid profile email',
responseType: 'token id_token',
redirectUri: location.protocol + '//' + location.host + '/static/silent.html'
})
</script>
<script>
webAuth.parseHash(window.location.hash, function (err, response) {
parent.postMessage(err || response, location.protocol + '//' + location.host);
})
</script>
</head>
<body></body>
</html>

View File

@ -1,26 +0,0 @@
// A custom Nightwatch assertion.
// the name of the method is the filename.
// can be used in tests like this:
//
// browser.assert.elementCount(selector, count)
//
// for how to write custom assertions see
// http://nightwatchjs.org/guide#writing-custom-assertions
exports.assertion = function (selector, count) {
this.message = 'Testing if element <' + selector + '> has count: ' + count
this.expected = count
this.pass = function (val) {
return val === this.expected
}
this.value = function (res) {
return res.value
}
this.command = function (cb) {
var self = this
return this.api.execute(function (selector) {
return document.querySelectorAll(selector).length
}, [selector], function (res) {
cb.call(self, res)
})
}
}

View File

@ -1,46 +0,0 @@
require('babel-register')
var config = require('../../config')
// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
src_folders: ['test/e2e/specs'],
output_folder: 'test/e2e/reports',
custom_assertions_path: ['test/e2e/custom-assertions'],
selenium: {
start_process: true,
server_path: require('selenium-server').path,
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': require('chromedriver').path
}
},
test_settings: {
default: {
selenium_port: 4444,
selenium_host: 'localhost',
silent: true,
globals: {
devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port)
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}

View File

@ -1,33 +0,0 @@
// 1. start the dev server using production config
process.env.NODE_ENV = 'testing'
var server = require('../../build/dev-server.js')
server.ready.then(() => {
// 2. run the nightwatch test suite against it
// to run in additional browsers:
// 1. add an entry in test/e2e/nightwatch.conf.json under "test_settings"
// 2. add it to the --env flag below
// or override the environment flag, for example: `npm run e2e -- --env chrome,firefox`
// For more information on Nightwatch's config file, see
// http://nightwatchjs.org/guide#settings-file
var opts = process.argv.slice(2)
if (opts.indexOf('--config') === -1) {
opts = opts.concat(['--config', 'test/e2e/nightwatch.conf.js'])
}
if (opts.indexOf('--env') === -1) {
opts = opts.concat(['--env', 'chrome'])
}
var spawn = require('cross-spawn')
var runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' })
runner.on('exit', function (code) {
server.close()
process.exit(code)
})
runner.on('error', function (err) {
server.close()
throw err
})
})

View File

@ -1,19 +0,0 @@
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function (browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to Your Vue.js App')
.assert.elementCount('img', 1)
.end()
}
}

View File

@ -1,9 +0,0 @@
{
"env": {
"mocha": true
},
"globals": {
"expect": true,
"sinon": true
}
}

View File

@ -1,13 +0,0 @@
import Vue from 'vue'
Vue.config.productionTip = false
// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/)
testsContext.keys().forEach(testsContext)
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/)
srcContext.keys().forEach(srcContext)

View File

@ -1,33 +0,0 @@
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,48 +0,0 @@
// myPrayerJournal API Server
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/danieljsummers/myPrayerJournal/src/api/data"
"github.com/danieljsummers/myPrayerJournal/src/api/routes"
)
// Web contains configuration for the web server.
type Web struct {
Port string `json:"port"`
}
// Settings contains configuration for the myPrayerJournal API.
type Settings struct {
Data *data.Settings `json:"data"`
Web *Web `json:"web"`
Auth *routes.AuthConfig `json:"auth"`
}
// readSettings parses the JSON configuration file into the Settings struct.
func readSettings(f string) *Settings {
config, err := os.Open(f)
if err != nil {
log.Fatal(err)
}
defer config.Close()
settings := Settings{}
if err = json.NewDecoder(config).Decode(&settings); err != nil {
log.Fatal(err)
}
return &settings
}
func main() {
cfg := readSettings("config.json")
if ok := data.Connect(cfg.Data); !ok {
log.Fatal("Unable to connect to database; exiting")
}
data.EnsureDB()
log.Printf("myPrayerJournal API listening on %s", cfg.Web.Port)
log.Fatal(http.ListenAndServe(cfg.Web.Port, routes.NewRouter(cfg.Auth)))
}