Files
habitica/website/server/controllers/api-v3/challenges.js
Kalista Payne 384fb505c1 Privacy Controls (#15492)
* WIP(privacy): start of banner

* WIP(privacy): layout rough

* WIP(privacy): mobile layout, add modal

* fix(privacy): implement toggle disable and setting row fold

* fix(privacy): clean up a couple of styles

* fix(privacy): adjust banner width at mobile sizes

* WIP(privacy): remove Loggly echo of Amplitude data

* fix(banners): account for privacy in snackbar position

* WIP(privacy): dismiss banner

* chore(analytics): update to maintaned GA4 library

* fix(tests): lint, misuse of apiError

* fix(analytics): add debug mode

* fix(analytics): load new library on client

* WIP(privacy): gtag.js based implementation

* fix(analytics): lint issues

* fix(lint): one more unused

* fix(lint): client errors

* feat(privacy): draft workflows

* fix(analytics): linting, send needed user values

* fix(tests): use mock analytics service in test env

* fix(tests): restore previous logic for node env

* feat(intro): jump to page 2 onboarding

* WIP(auth): revisions to registration flow

* WIP(privacy): landing page and banner revisions

* WIP(signup): added new username, tos, privacy state

* fix(signup): revert debugging logic

* WIP(signup): add defaulting and checkbox

* wip(signup): move social auth behind username screen

* Squashed commit of the following:

commit ca0a238e5f008525ed154c5eaf12e44f2fc22b00
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed May 7 12:17:20 2025 +0200

    make emails lowercase

commit a2ce748558ce9134e6825208a7e66d78e720202e
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed Apr 9 13:27:01 2025 +0200

    remove unused import

commit cc6ce6c388d9693cf192c4bea733931fc8c31c37
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed Apr 9 13:13:03 2025 +0200

    add tests for new api route

commit 0d40a6230b548625482aa9f6831c93ed9d62533a
Author: Kalista Payne <sabrecat@gmail.com>
Date:   Wed Jun 18 15:50:22 2025 -0500

    update social tests

commit 79177d6754589b9e54682af8a531b63f60215dab
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed Apr 9 10:21:51 2025 +0200

    new api route to check if an email is available

commit 11df73fe07eeb730c2a95593e18e14a931f52429
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed Apr 9 10:21:39 2025 +0200

    Add field to not register social account when called

* Squashed commit of the following:

commit b8a2f0b8ee
Author: CuriousMagpie <eilatan@gmail.com>
Date:   Thu Jun 20 17:18:30 2024 -0400

    update privacy policy

* fix(vite): import syntax

* feat(auth): precheck on defaulted username

* feat(auth): add store action for check-email

* feat(auth): check email before proceeding

* WIP(login): refactor username screen

* WIP(auth): complete login/reg flow

* fix(auth): filter out expected 404

* fix(login): use allowRegister with Apple
and add z-index to component

* fix(login): style corrections and email passthru

* Fix edgecase

Signed-off-by: Kalista Payne <sabrecat@gmail.com>

* fix(auth): correct error behaviors

* fix(auth): rewire Apple auth

* make check-email check for restricted domains

Signed-off-by: Kalista Payne <kalista@habitica.com>

* fix(signup): all the style

* fix(express): return when responding

* fix(error): reduce specificity for restricted domain issue

* fix apple auth

Signed-off-by: Kalista Payne <kalista@habitica.com>

* fix(signup): change from blur to 500ms debounce

* fix(login): add missing 200 response in Apple flow

* fix(signup): more reconciliation with @phillipthelen's work

* fix(signup): now using token not code

* fix(reg): don't bail on Apple if we're allowing reg

* fix(auth): more reconciliation with @phillipthelen code

* feat(copy): privacy policy updates

* fix(copy): replace placeholder

* fix(vue): use Vite syntax for scss import

* fix(static): corrections to copy and css

* chore(style): remove excess whitespace

* use correct error

Signed-off-by: Kalista Payne <kalista@habitica.com>

* fix(layout): inputs, add privacy banner

* fix(login): button hover, more validation states

* fix(login): further layout and UX corrections

* fix(static): add back containing div for show/hide

* fix(apple): clean out Apple token

* fix(settings): only change preference on save

* fix(settings): correct save/cancel behavior

* fix(layout): consistent use of header/footer

* fix(layout): reposition mountains for reg/login/forgot

* fix(signup): partial rollback of /username route

* refactor(signup): move /username to page

* fix(apple): don't overwrite reg method

* fix(username): don't skip empty validation

* fix(input): don't show valid if no username

* fix(login): clean out Apple token if using another method

* fix(apple): possible race with token

* fix(tests): some housekeeping

* fix(config): copypasta

* fix(lint): various cleanup

* fix(lint): line squeeze

* fix(lint): one more v-for

* fix(groups): funnel invite flow to new username page

* Squashed commit of the following:

commit 3c5ba4bf24e4bb7996786520101f27ad66405bce
Author: Kalista Payne <kalista@habitica.com>
Date:   Mon Aug 18 14:38:31 2025 -0500

    fix(privacy): update link ref

commit 9d216f623b
Author: Kalista Payne <kalista@habitica.com>
Date:   Mon Aug 18 14:18:22 2025 -0500

    fix(privacy-tos): copy edits cont'd

commit d744f47140
Author: Kalista Payne <kalista@habitica.com>
Date:   Mon Aug 18 13:43:22 2025 -0500

    fix(privacy): copy edits and ToC reflow

commit 2c3c3fc9ce
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Aug 18 18:46:24 2025 +0200

    lint

commit cf363034d5
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Aug 18 18:34:54 2025 +0200

    fix link

commit 3afacd2c05
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Aug 18 18:34:42 2025 +0200

    add updated terms

commit 258b722499
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Aug 18 17:58:42 2025 +0200

    put back button to show/hide third party info

commit 2992e0299b
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Aug 18 17:58:32 2025 +0200

    minor edits

commit bb5e252299
Author: Kalista Payne <kalista@habitica.com>
Date:   Sun Aug 17 21:01:50 2025 -0500

    fix(privacy): update Section 3

commit c79af7baa8
Author: Kalista Payne <kalista@habitica.com>
Date:   Fri Aug 15 17:28:49 2025 -0500

    fix(privacy): various copy edits

commit 100f2f4574
Author: Phillip Thelen <phillip@habitica.com>
Date:   Fri Aug 15 11:37:37 2025 +0200

    add newline

commit 11d1cfd0d9
Author: Phillip Thelen <phillip@habitica.com>
Date:   Fri Aug 15 11:10:01 2025 +0200

    update privacy policy

commit 59b99badf3
Author: Kalista Payne <kalista@habitica.com>
Date:   Fri Aug 8 14:04:19 2025 -0500

    5.38.2

commit 78daeb4191
Author: Kalista Payne <kalista@habitica.com>
Date:   Fri Aug 8 13:36:19 2025 -0500

    fix(apple): don't run auth middleware during redirect

commit 93f8d60903
Author: Weblate <noreply@weblate.org>
Date:   Fri Aug 8 10:12:25 2025 +0200

    Translated using Weblate (German)

    Currently translated at 99.4% (185 of 186 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 100.0% (186 of 186 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (186 of 186 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (54 of 54 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (243 of 243 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (15 of 15 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (47 of 47 strings)

    Translated using Weblate (Dutch)

    Currently translated at 78.0% (2643 of 3385 strings)

    Translated using Weblate (Dutch)

    Currently translated at 40.8% (100 of 245 strings)

    Translated using Weblate (Polish)

    Currently translated at 89.9% (233 of 259 strings)

    Translated using Weblate (Dutch)

    Currently translated at 67.5% (175 of 259 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (110 of 110 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 20.8% (51 of 245 strings)

    Translated using Weblate (Turkish)

    Currently translated at 65.9% (60 of 91 strings)

    Translated using Weblate (Turkish)

    Currently translated at 65.9% (60 of 91 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 17.9% (44 of 245 strings)

    Co-authored-by: FingerTiao <787170918@qq.com>
    Co-authored-by: Jaime Martí <jaumemarti77@icloud.com>
    Co-authored-by: Karmelkowy <kicimeow.karmelio@gmail.com>
    Co-authored-by: Linsey Dunya Pastoor <sekai.creations@gmail.com>
    Co-authored-by: Mete Olmez <metezori27@gmail.com>
    Co-authored-by: Sefa Uğurlu <ugurlusefa2@gmail.com>
    Co-authored-by: Summer_GUI <heyang94@163.com>
    Co-authored-by: Toro Mor <thomas.bizer@gmx.de>
    Co-authored-by: Weblate <noreply@weblate.org>
    Co-authored-by: innnko <ayakabooker@gmail.com>
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/challenge/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/communityguidelines/tr/
    Translate-URL: https://translate.habitica.com/projects/habitica/contrib/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/death/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/defaulttasks/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/nl/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/zh_Hant/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/zh_Hans/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/nl/
    Translate-URL: https://translate.habitica.com/projects/habitica/generic/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/nl/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/pl/
    Translation: Habitica/Backgrounds
    Translation: Habitica/Challenge
    Translation: Habitica/Communityguidelines
    Translation: Habitica/Contrib
    Translation: Habitica/Death
    Translation: Habitica/Defaulttasks
    Translation: Habitica/Faq
    Translation: Habitica/Front
    Translation: Habitica/Gear
    Translation: Habitica/Generic
    Translation: Habitica/Settings

commit eb16fec41e
Author: Phillip Thelen <phillip@habitica.com>
Date:   Wed Aug 6 22:08:07 2025 +0200

    Add interface to block ip-addresses or clients due to abuse (#15484)

    * Read IP blocks from database

    * begin building general blocking solution

    * add new frontend files

    * Add UI for managing blockers

    * correctly reset local data after creating blocker

    * Tweak wording

    * Add UI for managing blockers

    * restructure admin pages

    * improve test coverage

    * Improve blocker UI

    * add blocker to block emails from registration

    * lint fix

    * fix

    * lint fixes

    * fix import

    * add new permission for managing blockers

    * improve permission check

    * fix managing permissions from admin

    * improve navbar display for non fullAccess admin

    * update block error strings

    * lint fix

    * add option to errorHandler to skip logging

    * validate blocker value during input

    * improve blocker form display

    * chore(subproj): reconcile habitica-images

    * fix(scripts): use same Mongo version for dev/test

    * fix(whitespace): eof

    * documentation improvements

    * remove nconf import

    * remove old test

    ---------

    Co-authored-by: Kalista Payne <kalista@habitica.com>
    Co-authored-by: Kalista Payne <sabrecat@gmail.com>

commit 47d832bf12
Author: Fiz <34069775+Hafizzle@users.noreply.github.com>
Date:   Tue Aug 5 15:12:44 2025 -0500

    Add backend support for Hydra mount (#15482)

    * chore: update time travelers shop to display seasonal backgrounds

    * chore: update time travelers banner (note CSS borken rn)

    * chore: fix borken CSS and update logic in shop

    * chore: added isSubscribed function, not working

    * chore: isSubscribed working but no bg for subscribers

    * chore: logic and css updates

    * chore: update habitica-images

    * chore: add check for trinket

    * chore: more time traveler shop logicking

    * Add backend support for Hydra mount

    - Add Dragon-Hydra to special mounts in stable.js
      - Configure as contributor level 7 reward with canFind: true
      - Add GIF format support for mount sprites
      - Enable admin panel granting capability

    * Fix Vue template errors in timeTravelers component

    * Fix duplicate template block in timeTravelers component

    * add CSS for Hydra mount GIF sprites

    Added CSS rules for Mount_Head_Dragon-Hydra and Mount_Body_Dragon-Hydra GIF sprites

    * Remove the separate Hydra mount dimension declaration

    ---------

    Co-authored-by: CuriousMagpie <eilatan@gmail.com>

commit c03ab9855f
Author: Kalista Payne <kalista@habitica.com>
Date:   Tue Aug 5 14:31:05 2025 -0500

    5.38.1

commit 8f96b7b7fd
Author: Weblate <noreply@weblate.org>
Date:   Tue Aug 5 13:02:45 2025 +0200

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 17.1% (42 of 245 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 16.7% (41 of 245 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 16.3% (40 of 245 strings)

    Translated using Weblate (Polish)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 98.8% (425 of 430 strings)

    Translated using Weblate (French)

    Currently translated at 99.4% (184 of 185 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 15.9% (39 of 245 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 100.0% (268 of 268 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 100.0% (3385 of 3385 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 100.0% (185 of 185 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 99.8% (3379 of 3385 strings)

    Translated using Weblate (Polish)

    Currently translated at 95.5% (128 of 134 strings)

    Translated using Weblate (Japanese)

    Currently translated at 94.7% (254 of 268 strings)

    Translated using Weblate (Polish)

    Currently translated at 94.0% (126 of 134 strings)

    Translated using Weblate (Japanese)

    Currently translated at 98.6% (424 of 430 strings)

    Translated using Weblate (Japanese)

    Currently translated at 98.3% (423 of 430 strings)

    Translated using Weblate (Japanese)

    Currently translated at 92.5% (798 of 862 strings)

    Translated using Weblate (Japanese)

    Currently translated at 92.4% (797 of 862 strings)

    Translated using Weblate (Japanese)

    Currently translated at 90.6% (781 of 862 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.9% (3112 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.9% (3111 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 94.0% (174 of 185 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (8 of 8 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 15.5% (38 of 245 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.6% (3104 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 93.5% (173 of 185 strings)

    Translated using Weblate (Japanese)

    Currently translated at 99.6% (279 of 280 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (167 of 167 strings)

    Translated using Weblate (Japanese)

    Currently translated at 89.2% (769 of 862 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 94.4% (253 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.8% (170 of 185 strings)

    Translated using Weblate (Japanese)

    Currently translated at 97.9% (421 of 430 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.6% (3104 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 93.6% (251 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 90.8% (168 of 185 strings)

    Translated using Weblate (Japanese)

    Currently translated at 82.4% (202 of 245 strings)

    Translated using Weblate (French)

    Currently translated at 100.0% (268 of 268 strings)

    Translated using Weblate (French)

    Currently translated at 100.0% (3385 of 3385 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 15.1% (37 of 245 strings)

    Translated using Weblate (French)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.3% (3092 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 92.5% (248 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 92.5% (248 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (193 of 193 strings)

    Translated using Weblate (Croatian)

    Currently translated at 100.0% (15 of 15 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (167 of 167 strings)

    Translated using Weblate (Korean)

    Currently translated at 22.8% (56 of 245 strings)

    Translated using Weblate (Korean)

    Currently translated at 47.7% (128 of 268 strings)

    Translated using Weblate (Croatian)

    Currently translated at 45.1% (121 of 268 strings)

    Translated using Weblate (Korean)

    Currently translated at 71.9% (620 of 862 strings)

    Translated using Weblate (Croatian)

    Currently translated at 70.6% (609 of 862 strings)

    Translated using Weblate (Croatian)

    Currently translated at 75.0% (6 of 8 strings)

    Translated using Weblate (Korean)

    Currently translated at 67.6% (291 of 430 strings)

    Translated using Weblate (Korean)

    Currently translated at 52.8% (1788 of 3385 strings)

    Translated using Weblate (Croatian)

    Currently translated at 50.3% (1706 of 3385 strings)

    Translated using Weblate (Croatian)

    Currently translated at 51.7% (134 of 259 strings)

    Translated using Weblate (Czech)

    Currently translated at 92.8% (130 of 140 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 86.9% (233 of 268 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (94 of 94 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (94 of 94 strings)

    Translated using Weblate (Danish)

    Currently translated at 92.1% (105 of 114 strings)

    Translated using Weblate (Czech)

    Currently translated at 89.4% (102 of 114 strings)

    Translated using Weblate (Czech)

    Currently translated at 83.5% (112 of 134 strings)

    Translated using Weblate (Spanish (Latin America))

    Currently translated at 71.6% (308 of 430 strings)

    Translated using Weblate (Spanish (Latin America))

    Currently translated at 100.0% (245 of 245 strings)

    Translated using Weblate (Serbian)

    Currently translated at 84.4% (49 of 58 strings)

    Translated using Weblate (Bulgarian)

    Currently translated at 51.4% (144 of 280 strings)

    Translated using Weblate (Swedish)

    Currently translated at 66.5% (286 of 430 strings)

    Translated using Weblate (Serbian)

    Currently translated at 65.5% (282 of 430 strings)

    Translated using Weblate (Slovak)

    Currently translated at 65.5% (282 of 430 strings)

    Translated using Weblate (Romanian)

    Currently translated at 66.7% (287 of 430 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (430 of 430 strings)

    Translated using Weblate (Danish)

    Currently translated at 66.0% (284 of 430 strings)

    Translated using Weblate (Czech)

    Currently translated at 69.7% (300 of 430 strings)

    Translated using Weblate (Chinese (Simplified))

    Currently translated at 99.7% (3377 of 3385 strings)

    Translated using Weblate (Swedish)

    Currently translated at 54.1% (1834 of 3385 strings)

    Translated using Weblate (Serbian)

    Currently translated at 50.6% (1714 of 3385 strings)

    Translated using Weblate (Slovak)

    Currently translated at 50.0% (1695 of 3385 strings)

    Translated using Weblate (Romanian)

    Currently translated at 60.5% (2050 of 3385 strings)

    Translated using Weblate (Hebrew)

    Currently translated at 38.4% (1301 of 3385 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (3385 of 3385 strings)

    Translated using Weblate (Danish)

    Currently translated at 54.0% (1829 of 3385 strings)

    Translated using Weblate (Czech)

    Currently translated at 59.6% (2020 of 3385 strings)

    Translated using Weblate (Swedish)

    Currently translated at 75.6% (140 of 185 strings)

    Translated using Weblate (Serbian)

    Currently translated at 73.5% (136 of 185 strings)

    Translated using Weblate (Slovak)

    Currently translated at 84.8% (157 of 185 strings)

    Translated using Weblate (Romanian)

    Currently translated at 78.9% (146 of 185 strings)

    Translated using Weblate (Portuguese)

    Currently translated at 82.1% (152 of 185 strings)

    Translated using Weblate (Italian)

    Currently translated at 91.8% (170 of 185 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (185 of 185 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (185 of 185 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (185 of 185 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (Danish)

    Currently translated at 77.2% (143 of 185 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 98.7% (242 of 245 strings)

    Translated using Weblate (Czech)

    Currently translated at 75.1% (139 of 185 strings)

    Translated using Weblate (Bulgarian)

    Currently translated at 74.5% (138 of 185 strings)

    Translated using Weblate (Czech)

    Currently translated at 8.1% (20 of 245 strings)

    Translated using Weblate (Swedish)

    Currently translated at 72.0% (621 of 862 strings)

    Translated using Weblate (Serbian)

    Currently translated at 65.1% (562 of 862 strings)

    Translated using Weblate (Slovak)

    Currently translated at 66.9% (577 of 862 strings)

    Translated using Weblate (Romanian)

    Currently translated at 77.7% (670 of 862 strings)

    Translated using Weblate (Portuguese)

    Currently translated at 70.0% (604 of 862 strings)

    Translated using Weblate (Polish)

    Currently translated at 67.1% (579 of 862 strings)

    Translated using Weblate (Italian)

    Currently translated at 86.8% (749 of 862 strings)

    Translated using Weblate (Indonesian)

    Currently translated at 86.0% (742 of 862 strings)

    Translated using Weblate (Hebrew)

    Currently translated at 66.1% (570 of 862 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 98.0% (845 of 862 strings)

    Translated using Weblate (Danish)

    Currently translated at 69.9% (603 of 862 strings)

    Translated using Weblate (Czech)

    Currently translated at 69.7% (601 of 862 strings)

    Translated using Weblate (Bulgarian)

    Currently translated at 66.3% (572 of 862 strings)

    Translated using Weblate (Serbian)

    Currently translated at 74.0% (305 of 412 strings)

    Translated using Weblate (Turkish)

    Currently translated at 100.0% (193 of 193 strings)

    Translated using Weblate (Danish)

    Currently translated at 90.0% (371 of 412 strings)

    Translated using Weblate (Ukrainian)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Swedish)

    Currently translated at 53.6% (139 of 259 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Danish)

    Currently translated at 62.1% (161 of 259 strings)

    Translated using Weblate (Bulgarian)

    Currently translated at 54.0% (140 of 259 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 82.8% (222 of 268 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 99.4% (184 of 185 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 98.3% (241 of 245 strings)

    Translated using Weblate (Japanese)

    Currently translated at 91.3% (3092 of 3385 strings)

    Translated using Weblate (Japanese)

    Currently translated at 88.4% (237 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (134 of 134 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Japanese)

    Currently translated at 100.0% (243 of 243 strings)

    Translated using Weblate (Japanese)

    Currently translated at 82.4% (202 of 245 strings)

    Translated using Weblate (English (United Kingdom))

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Japanese)

    Currently translated at 87.3% (234 of 268 strings)

    Translated using Weblate (Japanese)

    Currently translated at 86.4% (160 of 185 strings)

    Translated using Weblate (Japanese)

    Currently translated at 99.8% (913 of 914 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (268 of 268 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (3377 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (259 of 259 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (3385 of 3385 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (914 of 914 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (268 of 268 strings)

    Translated using Weblate (Russian)

    Currently translated at 88.5% (248 of 280 strings)

    Translated using Weblate (Spanish)

    Currently translated at 99.8% (3379 of 3385 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (862 of 862 strings)

    Co-authored-by: Ayaka Booker <ayakabooker@gmail.com>
    Co-authored-by: Chaotic Lawful <habitica@eusebius.fr>
    Co-authored-by: FingerTiao <787170918@qq.com>
    Co-authored-by: Jaime Martí <jaumemarti77@icloud.com>
    Co-authored-by: Jan Freihöfer <jan.stauch.is@gmail.com>
    Co-authored-by: Karmelkowy <kicimeow.karmelio@gmail.com>
    Co-authored-by: Lio Zam <zerofux@web.de>
    Co-authored-by: Mika <isekai.chr@gmail.com>
    Co-authored-by: Sophie LE MASLE <sophiesuff@gmail.com>
    Co-authored-by: Summer_GUI <heyang94@163.com>
    Co-authored-by: Vera <verasmolinap@gmail.com>
    Co-authored-by: Weblate <noreply@weblate.org>
    Co-authored-by: Zhi Hao Li <zhihaoli000@gmail.com>
    Co-authored-by: Zuz Q <zuzannakunik@gmail.com>
    Co-authored-by: innnko <ayakabooker@gmail.com>
    Co-authored-by: 吳昀錡 <J1120241@gm.fdhs.tyc.edu.tw>
    Co-authored-by: 潘致翰 <happyq0908@gmail.com>
    Translate-URL: https://translate.habitica.com/projects/habitica/achievements/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/fr/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/pl/
    Translate-URL: https://translate.habitica.com/projects/habitica/backgrounds/zh_Hans/
    Translate-URL: https://translate.habitica.com/projects/habitica/character/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/character/tr/
    Translate-URL: https://translate.habitica.com/projects/habitica/content/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/content/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/death/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/es_419/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/ko/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/zh_Hant/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/bg/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/fr/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/it/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/pt/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/ro/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/sk/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/sv/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/zh_Hans/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/fr/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/he/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/ko/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/ro/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/sk/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/sv/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/zh_Hans/
    Translate-URL: https://translate.habitica.com/projects/habitica/generic/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/es_419/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/ko/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/ro/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/sk/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/groups/sv/
    Translate-URL: https://translate.habitica.com/projects/habitica/limited/bg/
    Translate-URL: https://translate.habitica.com/projects/habitica/limited/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/limited/ru/
    Translate-URL: https://translate.habitica.com/projects/habitica/messages/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/npc/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/npc/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/npc/pl/
    Translate-URL: https://translate.habitica.com/projects/habitica/overview/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/overview/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/pets/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/pets/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/quests/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/quests/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/bg/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/cs/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/he/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/id/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/it/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/ko/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/pl/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/pt/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/ro/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/sk/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/sr/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/sv/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/bg/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/da/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/sv/
    Translate-URL: https://translate.habitica.com/projects/habitica/settings/uk/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/en_GB/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/fr/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/hr/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/ja/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/ko/
    Translate-URL: https://translate.habitica.com/projects/habitica/subscriber/zh_Hans/
    Translate-URL: https://translate.habitica.com/projects/habitica/tasks/cs/
    Translation: Habitica/Achievements
    Translation: Habitica/Backgrounds
    Translation: Habitica/Character
    Translation: Habitica/Content
    Translation: Habitica/Death
    Translation: Habitica/Faq
    Translation: Habitica/Front
    Translation: Habitica/Gear
    Translation: Habitica/Generic
    Translation: Habitica/Groups
    Translation: Habitica/Limited
    Translation: Habitica/Messages
    Translation: Habitica/Npc
    Translation: Habitica/Overview
    Translation: Habitica/Pets
    Translation: Habitica/Quests
    Translation: Habitica/Questscontent
    Translation: Habitica/Settings
    Translation: Habitica/Subscriber
    Translation: Habitica/Tasks

commit 1dde2674f6
Author: Kalista Payne <sabrecat@gmail.com>
Date:   Mon Jun 16 16:43:56 2025 -0500

    fix(content): don't filter out the thing we want

commit 76122a8889
Author: Kalista Payne <sabrecat@gmail.com>
Date:   Wed Jun 4 14:28:27 2025 -0500

    fix(mobile): provide Challenge categories via API

commit 9e309a875e
Author: Kalista Payne <kalista@habitica.com>
Date:   Mon Jul 28 14:15:00 2025 -0500

    5.38.0

commit 09e3a394b8
Author: Kalista Payne <kalista@habitica.com>
Date:   Mon Jul 28 14:06:45 2025 -0500

    5.37.3

commit eba263360f
Author: Weblate <noreply@weblate.org>
Date:   Mon Jul 28 21:03:17 2025 +0200

    Translated using Weblate (German)

    Currently translated at 100.0% (134 of 134 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (134 of 134 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (3377 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (3377 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (3377 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (243 of 243 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 98.6% (850 of 862 strings)

    Translated using Weblate (German)

    Currently translated at 99.8% (3373 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.8% (3373 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.8% (3373 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.5% (3361 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.5% (3361 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.5% (3361 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 99.4% (3360 of 3377 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (Spanish)

    Currently translated at 100.0% (185 of 185 strings)

    Translated using Weblate (Polish)

    Currently translated at 67.1% (579 of 862 strings)

    Translated using Weblate (Polish)

    Currently translated at 67.1% (579 of 862 strings)

    Translated using Weblate (Polish)

    Currently translated at 100.0% (91 of 91 strings)

    Translated using Weblate (Polish)

    Currently translated at 100.0% (91 of 91 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (184 of 184 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (245 of 245 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (47 of 47 strings)

    Translated using Weblate (German)

    Currently translated at 100.0% (193 of 193 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 14.2% (35 of 245 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 13.8% (34 of 245 strings)

    Translated using Weblate (Chinese (Traditional))

    Currently translated at 13.0% (32 of 245 strings)

    Translated using Weblate (Hebrew)

    Currently translated at 2.0% (5 of 245 strings)

    Translated using Weblate (Hebrew)

    Currently translated at 66.1% (570 of 862 strings)

    Translated using Weblate (Portuguese)

    Currently translated at 54.1% (1830 of 3377 strings)

    Co-authored-by: FingerTiao <787170918@qq.com>
    Co-authored-by: Jaime Martí <jaumemarti77@icloud.com>
    Co-authored-by: Jan Freihöfer <jan.stauch.is@gmail.com>
    Co-authored-by: Jonathan Niessen <37.friedrich@gmail.com>
    Co-authored-by: Karmelkowy <kicimeow.karmelio@gmail.com>
    Co-authored-by: Katharina <katharinaanna.wilding@gmail.com>
    Co-authored-by: Laura Fleckenstein <fleckenstein_laura@web.de>
    Co-authored-by: Omer I.S <omeritzicschwartz@gmail.com>
    Co-authored-by: Remigiusz Haziak <haziakremigiusz@gmail.com>
    Co-authored-by: Uwe B <hbtca@tunixgut.de>
    Co-authored-by: Weblate <noreply@weblate.org>
    Co-authored-by: Wellinton Cardoso <wmcardoso1@hotmail.com>
    Co-authored-by: cloudzzy <truskawka412@gmail.com>
    Co-authored-by: 吳昀錡 <J1120241@gm.fdhs.tyc.edu.tw>
    Translate-URL: https://translate.habitica.com/projects/habitica/character/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/communityguidelines/pl/
    Translate-URL: https://translate.habitica.com/projects/habitica/contrib/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/he/
    Translate-URL: https://translate.habitica.com/projects/habitica/faq/zh_Hant/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/front/es/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/gear/pt/
    Translate-URL: https://translate.habitica.com/projects/habitica/generic/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/npc/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/de/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/he/
    Translate-URL: https://translate.habitica.com/projects/habitica/questscontent/pl/
    Translation: Habitica/Character
    Translation: Habitica/Communityguidelines
    Translation: Habitica/Contrib
    Translation: Habitica/Faq
    Translation: Habitica/Front
    Translation: Habitica/Gear
    Translation: Habitica/Generic
    Translation: Habitica/Npc
    Translation: Habitica/Questscontent

commit 9550eec718
Author: Phillip Thelen <phillip@habitica.com>
Date:   Mon Jul 28 16:50:38 2025 +0200

    Fix 500 when deleting a very old group plan account (#15481)

commit f267eb67e9
Author: Kalista Payne <kalista@habitica.com>
Date:   Tue Jul 29 14:12:35 2025 -0500

    fix(static): add back missing div for show/hide

commit 28251f42ab
Author: Kalista Payne <kalista@habitica.com>
Date:   Thu Jul 24 22:59:01 2025 -0500

    feat(privacy): preview page

* feat(privacy): respect Global Privacy Control

* fix(lint): remove unused component

* fix(test): test user opts in to tracking

* fix(test): add user pref to more contexts

* fix(test): final spot in api-unit

* fix(tests): update integrations

* chore(privacy): add paragraph to s1, retire separate preview pages

* fix(build): route copypasta

* fix(router): lingering dead import

---------

Signed-off-by: Kalista Payne <sabrecat@gmail.com>
Signed-off-by: Kalista Payne <kalista@habitica.com>
Co-authored-by: Phillip Thelen <phillip@habitica.com>
Co-authored-by: CuriousMagpie <eilatan@gmail.com>
2025-08-29 15:44:19 -05:00

1116 lines
38 KiB
JavaScript

import cloneDeep from 'lodash/cloneDeep';
import escapeRegExp from 'lodash/escapeRegExp';
import merge from 'lodash/merge';
import pick from 'lodash/pick';
import reduce from 'lodash/reduce';
import times from 'lodash/times';
import { authWithHeaders, authWithSession } from '../../middlewares/auth';
import { model as Challenge } from '../../models/challenge';
import bannedWords from '../../libs/bannedWords';
import bannedSlurs from '../../libs/bannedSlurs';
import { getMatchesByWordArray } from '../../libs/stringUtils';
import * as slack from '../../libs/slack';
import { getUserInfo } from '../../libs/email';
import {
model as Group,
basicFields as basicGroupFields,
TAVERN_ID,
} from '../../models/group';
import {
model as User,
nameFields,
} from '../../models/user';
import {
BadRequest,
NotFound,
NotAuthorized,
} from '../../libs/errors';
import * as Tasks from '../../models/task';
import csvStringify from '../../libs/csvStringify';
import {
createTasks,
} from '../../libs/tasks';
import {
addUserJoinChallengeNotification,
getChallengeGroupResponse,
createChallenge,
cleanUpTask,
createChallengeQuery,
} from '../../libs/challenges';
import { apiError } from '../../libs/apiError';
import common from '../../../common';
import {
clearFlags,
flagChallenge,
notifyOfFlaggedChallenge,
} from '../../libs/challenges/reporting';
const { MAX_SUMMARY_SIZE_FOR_CHALLENGES } = common.constants;
const api = {};
function textContainsBannedWord (message) {
if (!message) {
return false;
}
const bannedWordsMatched = getMatchesByWordArray(message, bannedWords);
return bannedWordsMatched.length > 0;
}
function textContainsBannedSlur (message) {
if (!message) {
return false;
}
const bannedSlursMatched = getMatchesByWordArray(message, bannedSlurs);
return bannedSlursMatched.length > 0;
}
/**
* @apiDefine ChallengeLeader Challenge Leader
* The leader of the challenge can use this route.
*/
/**
* @apiDefine ChallengeNotFound
* @apiError (404) {NotFound} ChallengeNotFound The specified challenge could not be found.
*/
/**
* @apiDefine SuccessfulChallengeRequest
* @apiSuccess {UUID} challenge.group._id The group id.
* @apiSuccess {String} challenge.group.type Group type: `guild` or `party`.
* @apiSuccess {String} challenge.group.privacy Group privacy: `public` or `private`.
* @apiSuccess {String} challenge.name Full name of challenge.
* @apiSuccess {String} challenge.shortName A shortened name for the challenge, to be used as a tag.
* @apiSuccess {Object} challenge.leader User details of challenge leader.
* @apiSuccess {UUID} challenge.leader._id User ID of challenge leader.
* @apiSuccess {Object} challenge.leader.profile Profile information of leader.
* @apiSuccess {Object} challenge.leader.profile.name Display Name of leader.
* @apiSuccess {String} challenge.updatedAt Timestamp of last update.
* @apiSuccess {String} challenge.createdAt Timestamp of challenge creation.
* @apiSuccess {UUID} challenge.id Id number of newly created challenge.
* @apiSuccess {UUID} challenge._id Same as `challenge.id`.
* @apiSuccess {String} challenge.prize Number of gems offered as prize to winner (can be 0).
* @apiSuccess {String} challenge.memberCount Number users participating in challenge.
* @apiSuccess {Object} challenge.tasksOrder Object containing IDs of the challenge's
* tasks and rewards in their preferred sort order.
* @apiSuccess {Array} challenge.tasksOrder.rewards Array of `reward` task IDs.
* @apiSuccess {Array} challenge.tasksOrder.todos Array of `todo` task IDs.
* @apiSuccess {Array} challenge.tasksOrder.dailys Array of `daily` task IDs.
* @apiSuccess {Array} challenge.tasksOrder.habits Array of `habit` task IDs.
* @apiSuccess {Boolean} challenge.official Boolean indicating if
* this is an official Habitica challenge.
*
*/
/**
* @apiDefine ChallengeSuccessExample
* @apiSuccessExample {json} Successful response with single challenge
{
"data": {
"group": {
"_id": "group-id-associated-with-challenge",
"name": "MyGroup",
"type": "guild",
"privacy": "public"
},
"name": "Long Detailed Name of Challenge",
"shortName": "my challenge",
"leader": {
"_id": "user-id-of-challenge-creator",
"profile": {
"name": "MyUserName"
}
},
"updatedAt": "timestamp,
"createdAt": "timestamp",
"_id": "challenge-id",
"prize": 0,
"memberCount": 1,
"tasksOrder": {
"rewards": [
"uuid-of-challenge-reward"
],
"todos": [
"uuid-of-challenge-todo"
],
"dailys": [
"uuid-of-challenge-daily"
],
"habits": [
"uuid-of-challenge-habit"
]
},
"official": false,
"id": "challenge-id"
}
}
*/
/**
* @apiDefine ChallengeArrayExample
* @apiSuccessExample {json} Successful response with array of challenges
{
"data": [{
"group": {
"_id": "group-id-associated-with-challenge",
"name": "MyGroup",
"type": "guild",
"privacy": "public"
},
"name": "Long Detailed Name of Challenge",
"shortName": "my challenge",
"leader": {
"_id": "user-id-of-challenge-creator",
"profile": {
"name": "MyUserName"
}
},
"updatedAt": "timestamp,
"createdAt": "timestamp",
"_id": "challenge-id",
"prize": 0,
"memberCount": 1,
"tasksOrder": {
"rewards": [
"uuid-of-challenge-reward"
],
"todos": [
"uuid-of-challenge-todo"
],
"dailys": [
"uuid-of-challenge-daily"
],
"habits": [
"uuid-of-challenge-habit"
]
},
"official": false,
"id": "challenge-id"
}]
}
*/
/**
* @api {post} /api/v3/challenges Create a new challenge
* @apiName CreateChallenge
* @apiGroup Challenge
* @apiDescription Creates a challenge. Cannot create associated
* tasks with this route. See <a href="#api-Task-CreateChallengeTasks">CreateChallengeTasks</a>.
*
* @apiParam (Body) {Object} challenge An object representing the challenge to be created
* @apiParam (Body) {UUID} challenge.group The id of the group to which the challenge belongs
* @apiParam (Body) {String} challenge.name The full name of the challenge
* @apiParam (Body) {String} challenge.shortName A shortened name for the challenge,
* to be used as a tag.
* @apiParam (Body) {String} [challenge.summary] A short summary advertising the main purpose
* of the challenge; maximum 250 characters;
* if not supplied, challenge.name will be used.
* @apiParam (Body) {String} [challenge.description] A detailed description of the challenge
* @apiParam (Body) {Boolean} [official=false] Whether or not a challenge is an official
* Habitica challenge (requires admin).
* @apiParam (Body) {Number} [challenge.prize=0] Number of gems offered as
* a prize to challenge winner.
*
* @apiSuccess (201) {Object} challenge The newly created challenge.
* @apiUse SuccessfulChallengeRequest
*
* @apiUse ChallengeSuccessExample
*
* @apiError (401) {NotAuthorized} CantAffordPrize User does not have enough
gems to offer this prize.
* @apiError (400) {BadRequest} ChallengeValidationFailed Invalid or missing parameter
in challenge body.
*
* @apiUse GroupNotFound
* @apiUse UserNotFound
*/
api.createChallenge = {
method: 'POST',
url: '/challenges',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkBody('group', apiError('groupIdRequired')).notEmpty();
req.checkBody('summary', apiError('summaryLengthExceedsMax')).isLength({ max: MAX_SUMMARY_SIZE_FOR_CHALLENGES });
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const group = await Group.getGroup({
user, groupId: req.body.group, fields: basicGroupFields, optionalMembership: true,
});
if (!group) {
throw new NotFound(res.t('groupNotFound'));
}
// check public challenges for banned words & chat revocation
if (group.privacy === 'public') {
const textToCheck = `${req.body.name} ${req.body.shortName} ${req.body.summary} ${req.body.description}`;
if (textContainsBannedSlur(textToCheck)) {
const authorEmail = getUserInfo(user, ['email']).email;
const problemContent = `Challenge Name: ${req.body.name}\n
Challenge Tag: ${req.body.shortName}\n
Challenge Summary: ${req.body.summary}\n
Challenge Description: ${req.body.description}`;
slack.sendChallengeSlurNotification({
authorEmail,
author: user,
displayName: user.profile.name,
username: user.auth.local.username,
uuid: user.id,
language: user.preferences.language,
problemContent,
});
user.flags.chatRevoked = true;
await user.save();
throw new BadRequest(res.t('challengeBannedSlurs'));
}
if (textContainsBannedWord(textToCheck)) {
throw new BadRequest(res.t('challengeBannedWords'));
}
if (user.flags.chatRevoked) {
throw new BadRequest(res.t('cannotMakeChallenge'));
}
}
const { savedChal } = await createChallenge(user, req, res);
await user.save();
const response = savedChal.toJSON();
response.leader = { // the leader is the authenticated user
_id: user._id,
profile: { name: user.profile.name },
};
response.group = getChallengeGroupResponse(group);
res.analytics.track('challenge create', {
user: pick(user, ['preferences', 'registeredThrough']),
uuid: user._id,
hitType: 'event',
category: 'behavior',
challengeID: response._id,
groupID: group._id,
groupName: group.privacy === 'private' ? null : group.name,
groupType: group._id === TAVERN_ID ? 'tavern' : group.type,
prize: response.prize,
headers: req.headers,
});
res.respond(201, response);
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/join Join a challenge
* @apiName JoinChallenge
* @apiGroup Challenge
* @apiParam (Path) {UUID} challengeId The challenge _id
*
* @apiSuccess {Object} challenge The challenge the user joined
* @apiUse SuccessfulChallengeRequest
*
* @apiUse ChallengeNotFound
* @apiUse UserNotFound
*
* @apiUse ChallengeSuccessExample
*/
api.joinChallenge = {
method: 'POST',
url: '/challenges/:challengeId/join',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
const group = await Group.getGroup({
user, groupId: challenge.group, fields: `${basicGroupFields} purchased`, optionalMembership: true,
});
if (!group || !challenge.canJoin(user, group)) throw new NotFound(res.t('challengeNotFound'));
group.purchased = undefined;
const addedSuccessfully = await challenge.addToUser(user);
if (!addedSuccessfully) {
throw new NotAuthorized(res.t('userAlreadyInChallenge'));
}
challenge.memberCount += 1;
addUserJoinChallengeNotification(user);
// Add all challenge's tasks to user's tasks and save the challenge
const results = await Promise.all([challenge.syncTasksToUser(user), challenge.save()]);
const response = results[1].toJSON();
response.group = getChallengeGroupResponse(group);
const chalLeader = await User.findById(response.leader).select(nameFields).exec();
response.leader = chalLeader ? chalLeader.toJSON({ minimize: true }) : null;
res.analytics.track('challenge join', {
user: pick(user, ['preferences', 'registeredThrough']),
uuid: user._id,
hitType: 'event',
category: 'behavior',
challengeID: challenge._id,
groupID: group._id,
groupName: group.privacy === 'private' ? null : group.name,
groupType: group._id === TAVERN_ID ? 'tavern' : group.type,
headers: req.headers,
});
res.respond(200, response);
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/leave Leave a challenge
* @apiName LeaveChallenge
* @apiGroup Challenge
* @apiParam (Path) {UUID} challengeId The challenge _id
* @apiParam (Body) {String="remove-all","keep-all"} [keep="keep-all"] Whether or not to
* keep or remove the
* challenge's tasks.
*
* @apiSuccess {Object} data An empty object
*
* @apiUse ChallengeNotFound
* @apiUse UserNotFound
*/
api.leaveChallenge = {
method: 'POST',
url: '/challenges/:challengeId/leave',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
const keep = req.body.keep === 'remove-all' ? 'remove-all' : 'keep-all';
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
if (!challenge.isMember(user)) throw new NotAuthorized(res.t('challengeMemberNotFound'));
// Unlink challenge's tasks from user's tasks and save the challenge
await challenge.unlinkTasks(user, keep);
res.analytics.track('challenge leave', {
user: pick(user, ['preferences', 'registeredThrough']),
uuid: user._id,
hitType: 'event',
category: 'behavior',
challengeID: challenge._id,
groupID: challenge.group._id,
groupName: challenge.group.privacy === 'private' ? null : challenge.group.name,
groupType: challenge.group._id === TAVERN_ID ? 'tavern' : challenge.group.type,
headers: req.headers,
});
res.respond(200, {});
},
};
/**
* @api {get} /api/v3/challenges/user Get challenges for a user
* @apiName GetUserChallenges
* @apiGroup Challenge
* @apiDescription Get challenges the user has access to. Includes public challenges,
* challenges belonging to the user's group, and challenges the user has already joined.
* Returns 10 results per page.
*
* @apiSuccess {Object[]} challenges An array of challenges sorted with official
* challenges first, followed by the challenges
* in order from newest to oldest.
*
* @apiParam (Query) {Number} page This parameter can be used to specify the page number
for the user challenges result (the initial page is number 0).
* @apiParam (Query) {String} [member] If set to `true` it limits results to challenges where the
user is a member, or the user owns the challenge.
* @apiParam (Query) {String} [owned] If set to `owned` it limits results to challenges owned
by the user. If set to `not_owned` it limits results
to challenges not owned by the user.
* @apiParam (Query) {String} [search] Optional query parameter to filter results to challenges
that include (even partially) the search query parameter
in the name or description.
* @apiParam (Query) {String} [categories] Optional comma separated list of categories.
If set it limits results to challenges that are part
of the given categories.
* @apiError (400) {BadRequest} queryPageInteger Page query parameter must be a positive integer
* @apiUse SuccessfulChallengeRequest
*
* @apiUse ChallengeArrayExample
*
* @apiUse UserNotFound
*/
api.getUserChallenges = {
method: 'GET',
url: '/challenges/user',
middlewares: [authWithHeaders()],
async handler (req, res) {
req.checkQuery('page').notEmpty().isInt({ min: 0 }, apiError('queryPageInteger'));
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const CHALLENGES_PER_PAGE = 10;
const {
categories,
member,
owned,
page,
search,
} = req.query;
const { user } = res.locals;
const query = {
$and: [],
};
if (!user.hasPermission('moderator')) {
query.$and.push(
{
$or: [
{ flagCount: { $not: { $gt: 1 } } },
{ leader: user._id },
],
},
);
}
// Challenges the user owns
const orOptions = [{ leader: user._id }];
// Challenges where the user is participating
if (user.challenges.length > 0) {
orOptions.push({ _id: { $in: user.challenges } });
}
// Challenges in groups user is a member of, plus public challenges
if (!member) {
const userGroups = await Group.getGroups({
user,
types: ['party', 'guilds', 'tavern'],
});
const userGroupIds = userGroups.map(userGroup => userGroup._id);
orOptions.push({
group: { $in: userGroupIds },
});
}
if (owned === 'not_owned') {
query.leader = { $ne: user._id }; // Show only Challenges user does not own
} else if (owned === 'owned') {
query.leader = user._id; // Show only Challenges user owns
} else {
orOptions.push(
{ leader: user._id }, // Additionally show Challenges user owns
);
}
query.$and.push({ $or: orOptions });
if (search) {
const searchOr = { $or: [] };
const searchWords = escapeRegExp(search).split(' ').join('|');
const searchQuery = { $regex: new RegExp(`${searchWords}`, 'i') };
searchOr.$or.push({ name: searchQuery });
searchOr.$or.push({ description: searchQuery });
query.$and.push(searchOr);
}
if (categories) {
const categorySlugs = categories.split(',');
query.categories = { $elemMatch: { slug: { $in: categorySlugs } } };
}
// Ensure that official challenges are always first
let mongoQuery = createChallengeQuery(query);
if (page) {
mongoQuery = mongoQuery
.skip(CHALLENGES_PER_PAGE * page)
.limit(CHALLENGES_PER_PAGE);
}
// see below why we're not using populate
// .populate('group', basicGroupFields)
// .populate('leader', nameFields)
const challenges = await mongoQuery.exec();
// Unserialize, then serialize the challenges to fill in default fields
const resChals = challenges.map(chal => (new Challenge(chal)).toJSON());
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
await Promise.all(resChals.map((chal, index) => Promise.all([
User.findById(chal.leader).select(`${nameFields} backer contributor`).exec(),
Group.findById(chal.group).select(basicGroupFields).exec(),
]).then(populatedData => {
resChals[index].leader = populatedData[0]
? populatedData[0].toJSON({ minimize: true })
: null;
resChals[index].group = populatedData[1]
? populatedData[1].toJSON({ minimize: true })
: null;
})));
res.respond(200, resChals);
},
};
/**
* @api {get} /api/v3/challenges/groups/:groupId Get challenges for a group
* @apiDescription Get challenges hosted in the specified group.
* @apiName GetGroupChallenges
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} groupId The group id ('party' for the user party and 'habitrpg'
* for tavern are accepted)
*
* @apiSuccess {Array} data An array of challenges sorted with official challenges first,
* followed by the challenges in order from newest to oldest.
*
* @apiUse SuccessfulChallengeRequest
* @apiUse ChallengeArrayExample
* @apiUse UserNotFound
* @apiUse GroupNotFound
*/
api.getGroupChallenges = {
method: 'GET',
url: '/challenges/groups/:groupId',
middlewares: [authWithHeaders({
// Some fields (including _id) are always loaded (see middlewares/auth)
userFieldsToInclude: ['party', 'guilds', 'contributor'], // Some fields are always loaded (see middlewares/auth)
})],
async handler (req, res) {
const { user } = res.locals;
let { groupId } = req.params;
req.checkParams('groupId', apiError('groupIdRequired')).notEmpty();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
if (groupId === 'party') groupId = user.party._id;
if (groupId === 'habitrpg') groupId = TAVERN_ID;
const group = await Group.getGroup({ user, groupId });
if (!group) throw new NotFound(res.t('groupNotFound'));
const challenges = await createChallengeQuery({ group: groupId })
// Only populate the leader as the group is implicit // see below why we're not using populate
// .populate('leader', nameFields)
.exec();
const resChals = challenges.map(challenge => {
// filter out challenges that the non-admin user isn't participating in, nor created
const nonParticipant = !user.challenges
|| (user.challenges
&& user.challenges.findIndex(cId => cId === challenge._id) === -1);
const isFlaggedForNonAdminUser = challenge.flagCount > 1
&& !user.hasPermission('moderator')
&& nonParticipant
&& challenge.leader !== user._id;
return isFlaggedForNonAdminUser ? null : (new Challenge(challenge)).toJSON();
}).filter(challenge => !!challenge);
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
await Promise.all(resChals.map((chal, index) => User
.findById(chal.leader)
.select(nameFields)
.exec()
.then(populatedLeader => {
resChals[index].leader = populatedLeader
? populatedLeader.toJSON({ minimize: true })
: null;
})));
res.respond(200, resChals);
},
};
/**
* @api {get} /api/v3/challenges/:challengeId Get a challenge
* @apiName GetChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The challenge _id
*
* @apiSuccess {Object} data The challenge object
* @apiUse SuccessfulChallengeRequest
* @apiUse ChallengeSuccessExample
*
* @apiUse ChallengeNotFound
*/
api.getChallenge = {
method: 'GET',
url: '/challenges/:challengeId',
middlewares: [authWithHeaders()],
async handler (req, res) {
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const { user } = res.locals;
const { challengeId } = req.params;
// Don't populate the group as we'll fetch it manually later
// .populate('leader', nameFields)
const challenge = await Challenge.findById(challengeId).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
const nonParticipant = !user.challenges
|| (user.challenges
&& user.challenges.findIndex(cId => cId === challenge._id) === -1);
const isFlaggedForNonAdminUser = challenge.flagCount > 1
&& !user.hasPermission('moderator')
&& nonParticipant
&& challenge.leader !== user._id;
if (isFlaggedForNonAdminUser) throw new NotFound(res.t('challengeNotFound'));
// Fetching basic group data
const group = await Group.getGroup({
user, groupId: challenge.group, fields: `${basicGroupFields} purchased`,
});
if (!group && !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
const chalRes = challenge.toJSON();
if (group) {
group.purchased = undefined;
chalRes.group = group.toJSON({ minimize: true });
}
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
const chalLeader = await User.findById(chalRes.leader).select(nameFields).exec();
chalRes.leader = chalLeader ? chalLeader.toJSON({ minimize: true }) : null;
res.respond(200, chalRes);
},
};
/**
* @api {get} /api/v3/challenges/:challengeId/export/csv Export a challenge in CSV
* @apiName ExportChallengeCsv
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The challenge _id
*
* @apiSuccess {String} challenge A csv file
*
* @apiUse ChallengeNotFound
*/
api.exportChallengeCsv = {
method: 'GET',
url: '/challenges/:challengeId/export/csv',
middlewares: [authWithSession],
async handler (req, res) {
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const { user } = res.locals;
const { challengeId } = req.params;
const challenge = await Challenge.findById(challengeId).select('_id group leader tasksOrder').exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
const group = await Group.getGroup({
user, groupId: challenge.group, fields: '_id type privacy', optionalMembership: true,
});
if (!group || !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
// In v2 this used the aggregation framework to run some
// computation on MongoDB but then iterated through all
// results on the server so the perf difference isn't that big (hopefully)
const [members, tasks] = await Promise.all([
User.find({ challenges: challengeId })
.select(nameFields)
.sort({ _id: 1 })
.lean() // so we don't involve mongoose
.exec(),
Tasks.Task.find({
'challenge.id': challengeId,
userId: { $exists: true },
}).sort({ userId: 1, text: 1 })
.select('userId type text value notes streak')
.lean()
.exec(),
]);
let resArray = members
.map(member => [member._id, member.profile.name, member.auth.local.username]);
let lastUserId;
let index = -1;
tasks.forEach(task => {
/**
* Occasional error does not unlink a user's challenge tasks from that challenge's data
* after the user leaves that challenge, which previously caused a failure when exporting
* to a CSV. The following if statement makes sure that the task's attached user still
* belongs to the challenge.
* See more at https://github.com/HabitRPG/habitica/issues/8350
*/
if (!resArray.map(line => line[0]).includes(task.userId)) {
return;
}
while (task.userId !== lastUserId) {
index += 1;
[lastUserId] = resArray[index]; // resArray[index][0] is an user id
}
const streak = task.streak || 0;
resArray[index].push(`${task.type}:${task.text}`, task.value, task.notes, streak);
});
// The first row is going to be UUID name Task Value Notes
// repeated n times for the n challenge tasks
const challengeTasks = reduce(
challenge.tasksOrder.toObject(),
(result, array) => result.concat(array),
[],
).sort();
resArray.unshift(['UUID', 'Display Name', 'Username']);
times(challengeTasks.length, () => resArray[0].push('Task', 'Value', 'Notes', 'Streak'));
// Remove lines for users without tasks info
resArray = resArray.filter(line => {
if (line.length === 2) { // only user data ([id, profile name]), no task data
return false;
}
return true;
});
res.set({
'Content-Type': 'text/csv',
'Content-disposition': `attachment; filename=${challengeId}.csv`,
});
const csvRes = await csvStringify(resArray);
res.status(200).send(csvRes);
},
};
/**
* @api {put} /api/v3/challenges/:challengeId Update a challenge's name, description, or summary
*
* @apiName UpdateChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The challenge _id
* @apiParam (Body) {String} [challenge.name] The new full name of the challenge.
* @apiParam (Body) {String} [challenge.summary] The new challenge summary.
* @apiParam (Body) {String} [challenge.description] The new challenge description.
*
* @apiSuccess {Object} data The updated challenge
* @apiPermission ChallengeLeader
*
* @apiUse ChallengeSuccessExample
*
* @apiUse ChallengeNotFound
*
* @apiError (401) {NotAuthorized} MustBeChallengeLeader Only challenge leader
* can update the challenge.
*/
api.updateChallenge = {
method: 'PUT',
url: '/challenges/:challengeId',
middlewares: [authWithHeaders()],
async handler (req, res) {
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
req.checkBody('summary', apiError('summaryLengthExceedsMax')).isLength({ max: MAX_SUMMARY_SIZE_FOR_CHALLENGES });
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const { user } = res.locals;
const { challengeId } = req.params;
const challenge = await Challenge.findById(challengeId).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
const group = await Group.getGroup({
user, groupId: challenge.group, fields: `${basicGroupFields} purchased`, optionalMembership: true,
});
if (!group || !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
if (!challenge.canModify(user)) throw new NotAuthorized(res.t('onlyLeaderUpdateChal'));
group.purchased = undefined;
merge(challenge, Challenge.sanitizeUpdate(req.body));
const savedChal = await challenge.save();
const response = savedChal.toJSON();
response.group = getChallengeGroupResponse(group);
const chalLeader = await User.findById(response.leader).select(nameFields).exec();
response.leader = chalLeader ? chalLeader.toJSON({ minimize: true }) : null;
res.respond(200, response);
},
};
/**
* @api {delete} /api/v3/challenges/:challengeId Delete a challenge
* @apiName DeleteChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The _id for the challenge to delete
*
* @apiSuccess {Object} data An empty object
*
* @apiUse ChallengeNotFound
*/
api.deleteChallenge = {
method: 'DELETE',
url: '/challenges/:challengeId',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
if (!challenge.canModify(user)) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
// Close channel in background, some ops are run in the background without `await`ing
await challenge.closeChal({ broken: 'CHALLENGE_DELETED' });
res.analytics.track('challenge delete', {
user: pick(user, ['preferences', 'registeredThrough']),
uuid: user._id,
hitType: 'event',
category: 'behavior',
challengeID: challenge._id,
groupID: challenge.group._id,
groupName: challenge.group.privacy === 'private' ? null : challenge.group.name,
groupType: challenge.group._id === TAVERN_ID ? 'tavern' : challenge.group.type,
prize: challenge.prize,
headers: req.headers,
});
res.respond(200, {});
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/selectWinner/:winnerId Select winner for challenge
* @apiName SelectChallengeWinner
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The _id for the challenge to close with a winner
* @apiParam (Path) {UUID} winnerId The _id of the winning user
*
* @apiSuccess {Object} data An empty object
*
* @apiUse ChallengeNotFound
*/
api.selectChallengeWinner = {
method: 'POST',
url: '/challenges/:challengeId/selectWinner/:winnerId',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
req.checkParams('winnerId', res.t('winnerIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
if (!challenge.canModify(user)) throw new NotAuthorized(res.t('onlyLeaderDeleteChal'));
const nonParticipant = !user.challenges
|| (user.challenges
&& user.challenges.findIndex(cId => cId === challenge._id) === -1);
const isFlaggedForNonAdminUser = challenge.flagCount > 1
&& !user.hasPermission('moderator')
&& nonParticipant
&& challenge.leader !== user._id;
if (isFlaggedForNonAdminUser) throw new NotFound(res.t('challengeNotFound'));
const winner = await User.findOne({ _id: req.params.winnerId }).exec();
if (!winner || winner.challenges.indexOf(challenge._id) === -1) throw new NotFound(res.t('winnerNotFound', { userId: req.params.winnerId }));
// Close channel in background, some ops are run in the background without `await`ing
await challenge.closeChal({ broken: 'CHALLENGE_CLOSED', winner });
res.analytics.track('challenge close', {
user: pick(user, ['preferences', 'registeredThrough']),
uuid: user._id,
hitType: 'event',
category: 'behavior',
challengeID: challenge._id,
challengeWinnerID: winner._id,
groupID: challenge.group._id,
groupName: challenge.group.privacy === 'private' ? null : challenge.group.name,
groupType: challenge.group._id === TAVERN_ID ? 'tavern' : challenge.group.type,
prize: challenge.prize,
headers: req.headers,
});
res.respond(200, {});
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/clone Clone a challenge
* @apiName CloneChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The _id for the challenge to clone
*
* @apiSuccess {Object} challenge The cloned challenge
*
* @apiUse ChallengeNotFound
*/
api.cloneChallenge = {
method: 'POST',
url: '/challenges/:challengeId/clone',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challengeToClone = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challengeToClone) throw new NotFound(res.t('challengeNotFound'));
const nonParticipant = !user.challenges
|| (user.challenges
&& user.challenges.findIndex(cId => cId === challengeToClone._id) === -1);
const isFlaggedForNonAdminUser = challengeToClone.flagCount > 1
&& !user.hasPermission('moderator')
&& nonParticipant
&& challengeToClone.leader !== user._id;
if (isFlaggedForNonAdminUser) throw new NotFound(res.t('challengeNotFound'));
const { savedChal } = await createChallenge(user, req, res);
const challengeTaskIds = [
...challengeToClone.tasksOrder.habits,
...challengeToClone.tasksOrder.dailys,
...challengeToClone.tasksOrder.todos,
...challengeToClone.tasksOrder.rewards,
];
const challengeTasks = await Promise.all(challengeTaskIds.map(async taskId => {
const task = Tasks.Task.findById(taskId).exec();
return task;
}));
// last task should be added first and vice-versa, since new tasks are prepended
challengeTasks.reverse();
const tasksToClone = challengeTasks.map(task => {
const clonedTask = cloneDeep(task.toObject());
const omittedTask = cleanUpTask(clonedTask);
return omittedTask;
});
const taskRequest = {
body: tasksToClone,
};
const clonedTasks = await createTasks(taskRequest, res, { user, challenge: savedChal });
res.respond(200, { clonedTasks, clonedChallenge: savedChal });
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/flag Flag a challenge
* @apiName FlagChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The _id for the challenge to flag
* @apiParam (Body) {String} [comment] Why the message was flagged
*
* @apiSuccess {Object} data The flagged challenge message
*
* @apiUse ChallengeNotFound
*/
api.flagChallenge = {
method: 'POST',
url: '/challenges/:challengeId/flag',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
await flagChallenge(challenge, user, res);
await notifyOfFlaggedChallenge(challenge, user, req.body.comment);
res.respond(200, { challenge });
},
};
/**
* @api {post} /api/v3/challenges/:challengeId/clearflags Clears flags on a challenge
* @apiName ClearFlagsChallenge
* @apiGroup Challenge
*
* @apiParam (Path) {UUID} challengeId The _id for the challenge to clear flags from
*
* @apiSuccess {Object} data The flagged challenge message
*
* @apiUse ChallengeNotFound
*/
api.clearFlagsChallenge = {
method: 'POST',
url: '/challenges/:challengeId/clearflags',
middlewares: [authWithHeaders()],
async handler (req, res) {
const { user } = res.locals;
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
const validationErrors = req.validationErrors();
if (validationErrors) throw validationErrors;
if (!user.hasPermission('moderator')) {
throw new NotAuthorized(res.t('messageGroupChatAdminClearFlagCount'));
}
const challenge = await Challenge.findOne({ _id: req.params.challengeId }).exec();
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
await clearFlags(challenge, user);
res.respond(200, { challenge });
},
};
export default api;