mirror of
https://github.com/HabitRPG/habitica.git
synced 2025-12-17 22:57:21 +01:00
API v3 [WIP] (#6144)
* Fixed more tests * Added tags into user service * Added api-v3 auth urls * v3: fix package.json * v3: fix package.json * Fixed auth tests. Updated Authctrl response * v3: remove newrelic config file in favour of env variables * v3: upgrade some deps * switch from Q to Bluebird * v3 fix tests with deferred * Removed extra consoles.log. Changed data.data to res.data * v3 fix tests and use coroutines instead of regenerator * v3: fix tests * v3: do not await a non promise * v3: q -> bluebird * Changed id param for registration response * Updated party query and create * Ensured login callback happens after user sync * Add challenges to groups. Fixed isMemberOfGuild check * Updated party and group tests * Fixed cron test * return user.id and send analytics event before changing page * fix trailing spaces * disable redirects * Api v3 party tavern fixes (#7191) * Added check if user is in party before query * Cached party query. Prevented party request when user is not in party. Updated Party create with no invites * Update tavern ctrl to use new promise * v3: misc fixes * Api v3 task fixes (#7193) * Update task view to use _id * Added try catch to user service ops calls * v3 client: saving after syncing is complete * Fixed test broken by part sync change (#7195) * v3: fix todo scoring and try to fix production testing problem * revert changes to mongoose config * mongoose: increase keepAlive * test mongoose fix * fix: Only apply captureStackTrace if it exists on the error object * v3: fix reminders with no startDate * mongoose: use options * chore(): rename website/src -> website/server and website/public -> website/client (#7199) * v3 fix GET /groups: return an error only if an invalid type is supplied not when there are 0 results (#7203) * [API v3] Fix calls to user.ops and deleting tags (#7204) * v3: fixes calls to user.ops from views and deleting tags * v3: fix tests that use user._statsComputed * Api v3 fixes continued (#7205) * Added timzeone offset back * Added APIToken back to settings page * Fixed fetch recent messages for party * Fixed returning group description * Fixed check if user is member of challenge * Fixed party members appearing in header * Updated get myGroups param to include public groups. Fixed isMemberOf group * Fixed hourglass purchase * Fixed challenge addding tasks on first creating * Updated tests to accomidate new changes * fix: Correct checklist on client Closes #7207 * fix: Pin eslint to 2.9 * minor improvements to cron code for clarity; fix inaccurate comments; add TODOs for rest-in-inn actions * fix: Add missing type param to equip call closes #7212 * rename and reword pubChalsMinPrize to reflect that it's only for Tavern challenges * allows players to send gems to each other; other minor related changes - fixes https://github.com/HabitRPG/habitrpg/issues/7227 * fix tests for /members/transfer-gems * fix: Set gems sent notification as translatable string * chore: Remove unusued variable * fix: Remove requirement on message paramter in transfer-gems * add a missing variable declaration * chore: clarify comments on cron code * fix: Correct client request from habitrpg -> tavern * update apidoc URL in package.json Closes #7222 * Fixed start party by invites * Updated spell casting to v3 * Fixed adding and removing tags on tasks * Fixed page reload on settings change * Fixed battle monsters with friends button * Loaded completed todos when done is clicked * chore: Reinstate floating version number for eslint babel-eslint regression fixed * Fixed reload tests * change "an user" to "a user" in comments and text (no code changes) (#7257) * fix: Alert user that drops were recieved * remove userServices.js from karma.conf - it's been moved to website/client/js/services * feat: Create debug update user route * fix: Correct set cron debug function * feat: Add make admin button to debug menu * lint: Add missing semicolons in test * fix: Temporarilly comment out udpate user debug route * v3: fix _tmp for crit and streakBonus * v3: execute all actions when leaving a solo party * v3 client: fix group not found when leaving party * v3 migration: fix challenge prize * v3 cron: only save modified tasks * v3: add CHALLENGE_TASK_NOT_FOUND to valid broken reasons * v3: fix tasks chart * v3 client: fix ability to leave challenge * v3 client: fix filtering by tag and correctly show tag tooltip * v3 common: fix tags tests * v3 client: support unlinking not found challenges tasks * v3: disable Bluebird warning for missing return, fixes #7269 * feat: Separate out update-user into set-cron and make-admin debug routes * chore: Disable make admin debug route for v3 prod testing * v3: misc fixes * v3: misc fixes * v3: fix adding multiple tasks * Fixed join/leave button updates * Queried only user groups to be available when creating challenges * Fixed bulk add tasks to challenge * Synced challenge tasks after leave and join. * Fixed default selected group * Fixed challenge member info. Fixed challenge winner selection * Fixed deleting challenge tasks * Fixed particiapting filter * v3 client: fix casting spells * v3: do not log sensitive data * v3: always save user when casting spell * v3: always save user when casting spell * v3: more fixes for spells * fix typos and missing information in apidocs - fixes https://github.com/HabitRPG/habitrpg/issues/7277 (#7282) * v3: add TODO for client side spells * feat: Add modify inventory debug menu * Fixed viewing user progress on challenge * Updated tests * fix: Fix quest progress button * fix incorrect Armoire test; remove unneeded param details from apidocs; disambiguate health potion * v3: fix stealth casting * v3: fix tasks saving and selection for rebirth reroll and reset (server-only) * v3: fix auto allocation * v3 client: misc fixes * rename buyPotion and buy-potion to buyHealthPotion and buy-health-potion; fix apidoc param error * Added delete for saved challenge task * Fixed member modal on front page * adjust text in apidocs for errors / clarity / consistency / standard terminology (no code changes) (#7298) * fix bug in Rebirth test, add new tests, adjust apidocs (#7293) * Updated task model to allow setting streak (#7306) * fix: Correct missing * in apidoc comments * Api v3 challenge fixes (#7287) * Fixed join/leave button updates * Queried only user groups to be available when creating challenges * Fixed bulk add tasks to challenge * Synced challenge tasks after leave and join. * Fixed default selected group * Fixed challenge member info. Fixed challenge winner selection * Fixed deleting challenge tasks * Fixed particiapting filter * Fixed viewing user progress on challenge * Updated tests * Added delete for saved challenge task * v3: fix sorting * [API v3] add CRON_SAFE_MODE (#7286) * add CRON_SAFE_MODE to example config file, fix some bugs, add an unrelated low-priority TODO * create CRON_SAFE_MODE to disable parts of cron for use after extended outage - fixes https://github.com/HabitRPG/habitrpg/issues/7161 * fix a bug with CRON_SAFE_MODE, remove duplicated code, remove completed TODO comment * fix check for CRON_SAFE_MODE * v3 client: fix typo * adjust debug menu Modify Inventory: hungrier pets, fewer Special items, "Hide" buttons * completed To-Dos: return the 30 most recent instead of 30 oldest (#7318) * v3 migration: fix createdAt date * adjust locales text, key names, and files for Rebirth, Reset, and Fortify / ReRoll for consistency with existing strings (#7321) * v3: fix unlinking multiple tasks * v3 fix releasing pets * v3: fix authenticating with apiUrl * v3: fix typo * v3 fix client tests for unlinking * v3 client: do not show start quest button when quest is active * v3 client: fix ability to send cards * v3 client: fix misc challenge issues * v3: fix notifications * v3 client: more user friendly errors * v3 client: only load completed todos once * v3 client: fix tests * v3: move TAVERN_ID to common code * fix: Provide default type and text for new task creation in score route * fix: Provide default history [] for habit in score route * fix: Add _legacyId prop to tasks to support non-uuid identifiers * chore: Change v3 migration to use _legacyId instead of legacyId * fix: check for _legacyId in tasks if id does not exist * refactor: Extract out finding task by id or _legacyId into a function * Api v3 party quest fixes (#7341) * Fix display of add challenge message when group challenges are empty * Fixed forced quest start to update quest without reload * Fixed needing to reload when accepting party invite * Fix group leave and join reload * Fixed leave current party and join another * Updated party tests * v3 client: remove console.log statement * v3: misc fixes * v3 client: fix predicatbale random * v3: info about API v3 * v3: update footer with links to developer resources * v3: support party invitation from email * v3 client: fix chat flagging * fix: Correct get tasks route to properly get todos (#7349) * move locales strings from api-v3.json to other locales files (#7347) * move locales strings from api-v3.json: authentication strings -> front.json * move locales strings from api-v3.json: authentication strings -> tasks.json * move locales strings from api-v3.json: authentication strings -> groups.json * move locales strings from api-v3.json: authentication strings -> challenge.json * move locales strings from api-v3.json: authentication strings -> groups.json (again) * move locales strings from api-v3.json: authentication strings -> quests.json * move locales strings from api-v3.json: authentication strings -> subscriber.json * move locales strings from api-v3.json: authentication strings -> spells.json * move locales strings from api-v3.json: authentication strings -> character.json * move locales strings from api-v3.json: authentication strings -> groups.json (PMs) * move locales strings from api-v3.json: authentication strings -> npc.json * move locales strings from api-v3.json: authentication strings -> pets.json * move locales strings from api-v3.json: authentication strings -> miscellaneous * move locales strings from api-v3.json: authentication strings -> contrib.json and settings.json * move locales strings from api-v3.json: delete unused string (invalidTasksOwner), delete api-v3.json, whitespace cleanup * v3 client: fix sticky header * v3: remove unused code * v3 client: correctly redirect after inviting * Removed v2 calls from views (#7351) * v3: fix tests for challenge export * v3: fallbackto authWithHeaders if wuthWithSession or authWithUrl fails * Added force cache update when fetching new messages (#7360) * v3: fetch whole user when booting from group tto avoid issues with pre save hook expecting all data * v3: misc fixes for payments * v3: limit fields of challenge tasks that can be updated * fix(tests): never connect to NODE_DB_URI for tests * Added new route for setting last cron and updated front end * v3: fix iap url * v3: fix build and ios IAP * Changed route to user set custom day start * v3: iap accessible under /api/v3, fixes to spells and groups invitations * v3: correctly use v3 routes in client * remove XP, GP when unticking a Daily with a completed checklist - fixes https://github.com/HabitRPG/habitrpg/issues/7246 * use natural language for error message about skills on challenge tasks (#7336), fix other gramatical error * Updated ui when user rejects a guild invite (#7368) * feat: complete custom day start route Closes #7363 * fix: Correct spelling of healAll skill fix: Correct sprite name of healAll skill * fix: Change all instances of spookDust -> spookySparkles * add dateCreated to all tasks; add empty challenge object to tasks that don't have one (#7386) * add plumilla to artists for Tangle Tree in Bailey message * Fixed quest drop modal (#7377) * Fixed quest drop modal * Fixed broken party test * [API v3] Maintenance Mode (#7367) * WIP(maintenance): maintenance * WIP(maintenance): working locale features * fix(maintenance): don't translate info page target * WIP(maintenance): start adding info page * fix(maintenance): linting * feat: Add container to maintenance info page * fix(maintenance): add config.json edits Also DRY variables for main vs info pages * fix(maintenance): linting * refactor(maintenance): further slim down variables * refactor: Remove unnecessary variables * fix: Correct string interpolation in maintenace view * feat: Dynamically add time to maintenance pages * maintenance mode: do not connect to mongodb * fix(maintenance): clean up timezones etc. * fix(maintenance): remove unneeded sprite * Tavern party challenges invites fix (#7394) * Added challenges and invitations to party * Loaded tavern challenges * Updated group and quest services tests * v3: implement automatic syncing if user is not up to date * Removed unnecessary fields when updating groups and challenges (#7395) * v3: do not saved populated user * v3: correctly return user subset * Chained party promises together (#7396) * v3: $w -> splitWhitespace * use bluebird * use babel polyfill * migration: fix items * update links for v3 * Updated shortname validation to support multiple browsers * Docs changes (#7401) * chore: Clarify transfer-gems documentation * chore: Clarify api status route documentation * chore: Mark webhooks as BETA * Added tags update route. Added sort to user service (#7381) * Added tags update route. Added sort to user service * Change update tasks route to reorder tasks * Fixed linting issue * Changed params for reorder tags route * Fixed not found tag and added test * Added password confirmation when deleteing account (#7402) * fix production logging * feat(commit): push * empty commit * feat(maintenance): post-downtime news & awards (#7406) * fix exporting avatar * second attempt at fixing exporting avatar * fix production logging * s3: convert moment to date instance * fix avatar sharing and caching (30 minutes) * fix: Correct missing parameter Closes #7433 * fix: Validate challenge shortname on server * adjust text strings - fixes https://github.com/HabitRPG/habitrpg/issues/5631 and also Short Name -> Tag Name
This commit is contained in:
512
website/server/controllers/api-v3/auth.js
Normal file
512
website/server/controllers/api-v3/auth.js
Normal file
@@ -0,0 +1,512 @@
|
||||
import validator from 'validator';
|
||||
import moment from 'moment';
|
||||
import passport from 'passport';
|
||||
import nconf from 'nconf';
|
||||
import {
|
||||
authWithHeaders,
|
||||
} from '../../middlewares/api-v3/auth';
|
||||
import {
|
||||
NotAuthorized,
|
||||
BadRequest,
|
||||
NotFound,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import Bluebird from 'bluebird';
|
||||
import * as passwordUtils from '../../libs/api-v3/password';
|
||||
import logger from '../../libs/api-v3/logger';
|
||||
import { model as User } from '../../models/user';
|
||||
import { model as Group } from '../../models/group';
|
||||
import { model as EmailUnsubscription } from '../../models/emailUnsubscription';
|
||||
import { sendTxn as sendTxnEmail } from '../../libs/api-v3/email';
|
||||
import { decrypt } from '../../libs/api-v3/encryption';
|
||||
import FirebaseTokenGenerator from 'firebase-token-generator';
|
||||
import { send as sendEmail } from '../../libs/api-v3/email';
|
||||
|
||||
let api = {};
|
||||
|
||||
// When the user signed up after having been invited to a group, invite them automatically to the group
|
||||
async function _handleGroupInvitation (user, invite) {
|
||||
// wrapping the code in a try because we don't want it to prevent the user from signing up
|
||||
// that's why errors are not translated
|
||||
try {
|
||||
let {sentAt, id: groupId, inviter} = JSON.parse(decrypt(invite));
|
||||
|
||||
// check that the invite has not expired (after 7 days)
|
||||
if (sentAt && moment().subtract(7, 'days').isAfter(sentAt)) {
|
||||
let err = new Error('Invite expired.');
|
||||
err.privateData = invite;
|
||||
throw err;
|
||||
}
|
||||
|
||||
let group = await Group.getGroup({user, optionalMembership: true, groupId, fields: 'name type'});
|
||||
if (!group) throw new NotFound('Group not found.');
|
||||
|
||||
if (group.type === 'party') {
|
||||
user.invitations.party = {id: group._id, name: group.name, inviter};
|
||||
} else {
|
||||
user.invitations.guilds.push({id: group._id, name: group.name, inviter});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/auth/local/register Register
|
||||
* @apiDescription Register a new user with email, username and password or attach local auth to a social user
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserRegisterLocal
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {String} username Body parameter - Username of the new user
|
||||
* @apiParam {String} email Body parameter - Email address of the new user
|
||||
* @apiParam {String} password Body parameter - Password for the new user
|
||||
* @apiParam {String} confirmPassword Body parameter - Password confirmation
|
||||
*
|
||||
* @apiSuccess {Object} data The user object, if local auth was just attached to a social user then only user.auth.local
|
||||
*/
|
||||
api.registerLocal = {
|
||||
method: 'POST',
|
||||
middlewares: [authWithHeaders(true)],
|
||||
url: '/user/auth/local/register',
|
||||
async handler (req, res) {
|
||||
let fbUser = res.locals.user; // If adding local auth to social user
|
||||
|
||||
req.checkBody({
|
||||
email: {
|
||||
notEmpty: {errorMessage: res.t('missingEmail')},
|
||||
isEmail: {errorMessage: res.t('notAnEmail')},
|
||||
},
|
||||
username: {notEmpty: {errorMessage: res.t('missingUsername')}},
|
||||
password: {
|
||||
notEmpty: {errorMessage: res.t('missingPassword')},
|
||||
equals: {options: [req.body.confirmPassword], errorMessage: res.t('passwordConfirmationMatch')},
|
||||
},
|
||||
});
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let { email, username, password } = req.body;
|
||||
|
||||
// Get the lowercase version of username to check that we do not have duplicates
|
||||
// So we can search for it in the database and then reject the choosen username if 1 or more results are found
|
||||
email = email.toLowerCase();
|
||||
let lowerCaseUsername = username.toLowerCase();
|
||||
|
||||
// Search for duplicates using lowercase version of username
|
||||
let user = await User.findOne({$or: [
|
||||
{'auth.local.email': email},
|
||||
{'auth.local.lowerCaseUsername': lowerCaseUsername},
|
||||
]}, {'auth.local': 1}).exec();
|
||||
|
||||
if (user) {
|
||||
if (email === user.auth.local.email) throw new NotAuthorized(res.t('emailTaken'));
|
||||
// Check that the lowercase username isn't already used
|
||||
if (lowerCaseUsername === user.auth.local.lowerCaseUsername) throw new NotAuthorized(res.t('usernameTaken'));
|
||||
}
|
||||
|
||||
let salt = passwordUtils.makeSalt();
|
||||
let hashed_password = passwordUtils.encrypt(password, salt); // eslint-disable-line camelcase
|
||||
let newUser = {
|
||||
auth: {
|
||||
local: {
|
||||
username,
|
||||
lowerCaseUsername,
|
||||
email,
|
||||
salt,
|
||||
hashed_password, // eslint-disable-line camelcase
|
||||
},
|
||||
},
|
||||
preferences: {
|
||||
language: req.language,
|
||||
},
|
||||
};
|
||||
|
||||
if (fbUser) {
|
||||
if (!fbUser.auth.facebook.id) throw new NotAuthorized(res.t('onlySocialAttachLocal'));
|
||||
fbUser.auth.local = newUser.auth.local;
|
||||
newUser = fbUser;
|
||||
} else {
|
||||
newUser = new User(newUser);
|
||||
newUser.registeredThrough = req.headers['x-client']; // Not saved, used to create the correct tasks based on the device used
|
||||
}
|
||||
|
||||
// we check for partyInvite for backward compatibility
|
||||
if (req.query.groupInvite || req.query.partyInvite) {
|
||||
await _handleGroupInvitation(newUser, req.query.groupInvite || req.query.partyInvite);
|
||||
}
|
||||
|
||||
let savedUser = await newUser.save();
|
||||
|
||||
if (savedUser.auth.facebook.id) {
|
||||
res.respond(200, savedUser.toJSON().auth.local); // We convert to toJSON to hide private fields
|
||||
} else {
|
||||
res.respond(201, savedUser);
|
||||
}
|
||||
|
||||
// Clean previous email preferences and send welcome email
|
||||
EmailUnsubscription
|
||||
.remove({email: savedUser.auth.local.email})
|
||||
.then(() => sendTxnEmail(savedUser, 'welcome'));
|
||||
|
||||
if (!savedUser.auth.facebook.id) {
|
||||
res.analytics.track('register', {
|
||||
category: 'acquisition',
|
||||
type: 'local',
|
||||
gaLabel: 'local',
|
||||
uuid: savedUser._id,
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
function _loginRes (user, req, res) {
|
||||
if (user.auth.blocked) throw new NotAuthorized(res.t('accountSuspended', {userId: user._id}));
|
||||
return res.respond(200, {id: user._id, apiToken: user.apiToken});
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/auth/local/login Login
|
||||
* @apiDescription Login a user with email / username and password
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserLoginLocal
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {String} username Body parameter - Username or email of the user
|
||||
* @apiParam {String} password Body parameter - The user's password
|
||||
*
|
||||
* @apiSuccess {String} data._id The user's unique identifier
|
||||
* @apiSuccess {String} data.apiToken The user's api token that must be used to authenticate requests.
|
||||
*/
|
||||
api.loginLocal = {
|
||||
method: 'POST',
|
||||
url: '/user/auth/local/login',
|
||||
middlewares: [],
|
||||
async handler (req, res) {
|
||||
req.checkBody({
|
||||
username: {
|
||||
notEmpty: true,
|
||||
errorMessage: res.t('missingUsernameEmail'),
|
||||
},
|
||||
password: {
|
||||
notEmpty: true,
|
||||
errorMessage: res.t('missingPassword'),
|
||||
},
|
||||
});
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
req.sanitizeBody('username').trim();
|
||||
req.sanitizeBody('password').trim();
|
||||
|
||||
let login;
|
||||
let username = req.body.username;
|
||||
|
||||
if (validator.isEmail(username)) {
|
||||
login = {'auth.local.email': username.toLowerCase()}; // Emails are stored lowercase
|
||||
} else {
|
||||
login = {'auth.local.username': username};
|
||||
}
|
||||
|
||||
let user = await User.findOne(login, {auth: 1, apiToken: 1}).exec();
|
||||
let isValidPassword = user && user.auth.local.hashed_password === passwordUtils.encrypt(req.body.password, user.auth.local.salt);
|
||||
if (!isValidPassword) throw new NotAuthorized(res.t('invalidLoginCredentialsLong'));
|
||||
return _loginRes(user, ...arguments);
|
||||
},
|
||||
};
|
||||
|
||||
function _passportFbProfile (accessToken) {
|
||||
return new Bluebird((resolve, reject) => {
|
||||
passport._strategies.facebook.userProfile(accessToken, (err, profile) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(profile);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Called as a callback by Facebook (or other social providers). Internal route
|
||||
api.loginSocial = {
|
||||
method: 'POST',
|
||||
url: '/user/auth/social', // this isn't the most appropriate url but must be the same as v2
|
||||
async handler (req, res) {
|
||||
let accessToken = req.body.authResponse.access_token;
|
||||
let network = req.body.network;
|
||||
|
||||
if (network !== 'facebook') throw new NotAuthorized(res.t('onlyFbSupported'));
|
||||
|
||||
let profile = await _passportFbProfile(accessToken);
|
||||
|
||||
let user = await User.findOne({
|
||||
[`auth.${network}.id`]: profile.id,
|
||||
}, {_id: 1, apiToken: 1, auth: 1}).exec();
|
||||
|
||||
// User already signed up
|
||||
if (user) {
|
||||
_loginRes(user, ...arguments);
|
||||
} else { // Create new user
|
||||
user = new User({
|
||||
auth: {
|
||||
[network]: profile,
|
||||
},
|
||||
preferences: {
|
||||
language: req.language,
|
||||
},
|
||||
});
|
||||
user.registeredThrough = req.headers['x-client'];
|
||||
|
||||
let savedUser = await user.save();
|
||||
|
||||
_loginRes(user, ...arguments);
|
||||
|
||||
// Clean previous email preferences
|
||||
if (savedUser.auth[network].emails && savedUser.auth.facebook.emails[0] && savedUser.auth[network].emails[0].value) {
|
||||
EmailUnsubscription
|
||||
.remove({email: savedUser.auth[network].emails[0].value.toLowerCase()})
|
||||
.exec()
|
||||
.then(() => sendTxnEmail(savedUser, 'welcome')); // eslint-disable-line max-nested-callbacks
|
||||
}
|
||||
|
||||
res.analytics.track('register', {
|
||||
category: 'acquisition',
|
||||
type: network,
|
||||
gaLabel: network,
|
||||
uuid: savedUser._id,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/user/auth/update-username Update username
|
||||
* @apiDescription Update the username of a local user
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateUsername
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {string} password Body parameter - The current user password
|
||||
* @apiParam {string} username Body parameter - The new username
|
||||
|
||||
* @apiSuccess {String} data.username The new username
|
||||
**/
|
||||
api.updateUsername = {
|
||||
method: 'PUT',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/auth/update-username',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkBody({
|
||||
password: {
|
||||
notEmpty: {errorMessage: res.t('missingPassword')},
|
||||
},
|
||||
username: {
|
||||
notEmpty: { errorMessage: res.t('missingUsername') },
|
||||
},
|
||||
});
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
if (!user.auth.local.username) throw new BadRequest(res.t('userHasNoLocalRegistration'));
|
||||
|
||||
let oldPassword = passwordUtils.encrypt(req.body.password, user.auth.local.salt);
|
||||
if (oldPassword !== user.auth.local.hashed_password) throw new NotAuthorized(res.t('wrongPassword'));
|
||||
|
||||
let count = await User.count({ 'auth.local.lowerCaseUsername': req.body.username.toLowerCase() });
|
||||
if (count > 0) throw new BadRequest(res.t('usernameTaken'));
|
||||
|
||||
// save username
|
||||
user.auth.local.lowerCaseUsername = req.body.username.toLowerCase();
|
||||
user.auth.local.username = req.body.username;
|
||||
await user.save();
|
||||
|
||||
res.respond(200, { username: req.body.username });
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/user/auth/update-password
|
||||
* @apiDescription Update the password of a local user
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdatePassword
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {string} password Body parameter - The old password
|
||||
* @apiParam {string} newPassword Body parameter - The new password
|
||||
* @apiParam {string} confirmPassword Body parameter - New password confirmation
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
**/
|
||||
api.updatePassword = {
|
||||
method: 'PUT',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/auth/update-password',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
if (!user.auth.local.hashed_password) throw new BadRequest(res.t('userHasNoLocalRegistration'));
|
||||
|
||||
let oldPassword = passwordUtils.encrypt(req.body.password, user.auth.local.salt);
|
||||
if (oldPassword !== user.auth.local.hashed_password) throw new NotAuthorized(res.t('wrongPassword'));
|
||||
|
||||
req.checkBody({
|
||||
password: {
|
||||
notEmpty: {errorMessage: res.t('missingNewPassword')},
|
||||
},
|
||||
newPassword: {
|
||||
notEmpty: {errorMessage: res.t('missingPassword')},
|
||||
},
|
||||
});
|
||||
|
||||
if (req.body.newPassword !== req.body.confirmPassword) throw new NotAuthorized(res.t('passwordConfirmationMatch'));
|
||||
|
||||
user.auth.local.hashed_password = passwordUtils.encrypt(req.body.newPassword, user.auth.local.salt); // eslint-disable-line camelcase
|
||||
await user.save();
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/reset-password Reset password
|
||||
* @apiDescription Reset the user password
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ResetPassword
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {string} email Body parameter - The email address of the user
|
||||
*
|
||||
* @apiSuccess {string} message The localized success message
|
||||
**/
|
||||
api.resetPassword = {
|
||||
method: 'POST',
|
||||
middlewares: [],
|
||||
url: '/user/reset-password',
|
||||
async handler (req, res) {
|
||||
req.checkBody({
|
||||
email: {
|
||||
notEmpty: {errorMessage: res.t('missingEmail')},
|
||||
},
|
||||
});
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let email = req.body.email.toLowerCase();
|
||||
let salt = passwordUtils.makeSalt();
|
||||
let newPassword = passwordUtils.makeSalt(); // use a salt as the new password too (they'll change it later)
|
||||
let hashedPassword = passwordUtils.encrypt(newPassword, salt);
|
||||
|
||||
let user = await User.findOne({ 'auth.local.email': email }, { 'auth.local': 1 });
|
||||
|
||||
if (user) {
|
||||
user.auth.local.salt = salt;
|
||||
user.auth.local.hashed_password = hashedPassword; // eslint-disable-line camelcase
|
||||
sendEmail({
|
||||
from: 'Habitica <admin@habitica.com>',
|
||||
to: email,
|
||||
subject: res.t('passwordResetEmailSubject'),
|
||||
text: res.t('passwordResetEmailText', { username: user.auth.local.username,
|
||||
newPassword,
|
||||
baseUrl: nconf.get('BASE_URL'),
|
||||
}),
|
||||
html: res.t('passwordResetEmailHtml', { username: user.auth.local.username,
|
||||
newPassword,
|
||||
baseUrl: nconf.get('BASE_URL'),
|
||||
}),
|
||||
});
|
||||
await user.save();
|
||||
}
|
||||
res.respond(200, {}, res.t('passwordReset'));
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/user/auth/update-email Update email
|
||||
* @apiDescription Change the user email address
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateEmail
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiParam {string} Body parameter - newEmail The new email address.
|
||||
* @apiParam {string} Body parameter - password The user password.
|
||||
*
|
||||
* @apiSuccess {string} data.email The updated email address
|
||||
*/
|
||||
api.updateEmail = {
|
||||
method: 'PUT',
|
||||
middlewares: [authWithHeaders()],
|
||||
url: '/user/auth/update-email',
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
if (!user.auth.local.email) throw new BadRequest(res.t('userHasNoLocalRegistration'));
|
||||
|
||||
req.checkBody('newEmail', res.t('newEmailRequired')).notEmpty().isEmail();
|
||||
req.checkBody('password', res.t('missingPassword')).notEmpty();
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let candidatePassword = passwordUtils.encrypt(req.body.password, user.auth.local.salt);
|
||||
if (candidatePassword !== user.auth.local.hashed_password) throw new NotAuthorized(res.t('wrongPassword'));
|
||||
|
||||
user.auth.local.email = req.body.newEmail;
|
||||
await user.save();
|
||||
|
||||
return res.respond(200, { email: user.auth.local.email });
|
||||
},
|
||||
};
|
||||
|
||||
const firebaseTokenGenerator = new FirebaseTokenGenerator(nconf.get('FIREBASE:SECRET'));
|
||||
|
||||
// Internal route
|
||||
api.getFirebaseToken = {
|
||||
method: 'POST',
|
||||
url: '/user/auth/firebase',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
// Expires 24 hours from now (60*60*24*1000) (in milliseconds)
|
||||
let expires = new Date();
|
||||
expires.setTime(expires.getTime() + 86400000);
|
||||
|
||||
let token = firebaseTokenGenerator.createToken({
|
||||
uid: user._id,
|
||||
isHabiticaUser: true,
|
||||
}, { expires });
|
||||
|
||||
res.respond(200, {token, expires});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/user/auth/social/:network Delete social authentication method
|
||||
* @apiDescription Remove a social authentication method (only facebook supported) from a user profile. The user must have local authentication enabled
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UserDeleteSocial
|
||||
* @apiGroup User
|
||||
*
|
||||
* @apiSuccess {Object} data Empty object
|
||||
*/
|
||||
api.deleteSocial = {
|
||||
method: 'DELETE',
|
||||
url: '/user/auth/social/:network',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let network = req.params.network;
|
||||
|
||||
if (network !== 'facebook') throw new NotAuthorized(res.t('onlyFbSupported'));
|
||||
if (!user.auth.local.username) throw new NotAuthorized(res.t('cantDetachFb'));
|
||||
|
||||
await User.update({_id: user._id}, {$unset: {'auth.facebook': 1}}).exec();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
518
website/server/controllers/api-v3/challenges.js
Normal file
518
website/server/controllers/api-v3/challenges.js
Normal file
@@ -0,0 +1,518 @@
|
||||
import { authWithHeaders, authWithSession } from '../../middlewares/api-v3/auth';
|
||||
import _ from 'lodash';
|
||||
import { model as Challenge } from '../../models/challenge';
|
||||
import {
|
||||
model as Group,
|
||||
basicFields as basicGroupFields,
|
||||
TAVERN_ID,
|
||||
} from '../../models/group';
|
||||
import {
|
||||
model as User,
|
||||
nameFields,
|
||||
} from '../../models/user';
|
||||
import {
|
||||
NotFound,
|
||||
NotAuthorized,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import * as Tasks from '../../models/task';
|
||||
import Bluebird from 'bluebird';
|
||||
import csvStringify from '../../libs/api-v3/csvStringify';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/challenges Create a new challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CreateChallenge
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiSuccess {object} data The newly created challenge
|
||||
*/
|
||||
api.createChallenge = {
|
||||
method: 'POST',
|
||||
url: '/challenges',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkBody('group', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let groupId = req.body.group;
|
||||
let prize = req.body.prize;
|
||||
|
||||
let group = await Group.getGroup({user, groupId, fields: '-chat', mustBeMember: true});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (!group.isMember(user)) throw new NotAuthorized(res.t('mustBeGroupMember'));
|
||||
|
||||
if (group.leaderOnly && group.leaderOnly.challenges && group.leader !== user._id) {
|
||||
throw new NotAuthorized(res.t('onlyGroupLeaderChal'));
|
||||
}
|
||||
|
||||
if (group._id === TAVERN_ID && prize < 1) {
|
||||
throw new NotAuthorized(res.t('tavChalsMinPrize'));
|
||||
}
|
||||
|
||||
if (prize > 0) {
|
||||
let groupBalance = group.balance && group.leader === user._id ? group.balance : 0;
|
||||
let prizeCost = prize / 4;
|
||||
|
||||
if (prizeCost > user.balance + groupBalance) {
|
||||
throw new NotAuthorized(res.t('cantAfford'));
|
||||
}
|
||||
|
||||
if (groupBalance >= prizeCost) {
|
||||
// Group pays for all of prize
|
||||
group.balance -= prizeCost;
|
||||
} else if (groupBalance > 0) {
|
||||
// User pays remainder of prize cost after group
|
||||
let remainder = prizeCost - group.balance;
|
||||
group.balance = 0;
|
||||
user.balance -= remainder;
|
||||
} else {
|
||||
// User pays for all of prize
|
||||
user.balance -= prizeCost;
|
||||
}
|
||||
}
|
||||
|
||||
group.challengeCount += 1;
|
||||
|
||||
req.body.leader = user._id;
|
||||
req.body.official = user.contributor.admin && req.body.official ? true : false;
|
||||
let challenge = new Challenge(Challenge.sanitize(req.body));
|
||||
|
||||
// First validate challenge so we don't save group if it's invalid (only runs sync validators)
|
||||
let challengeValidationErrors = challenge.validateSync();
|
||||
if (challengeValidationErrors) throw challengeValidationErrors;
|
||||
|
||||
let results = await Bluebird.all([challenge.save({
|
||||
validateBeforeSave: false, // already validate
|
||||
}), group.save()]);
|
||||
let savedChal = results[0];
|
||||
|
||||
await savedChal.syncToUser(user); // (it also saves the user)
|
||||
|
||||
let response = savedChal.toJSON();
|
||||
response.leader = { // the leader is the authenticated user
|
||||
_id: user._id,
|
||||
profile: {name: user.profile.name},
|
||||
};
|
||||
response.group = { // we already have the group data
|
||||
_id: group._id,
|
||||
name: group.name,
|
||||
type: group.type,
|
||||
privacy: group.privacy,
|
||||
};
|
||||
|
||||
res.respond(201, response);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/challenges/:challengeId/join Joins a challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName JoinChallenge
|
||||
* @apiGroup Challenge
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
*
|
||||
* @apiSuccess {object} data The challenge the user joined
|
||||
*/
|
||||
api.joinChallenge = {
|
||||
method: 'POST',
|
||||
url: '/challenges/:challengeId/join',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let challenge = await Challenge.findOne({ _id: req.params.challengeId });
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.isMember(user)) throw new NotAuthorized(res.t('userAlreadyInChallenge'));
|
||||
|
||||
let group = await Group.getGroup({user, groupId: challenge.group, fields: basicGroupFields, optionalMembership: true});
|
||||
if (!group || !challenge.hasAccess(user, group)) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
challenge.memberCount += 1;
|
||||
|
||||
// Add all challenge's tasks to user's tasks and save the challenge
|
||||
let results = await Bluebird.all([challenge.syncToUser(user), challenge.save()]);
|
||||
|
||||
let response = results[1].toJSON();
|
||||
response.group = { // we already have the group data
|
||||
_id: group._id,
|
||||
name: group.name,
|
||||
type: group.type,
|
||||
privacy: group.privacy,
|
||||
};
|
||||
let chalLeader = await User.findById(response.leader).select(nameFields).exec();
|
||||
response.leader = chalLeader ? chalLeader.toJSON({minimize: true}) : null;
|
||||
|
||||
res.respond(200, response);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/challenges/:challengeId/leave Leaves a challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName LeaveChallenge
|
||||
* @apiGroup Challenge
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.leaveChallenge = {
|
||||
method: 'POST',
|
||||
url: '/challenges/:challengeId/leave',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let keep = req.body.keep === 'remove-all' ? 'remove-all' : 'keep-all';
|
||||
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let challenge = await Challenge.findOne({ _id: req.params.challengeId });
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
let group = await Group.getGroup({user, groupId: challenge.group, fields: '_id type privacy'});
|
||||
if (!group || !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
if (!challenge.isMember(user)) throw new NotAuthorized(res.t('challengeMemberNotFound'));
|
||||
|
||||
challenge.memberCount -= 1;
|
||||
|
||||
// Unlink challenge's tasks from user's tasks and save the challenge
|
||||
await Bluebird.all([challenge.unlinkTasks(user, keep), challenge.save()]);
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/challenges/user Get challenges for a user
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetUserChallenges
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiSuccess {Array} data An array of challenges
|
||||
*/
|
||||
api.getUserChallenges = {
|
||||
method: 'GET',
|
||||
url: '/challenges/user',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
let challenges = await Challenge.find({
|
||||
$or: [
|
||||
{_id: {$in: user.challenges}}, // Challenges where the user is participating
|
||||
{group: {$in: user.getGroups()}}, // Challenges in groups where I'm a member
|
||||
{leader: user._id}, // Challenges where I'm the leader
|
||||
],
|
||||
_id: {$ne: '95533e05-1ff9-4e46-970b-d77219f199e9'}, // remove the Spread the Word Challenge for now, will revisit when we fix the closing-challenge bug TODO revisit
|
||||
})
|
||||
.sort('-official -timestamp')
|
||||
// see below why we're not using populate
|
||||
// .populate('group', basicGroupFields)
|
||||
// .populate('leader', nameFields)
|
||||
.exec();
|
||||
|
||||
let resChals = challenges.map(challenge => challenge.toJSON());
|
||||
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
|
||||
await Bluebird.all(resChals.map((chal, index) => {
|
||||
return Bluebird.all([
|
||||
User.findById(chal.leader).select(nameFields).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/group/group:Id Get challenges for a group
|
||||
* @apiDescription Get challenges that the user is a member, public challenges and the ones from the user's groups.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetGroupChallenges
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {groupId} groupId The group _id
|
||||
*
|
||||
* @apiSuccess {Array} data An array of challenges
|
||||
*/
|
||||
api.getGroupChallenges = {
|
||||
method: 'GET',
|
||||
url: '/challenges/groups/:groupId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let challenges = await Challenge.find({group: groupId})
|
||||
.sort('-official -timestamp')
|
||||
// .populate('leader', nameFields) // Only populate the leader as the group is implicit
|
||||
.exec();
|
||||
|
||||
let resChals = challenges.map(challenge => challenge.toJSON());
|
||||
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
|
||||
await Bluebird.all(resChals.map((chal, index) => {
|
||||
return 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 given its id
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetChallenge
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
*
|
||||
* @apiSuccess {object} data The challenge object
|
||||
*/
|
||||
api.getChallenge = {
|
||||
method: 'GET',
|
||||
url: '/challenges/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let challenge = await Challenge.findById(challengeId)
|
||||
// Don't populate the group as we'll fetch it manually later
|
||||
// .populate('leader', nameFields)
|
||||
.exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
// Fetching basic group data
|
||||
let group = await Group.getGroup({user, groupId: challenge.group, fields: basicGroupFields, optionalMembership: true});
|
||||
if (!group || !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
let chalRes = challenge.toJSON();
|
||||
chalRes.group = group.toJSON({minimize: true});
|
||||
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
|
||||
let 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
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ExportChallengeCsv
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
*
|
||||
* @apiSuccess {string} challenge A csv file
|
||||
*/
|
||||
api.exportChallengeCsv = {
|
||||
method: 'GET',
|
||||
url: '/challenges/:challengeId/export/csv',
|
||||
middlewares: [authWithSession],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let challenge = await Challenge.findById(challengeId).select('_id group leader tasksOrder').exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
let 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)
|
||||
|
||||
let [members, tasks] = await Bluebird.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').lean().exec(),
|
||||
]);
|
||||
|
||||
let resArray = members.map(member => [member._id, member.profile.name]);
|
||||
|
||||
// We assume every user in the challenge as at least some data so we can say that members[0] tasks will be at tasks [0]
|
||||
let lastUserId;
|
||||
let index = -1;
|
||||
tasks.forEach(task => {
|
||||
if (task.userId !== lastUserId) {
|
||||
lastUserId = task.userId;
|
||||
index++;
|
||||
}
|
||||
|
||||
resArray[index].push(`${task.type}:${task.text}`, task.value, task.notes);
|
||||
});
|
||||
|
||||
// The first row is going to be UUID name Task Value Notes repeated n times for the n challenge tasks
|
||||
let challengeTasks = _.reduce(challenge.tasksOrder.toObject(), (result, array) => {
|
||||
return result.concat(array);
|
||||
}, []).sort();
|
||||
resArray.unshift(['UUID', 'name']);
|
||||
_.times(challengeTasks.length, () => resArray[0].push('Task', 'Value', 'Notes'));
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'text/csv',
|
||||
'Content-disposition': `attachment; filename=${challengeId}.csv`,
|
||||
});
|
||||
|
||||
let csvRes = await csvStringify(resArray);
|
||||
res.status(200).send(csvRes);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/challenges/:challengeId Update a challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateChallenge
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated challenge
|
||||
*/
|
||||
api.updateChallenge = {
|
||||
method: 'PUT',
|
||||
url: '/challenges/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let challenge = await Challenge.findById(challengeId).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
let group = await Group.getGroup({user, groupId: challenge.group, fields: basicGroupFields, optionalMembership: true});
|
||||
if (!group || !challenge.canView(user, group)) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (!challenge.canModify(user)) throw new NotAuthorized(res.t('onlyLeaderUpdateChal'));
|
||||
|
||||
_.merge(challenge, Challenge.sanitizeUpdate(req.body));
|
||||
|
||||
let savedChal = await challenge.save();
|
||||
let response = savedChal.toJSON();
|
||||
response.group = { // we already have the group data
|
||||
_id: group._id,
|
||||
name: group.name,
|
||||
type: group.type,
|
||||
privacy: group.privacy,
|
||||
};
|
||||
let 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
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName DeleteChallenge
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The _id for the challenge to delete
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.deleteChallenge = {
|
||||
method: 'DELETE',
|
||||
url: '/challenges/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let 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.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/challenges/:challengeId/selectWinner/:winnerId Select winner for challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName SelectChallengeWinner
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The _id for the challenge to close with a winner
|
||||
* @apiParam {UUID} winnerId The _id of the winning user
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.selectChallengeWinner = {
|
||||
method: 'POST',
|
||||
url: '/challenges/:challengeId/selectWinner/:winnerId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('winnerId', res.t('winnerIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let 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'));
|
||||
|
||||
let 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.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
398
website/server/controllers/api-v3/chat.js
Normal file
398
website/server/controllers/api-v3/chat.js
Normal file
@@ -0,0 +1,398 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import {
|
||||
model as Group,
|
||||
TAVERN_ID,
|
||||
} from '../../models/group';
|
||||
import { model as User } from '../../models/user';
|
||||
import {
|
||||
NotFound,
|
||||
NotAuthorized,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import _ from 'lodash';
|
||||
import { removeFromArray } from '../../libs/api-v3/collectionManipulators';
|
||||
import { sendTxn } from '../../libs/api-v3/email';
|
||||
import nconf from 'nconf';
|
||||
import Bluebird from 'bluebird';
|
||||
|
||||
const FLAG_REPORT_EMAILS = nconf.get('FLAG_REPORT_EMAIL').split(',').map((email) => {
|
||||
return { email, canSend: true };
|
||||
});
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/groups/:groupId/chat Get chat messages from a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetChat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Array} data An array of chat messages
|
||||
*/
|
||||
api.getChat = {
|
||||
method: 'GET',
|
||||
url: '/groups/:groupId/chat',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: 'chat'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
res.respond(200, Group.toJSONCleanChat(group, user).chat);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/chat Post chat message to a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName PostCat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {UUID} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {message} Body parameter - message The message to post
|
||||
* @apiParam {previousMsg} previousMsg Query parameter - The previous chat message which will force a return of the full group chat
|
||||
*
|
||||
* @apiSuccess data An array of chat messages if a new message was posted after previousMsg, otherwise the posted message
|
||||
*/
|
||||
api.postChat = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/chat',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
let chatUpdated;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkBody('message', res.t('messageGroupChatBlankMessage')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId});
|
||||
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party' && user.flags.chatRevoked) {
|
||||
throw new NotFound('Your chat privileges have been revoked.');
|
||||
}
|
||||
|
||||
let lastClientMsg = req.query.previousMsg;
|
||||
chatUpdated = lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg ? true : false;
|
||||
|
||||
group.sendChat(req.body.message, user);
|
||||
|
||||
let toSave = [group.save()];
|
||||
|
||||
if (group.type === 'party') {
|
||||
user.party.lastMessageSeen = group.chat[0].id;
|
||||
toSave.push(user.save());
|
||||
}
|
||||
|
||||
let [savedGroup] = await Bluebird.all(toSave);
|
||||
if (chatUpdated) {
|
||||
res.respond(200, {chat: Group.toJSONCleanChat(savedGroup, user).chat});
|
||||
} else {
|
||||
res.respond(200, {message: savedGroup.chat[0]});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/chat/:chatId/like Like a group chat message
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName LikeChat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {groupId} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {chatId} chatId The chat message _id
|
||||
*
|
||||
* @apiSuccess {Object} data The liked chat message
|
||||
*/
|
||||
api.likeChat = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/chat/:chatId/like',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let message = _.find(group.chat, {id: req.params.chatId});
|
||||
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
|
||||
if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatLikeOwnMessage'));
|
||||
|
||||
let update = {$set: {}};
|
||||
|
||||
if (!message.likes) message.likes = {};
|
||||
|
||||
message.likes[user._id] = !message.likes[user._id];
|
||||
update.$set[`chat.$.likes.${user._id}`] = message.likes[user._id];
|
||||
|
||||
await Group.update(
|
||||
{_id: group._id, 'chat.id': message.id},
|
||||
update
|
||||
);
|
||||
res.respond(200, message); // TODO what if the message is flagged and shouldn't be returned?
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/chat/:chatId/like Like a group chat message
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName LikeChat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {groupId} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {chatId} chatId The chat message id
|
||||
*
|
||||
* @apiSuccess {object} data The flagged chat message
|
||||
*/
|
||||
api.flagChat = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/chat/:chatId/flag',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
let message = _.find(group.chat, {id: req.params.chatId});
|
||||
|
||||
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
|
||||
|
||||
if (message.uuid === user._id) throw new NotFound(res.t('messageGroupChatFlagOwnMessage'));
|
||||
|
||||
let author = await User.findOne({_id: message.uuid}, {auth: 1});
|
||||
|
||||
let update = {$set: {}};
|
||||
|
||||
// Log user ids that have flagged the message
|
||||
if (!message.flags) message.flags = {};
|
||||
if (message.flags[user._id] && !user.contributor.admin) throw new NotFound(res.t('messageGroupChatFlagAlreadyReported'));
|
||||
message.flags[user._id] = true;
|
||||
update.$set[`chat.$.flags.${user._id}`] = true;
|
||||
|
||||
// Log total number of flags (publicly viewable)
|
||||
if (!message.flagCount) message.flagCount = 0;
|
||||
if (user.contributor.admin) {
|
||||
// Arbitraty amount, higher than 2
|
||||
message.flagCount = 5;
|
||||
} else {
|
||||
message.flagCount++;
|
||||
}
|
||||
update.$set['chat.$.flagCount'] = message.flagCount;
|
||||
|
||||
await Group.update(
|
||||
{_id: group._id, 'chat.id': message.id},
|
||||
update
|
||||
);
|
||||
|
||||
let reporterEmailContent;
|
||||
if (user.auth.local) {
|
||||
reporterEmailContent = user.auth.local.email;
|
||||
} else if (user.auth.facebook && user.auth.facebook.emails && user.auth.facebook.emails[0]) {
|
||||
reporterEmailContent = user.auth.facebook.emails[0].value;
|
||||
}
|
||||
|
||||
let authorEmailContent;
|
||||
if (author.auth.local) {
|
||||
authorEmailContent = author.auth.local.email;
|
||||
} else if (author.auth.facebook && author.auth.facebook.emails && author.auth.facebook.emails[0]) {
|
||||
authorEmailContent = author.auth.facebook.emails[0].value;
|
||||
}
|
||||
|
||||
let groupUrl;
|
||||
if (group._id === TAVERN_ID) {
|
||||
groupUrl = '/#/options/groups/tavern';
|
||||
} else if (group.type === 'guild') {
|
||||
groupUrl = `/#/options/groups/guilds/${group._id}`;
|
||||
} else {
|
||||
groupUrl = 'party';
|
||||
}
|
||||
|
||||
sendTxn(FLAG_REPORT_EMAILS, 'flag-report-to-mods', [
|
||||
{name: 'MESSAGE_TIME', content: (new Date(message.timestamp)).toString()},
|
||||
{name: 'MESSAGE_TEXT', content: message.text},
|
||||
|
||||
{name: 'REPORTER_USERNAME', content: user.profile.name},
|
||||
{name: 'REPORTER_UUID', content: user._id},
|
||||
{name: 'REPORTER_EMAIL', content: reporterEmailContent},
|
||||
{name: 'REPORTER_MODAL_URL', content: `/static/front/#?memberId=${user._id}`},
|
||||
|
||||
{name: 'AUTHOR_USERNAME', content: message.user},
|
||||
{name: 'AUTHOR_UUID', content: message.uuid},
|
||||
{name: 'AUTHOR_EMAIL', content: authorEmailContent},
|
||||
{name: 'AUTHOR_MODAL_URL', content: `/static/front/#?memberId=${message.uuid}`},
|
||||
|
||||
{name: 'GROUP_NAME', content: group.name},
|
||||
{name: 'GROUP_TYPE', content: group.type},
|
||||
{name: 'GROUP_ID', content: group._id},
|
||||
{name: 'GROUP_URL', content: groupUrl},
|
||||
]);
|
||||
|
||||
res.respond(200, message);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/chat/:chatId/clear-flags Clear a group chat message's flags
|
||||
* @apiDescription Admin-only
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ClearFlags
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {groupId} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {chatId} chatId The chat message id
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
*/
|
||||
api.clearChatFlags = {
|
||||
method: 'Post',
|
||||
url: '/groups/:groupId/chat/:chatId/clearflags',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
let chatId = req.params.chatId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
if (!user.contributor.admin) {
|
||||
throw new NotAuthorized(res.t('messageGroupChatAdminClearFlagCount'));
|
||||
}
|
||||
|
||||
let group = await Group.getGroup({user, groupId});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let message = _.find(group.chat, {id: chatId});
|
||||
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
|
||||
|
||||
message.flagCount = 0;
|
||||
|
||||
await Group.update(
|
||||
{_id: group._id, 'chat.id': message.id},
|
||||
{$set: {'chat.$.flagCount': message.flagCount}}
|
||||
);
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/chat/:chatId/seen Seen a group chat message
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName SeenChat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {groupId} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
*/
|
||||
api.seenChat = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/chat/seen',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
// Do not validate group existence, it doesn't really matter and make it works if the group gets deleted
|
||||
// let group = await Group.getGroup({user, groupId});
|
||||
// if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let update = {$unset: {}};
|
||||
update.$unset[`newMessages.${groupId}`] = true;
|
||||
|
||||
await User.update({_id: user._id}, update).exec();
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/groups/:groupId/chat/:chatId Delete chat message from a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName DeleteChat
|
||||
* @apiGroup Chat
|
||||
*
|
||||
* @apiParam {string} previousMsg Query parameter - The last message fetched by the client so that the whole chat will be returned only if new messages have been posted in the meantime
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {string} chatId The chat message id
|
||||
*
|
||||
* @apiSuccess data The updated chat array or an empty object if no message was posted after previousMsg
|
||||
* @apiSuccess {Object} data An empty object when the previous message was deleted
|
||||
*/
|
||||
api.deleteChat = {
|
||||
method: 'DELETE',
|
||||
url: '/groups/:groupId/chat/:chatId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
let chatId = req.params.chatId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkParams('chatId', res.t('chatIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId, fields: 'chat'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let message = _.find(group.chat, {id: chatId});
|
||||
if (!message) throw new NotFound(res.t('messageGroupChatNotFound'));
|
||||
|
||||
if (user._id !== message.uuid && !user.contributor.admin) {
|
||||
throw new NotAuthorized(res.t('onlyCreatorOrAdminCanDeleteChat'));
|
||||
}
|
||||
|
||||
let lastClientMsg = req.query.previousMsg;
|
||||
let chatUpdated = lastClientMsg && group.chat && group.chat[0] && group.chat[0].id !== lastClientMsg ? true : false;
|
||||
|
||||
await Group.update(
|
||||
{_id: group._id},
|
||||
{$pull: {chat: {id: chatId}}}
|
||||
);
|
||||
|
||||
if (chatUpdated) {
|
||||
let chatRes = Group.toJSONCleanChat(group, user).chat;
|
||||
removeFromArray(chatRes, {id: chatId});
|
||||
res.respond(200, chatRes);
|
||||
} else {
|
||||
res.respond(200, {});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
110
website/server/controllers/api-v3/content.js
Normal file
110
website/server/controllers/api-v3/content.js
Normal file
@@ -0,0 +1,110 @@
|
||||
import common from '../../../../common';
|
||||
import _ from 'lodash';
|
||||
import { langCodes } from '../../libs/api-v3/i18n';
|
||||
import Bluebird from 'bluebird';
|
||||
import fsCallback from 'fs';
|
||||
import path from 'path';
|
||||
import logger from '../../libs/api-v3/logger';
|
||||
|
||||
// Transform fs methods that accept callbacks in ones that return promises
|
||||
const fs = {
|
||||
readFile: Bluebird.promisify(fsCallback.readFile, {context: fsCallback}),
|
||||
writeFile: Bluebird.promisify(fsCallback.writeFile, {context: fsCallback}),
|
||||
stat: Bluebird.promisify(fsCallback.stat, {context: fsCallback}),
|
||||
mkdir: Bluebird.promisify(fsCallback.mkdir, {context: fsCallback}),
|
||||
};
|
||||
|
||||
let api = {};
|
||||
|
||||
function walkContent (obj, lang) {
|
||||
_.each(obj, (item, key, source) => {
|
||||
if (_.isPlainObject(item) || _.isArray(item)) return walkContent(item, lang);
|
||||
if (_.isFunction(item) && item.i18nLangFunc) source[key] = item(lang);
|
||||
});
|
||||
}
|
||||
|
||||
// After the getContent route is called the first time for a certain language
|
||||
// the response is saved on disk and subsequentially served directly from there to reduce computation.
|
||||
// Example: if `cachedContentResponses.en` is true it means that the response is cached
|
||||
let cachedContentResponses = {};
|
||||
|
||||
// Language key set to true while the cache file is being written
|
||||
let cacheBeingWritten = {};
|
||||
|
||||
_.each(langCodes, code => {
|
||||
cachedContentResponses[code] = false;
|
||||
cacheBeingWritten[code] = false;
|
||||
});
|
||||
|
||||
|
||||
const CONTENT_CACHE_PATH = path.join(__dirname, '/../../../build/content_cache/');
|
||||
|
||||
async function saveContentToDisk (language, content) {
|
||||
try {
|
||||
cacheBeingWritten[language] = true;
|
||||
|
||||
await fs.stat(CONTENT_CACHE_PATH); // check if the directory exists, if it doesn't an error is thrown
|
||||
await fs.writeFile(`${CONTENT_CACHE_PATH}${language}.json`, content, 'utf8');
|
||||
|
||||
cacheBeingWritten[language] = false;
|
||||
cachedContentResponses[language] = true;
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT' && err.syscall === 'stat') { // the directory doesn't exists, create it and retry
|
||||
await fs.mkdir(CONTENT_CACHE_PATH);
|
||||
return saveContentToDisk(language, content);
|
||||
} else {
|
||||
cacheBeingWritten[language] = false;
|
||||
logger.error(err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/content Get all available content objects
|
||||
* @apiDescription Does not require authentication.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ContentGet
|
||||
* @apiGroup Content
|
||||
*
|
||||
* @apiParam {string} language Query parameter, the language code used for the items' strings. Defaulting to english
|
||||
*
|
||||
* @apiSuccess {Object} data All the content available on Habitica
|
||||
*/
|
||||
api.getContent = {
|
||||
method: 'GET',
|
||||
url: '/content',
|
||||
async handler (req, res) {
|
||||
let language = 'en';
|
||||
let proposedLang = req.query.language && req.query.language.toString();
|
||||
|
||||
if (proposedLang in cachedContentResponses) {
|
||||
language = proposedLang;
|
||||
}
|
||||
|
||||
let content;
|
||||
|
||||
// is the content response for this language cached?
|
||||
if (cachedContentResponses[language] === true) {
|
||||
content = await fs.readFile(`${CONTENT_CACHE_PATH}${language}.json`, 'utf8');
|
||||
} else { // generate the response
|
||||
content = _.cloneDeep(common.content);
|
||||
walkContent(content, language);
|
||||
content = JSON.stringify(content);
|
||||
}
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
|
||||
let jsonResString = `{"success": true, "data": ${content}}`;
|
||||
res.status(200).send(jsonResString);
|
||||
|
||||
// save the file in background unless it's already cached or being written right now
|
||||
if (cachedContentResponses[language] !== true && cacheBeingWritten[language] !== true) {
|
||||
saveContentToDisk(language, content);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
126
website/server/controllers/api-v3/coupon.js
Normal file
126
website/server/controllers/api-v3/coupon.js
Normal file
@@ -0,0 +1,126 @@
|
||||
import csvStringify from '../../libs/api-v3/csvStringify';
|
||||
import {
|
||||
authWithHeaders,
|
||||
authWithSession,
|
||||
} from '../../middlewares/api-v3/auth';
|
||||
import { ensureSudo } from '../../middlewares/api-v3/ensureAccessRight';
|
||||
import { model as Coupon } from '../../models/coupon';
|
||||
import _ from 'lodash';
|
||||
import couponCode from 'coupon-code';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/coupons Get coupons
|
||||
* @apiDescription Sudo users only
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetCoupons
|
||||
* @apiGroup Coupon
|
||||
*
|
||||
* @apiSuccess {string} Coupons in CSV format
|
||||
*/
|
||||
api.getCoupons = {
|
||||
method: 'GET',
|
||||
url: '/coupons',
|
||||
middlewares: [authWithSession, ensureSudo],
|
||||
async handler (req, res) {
|
||||
let coupons = await Coupon.find().sort('createdAt').lean().exec();
|
||||
|
||||
let output = [['code', 'event', 'date', 'user']].concat(_.map(coupons, coupon => {
|
||||
return [coupon._id, coupon.event, coupon.createdAt, coupon.user];
|
||||
}));
|
||||
let csv = await csvStringify(output);
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'text/csv',
|
||||
'Content-disposition': 'attachment; filename=habitica-coupons.csv',
|
||||
});
|
||||
res.status(200).send(csv);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/coupons/generate/:event Generate coupons for an event
|
||||
* @apiDescription Sudo users only
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GenerateCoupons
|
||||
* @apiGroup Coupon
|
||||
*
|
||||
* @apiParam {string} event The event for which the coupon should be generated
|
||||
* @apiParam {number} count Query parameter to specify the number of coupon codes to generate
|
||||
*
|
||||
* @apiSuccess {array} data Generated coupons
|
||||
*/
|
||||
api.generateCoupons = {
|
||||
method: 'POST',
|
||||
url: '/coupons/generate/:event',
|
||||
middlewares: [authWithHeaders(), ensureSudo],
|
||||
async handler (req, res) {
|
||||
req.checkParams('event', res.t('eventRequired')).notEmpty();
|
||||
req.checkQuery('count', res.t('countRequired')).notEmpty().isNumeric();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let coupons = await Coupon.generate(req.params.event, req.query.count);
|
||||
res.respond(200, coupons);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/user/coupon/:code Enter coupon code
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName EnterCouponCode
|
||||
* @apiGroup Coupon
|
||||
*
|
||||
* @apiParam {string} code The coupon code to apply
|
||||
*
|
||||
* @apiSuccess {object} data User object
|
||||
*/
|
||||
api.enterCouponCode = {
|
||||
method: 'POST',
|
||||
url: '/coupons/enter/:code',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('code', res.t('couponCodeRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
await Coupon.apply(user, req, req.params.code);
|
||||
res.respond(200, user);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/coupons/validate/:code Validate a coupon code
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ValidateCoupon
|
||||
* @apiGroup Coupon
|
||||
*
|
||||
* @apiSuccess {boolean} data.valid True or false
|
||||
*/
|
||||
api.validateCoupon = {
|
||||
method: 'POST',
|
||||
url: '/coupons/validate/:code',
|
||||
middlewares: [authWithHeaders(true)],
|
||||
async handler (req, res) {
|
||||
req.checkParams('code', res.t('couponCodeRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let valid = false;
|
||||
let code = couponCode.validate(req.params.code);
|
||||
if (code) {
|
||||
let coupon = await Coupon.findOne({_id: code}).exec();
|
||||
valid = coupon ? true : false;
|
||||
}
|
||||
|
||||
res.respond(200, {valid});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
190
website/server/controllers/api-v3/debug.js
Normal file
190
website/server/controllers/api-v3/debug.js
Normal file
@@ -0,0 +1,190 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import ensureDevelpmentMode from '../../middlewares/api-v3/ensureDevelpmentMode';
|
||||
import { BadRequest } from '../../libs/api-v3/errors';
|
||||
import { content } from '../../../../common';
|
||||
import _ from 'lodash';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/add-ten-gems Add ten gems to the current user
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AddTenGems
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.addTenGems = {
|
||||
method: 'POST',
|
||||
url: '/debug/add-ten-gems',
|
||||
middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
user.balance += 2.5;
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/add-hourglass Add Hourglass to the current user
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AddHourglass
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.addHourglass = {
|
||||
method: 'POST',
|
||||
url: '/debug/add-hourglass',
|
||||
middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
user.purchased.plan.consecutive.trinkets += 1;
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/set-cron Sets lastCron for user
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName setCron
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.setCron = {
|
||||
method: 'POST',
|
||||
url: '/debug/set-cron',
|
||||
middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let cron = req.body.lastCron;
|
||||
|
||||
user.lastCron = cron;
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/make-admin Sets contributor.admin to true
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName setCron
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
// TODO: Re-enable after v3 prod testing is done
|
||||
// api.makeAdmin = {
|
||||
// method: 'POST',
|
||||
// url: '/debug/make-admin',
|
||||
// middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
// async handler (req, res) {
|
||||
// let user = res.locals.user;
|
||||
//
|
||||
// user.contributor.admin = true;
|
||||
//
|
||||
// await user.save();
|
||||
//
|
||||
// res.respond(200, {});
|
||||
// },
|
||||
// };
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/modify-inventory Manipulate user's inventory
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName modifyInventory
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.modifyInventory = {
|
||||
method: 'POST',
|
||||
url: '/debug/modify-inventory',
|
||||
middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let { gear } = req.body;
|
||||
|
||||
if (gear) {
|
||||
user.items.gear.owned = gear;
|
||||
}
|
||||
|
||||
[
|
||||
'special',
|
||||
'pets',
|
||||
'mounts',
|
||||
'eggs',
|
||||
'hatchingPotions',
|
||||
'food',
|
||||
'quests',
|
||||
].forEach((type) => {
|
||||
if (req.body[type]) {
|
||||
user.items[type] = req.body[type];
|
||||
}
|
||||
});
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/debug/quest-progress Artificially accelerate quest progress
|
||||
* @apiDescription Only available in development mode.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName questProgress
|
||||
* @apiGroup Development
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.questProgress = {
|
||||
method: 'POST',
|
||||
url: '/debug/quest-progress',
|
||||
middlewares: [ensureDevelpmentMode, authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let key = _.get(user, 'party.quest.key');
|
||||
let quest = content.quests[key];
|
||||
|
||||
if (!quest) {
|
||||
throw new BadRequest('User is not on a valid quest.');
|
||||
}
|
||||
|
||||
if (quest.boss) {
|
||||
user.party.quest.progress.up += 1000;
|
||||
}
|
||||
|
||||
if (quest.collect) {
|
||||
let collect = user.party.quest.progress.collect;
|
||||
_.each(quest.collect, (details, item) => {
|
||||
collect[item] = collect[item] || 0;
|
||||
collect[item] += 300;
|
||||
});
|
||||
}
|
||||
|
||||
user.markModified('party.quest.progress');
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
670
website/server/controllers/api-v3/groups.js
Normal file
670
website/server/controllers/api-v3/groups.js
Normal file
@@ -0,0 +1,670 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import Bluebird from 'bluebird';
|
||||
import _ from 'lodash';
|
||||
import {
|
||||
INVITES_LIMIT,
|
||||
model as Group,
|
||||
basicFields as basicGroupFields,
|
||||
} from '../../models/group';
|
||||
import {
|
||||
model as User,
|
||||
nameFields,
|
||||
} from '../../models/user';
|
||||
import { model as EmailUnsubscription } from '../../models/emailUnsubscription';
|
||||
import {
|
||||
NotFound,
|
||||
BadRequest,
|
||||
NotAuthorized,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import { removeFromArray } from '../../libs/api-v3/collectionManipulators';
|
||||
import * as firebase from '../../libs/api-v3/firebase';
|
||||
import { sendTxn as sendTxnEmail } from '../../libs/api-v3/email';
|
||||
import { encrypt } from '../../libs/api-v3/encryption';
|
||||
import common from '../../../../common';
|
||||
import sendPushNotification from '../../libs/api-v3/pushNotifications';
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups Create group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CreateGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiSuccess {Object} data The create group
|
||||
*/
|
||||
api.createGroup = {
|
||||
method: 'POST',
|
||||
url: '/groups',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let group = new Group(Group.sanitize(req.body));
|
||||
group.leader = user._id;
|
||||
|
||||
if (group.type === 'guild') {
|
||||
if (user.balance < 1) throw new NotAuthorized(res.t('messageInsufficientGems'));
|
||||
|
||||
group.balance = 1;
|
||||
|
||||
user.balance--;
|
||||
user.guilds.push(group._id);
|
||||
} else {
|
||||
if (group.privacy !== 'private') throw new NotAuthorized(res.t('partyMustbePrivate'));
|
||||
if (user.party._id) throw new NotAuthorized(res.t('messageGroupAlreadyInParty'));
|
||||
|
||||
user.party._id = group._id;
|
||||
}
|
||||
|
||||
let results = await Bluebird.all([user.save(), group.save()]);
|
||||
let savedGroup = results[1];
|
||||
|
||||
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
|
||||
// await Q.ninvoke(savedGroup, 'populate', ['leader', nameFields]); // doc.populate doesn't return a promise
|
||||
let response = savedGroup.toJSON();
|
||||
// the leader is the authenticated user
|
||||
response.leader = {
|
||||
_id: user._id,
|
||||
profile: {name: user.profile.name},
|
||||
};
|
||||
res.respond(201, response); // do not remove chat flags data as we've just created the group
|
||||
|
||||
firebase.updateGroupData(savedGroup);
|
||||
firebase.addUserToGroup(savedGroup._id, user._id);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/groups Get groups for a user
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetGroups
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} type The type of groups to retrieve. Must be a query string representing a list of values like 'tavern,party'. Possible values are party, guilds, privateGuilds, publicGuilds, tavern
|
||||
*
|
||||
* @apiSuccess {Array} data An array of the requested groups
|
||||
*/
|
||||
api.getGroups = {
|
||||
method: 'GET',
|
||||
url: '/groups',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkQuery('type', res.t('groupTypesRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let types = req.query.type.split(',');
|
||||
let groupFields = basicGroupFields.concat(' description memberCount balance');
|
||||
let sort = '-memberCount';
|
||||
|
||||
let results = await Group.getGroups({user, types, groupFields, sort});
|
||||
res.respond(200, results);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/groups/:groupId Get group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Object} data The group object
|
||||
*/
|
||||
api.getGroup = {
|
||||
method: 'GET',
|
||||
url: '/groups/:groupId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, populateLeader: false});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
group = Group.toJSONCleanChat(group, user);
|
||||
// Instead of populate we make a find call manually because of https://github.com/Automattic/mongoose/issues/3833
|
||||
let leader = await User.findById(group.leader).select(nameFields).exec();
|
||||
if (leader) group.leader = leader.toJSON({minimize: true});
|
||||
|
||||
res.respond(200, group);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/groups/:groupId Update group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Object} data The updated group
|
||||
*/
|
||||
api.updateGroup = {
|
||||
method: 'PUT',
|
||||
url: '/groups/:groupId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
if (group.leader !== user._id) throw new NotAuthorized(res.t('messageGroupOnlyLeaderCanUpdate'));
|
||||
|
||||
_.assign(group, _.merge(group.toObject(), Group.sanitizeUpdate(req.body)));
|
||||
|
||||
let savedGroup = await group.save();
|
||||
let response = Group.toJSONCleanChat(savedGroup, user);
|
||||
// If the leader changed fetch new data, otherwise use authenticated user
|
||||
if (response.leader !== user._id) {
|
||||
response.leader = (await User.findById(response.leader).select(nameFields).exec()).toJSON({minimize: true});
|
||||
} else {
|
||||
response.leader = {
|
||||
_id: user._id,
|
||||
profile: {name: user.profile.name},
|
||||
};
|
||||
}
|
||||
res.respond(200, response);
|
||||
|
||||
firebase.updateGroupData(savedGroup);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/join Join a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName JoinGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {UUID} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Object} data The joined group
|
||||
*/
|
||||
api.joinGroup = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/join',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let inviter;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); // .isUUID(); can't be used because it would block 'habitrpg' or 'party'
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
// Works even if the user is not yet a member of the group
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, optionalMembership: true}); // Do not fetch chat and work even if the user is not yet a member of the group
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let isUserInvited = false;
|
||||
|
||||
if (group.type === 'party' && group._id === user.invitations.party.id) {
|
||||
inviter = user.invitations.party.inviter;
|
||||
user.invitations.party = {}; // Clear invite
|
||||
user.markModified('invitations.party');
|
||||
|
||||
// invite new user to pending quest
|
||||
if (group.quest.key && !group.quest.active) {
|
||||
user.party.quest.RSVPNeeded = true;
|
||||
user.party.quest.key = group.quest.key;
|
||||
group.quest.members[user._id] = null;
|
||||
group.markModified('quest.members');
|
||||
}
|
||||
|
||||
// If user was in a different party (when partying solo you can be invited to a new party)
|
||||
// make him leave that party before doing anything
|
||||
if (user.party._id) {
|
||||
let userPreviousParty = await Group.getGroup({user, groupId: user.party._id});
|
||||
if (userPreviousParty) await userPreviousParty.leave(user);
|
||||
}
|
||||
|
||||
user.party._id = group._id; // Set group as user's party
|
||||
|
||||
isUserInvited = true;
|
||||
} else if (group.type === 'guild') {
|
||||
let hasInvitation = removeFromArray(user.invitations.guilds, { id: group._id });
|
||||
|
||||
if (hasInvitation) {
|
||||
isUserInvited = true;
|
||||
} else {
|
||||
isUserInvited = group.privacy === 'private' ? false : true;
|
||||
}
|
||||
}
|
||||
|
||||
if (isUserInvited && group.type === 'guild') {
|
||||
if (user.guilds.indexOf(group._id) !== -1) { // if user is already a member (party is checked previously)
|
||||
throw new NotAuthorized(res.t('userAlreadyInGroup'));
|
||||
}
|
||||
user.guilds.push(group._id); // Add group to user's guilds
|
||||
}
|
||||
if (!isUserInvited) throw new NotAuthorized(res.t('messageGroupRequiresInvite'));
|
||||
|
||||
if (group.memberCount === 0) group.leader = user._id; // If new user is only member -> set as leader
|
||||
|
||||
group.memberCount += 1;
|
||||
|
||||
let promises = [group.save(), user.save()];
|
||||
|
||||
if (group.type === 'party' && inviter) {
|
||||
promises.push(User.update({_id: inviter}, {$inc: {'items.quests.basilist': 1}}).exec()); // Reward inviter
|
||||
if (group.memberCount > 1) {
|
||||
promises.push(User.update({$or: [{'party._id': group._id}, {_id: user._id}], 'achievements.partyUp': {$ne: true}}, {$set: {'achievements.partyUp': true}}, {multi: true}).exec());
|
||||
}
|
||||
if (group.memberCount > 3) {
|
||||
promises.push(User.update({$or: [{'party._id': group._id}, {_id: user._id}], 'achievements.partyOn': {$ne: true}}, {$set: {'achievements.partyOn': true}}, {multi: true}).exec());
|
||||
}
|
||||
}
|
||||
|
||||
promises = await Bluebird.all(promises);
|
||||
|
||||
let response = Group.toJSONCleanChat(promises[0], user);
|
||||
let leader = await User.findById(response.leader).select(nameFields).exec();
|
||||
if (leader) {
|
||||
response.leader = leader.toJSON({minimize: true});
|
||||
}
|
||||
res.respond(200, response);
|
||||
|
||||
firebase.addUserToGroup(group._id, user._id);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/reject Reject a group invitation
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName RejectGroupInvite
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {UUID} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
*/
|
||||
api.rejectGroupInvite = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/reject-invite',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); // .isUUID(); can't be used because it would block 'habitrpg' or 'party'
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let groupId = req.params.groupId;
|
||||
let isUserInvited = false;
|
||||
|
||||
if (groupId === user.invitations.party.id) {
|
||||
user.invitations.party = {};
|
||||
user.markModified('invitations.party');
|
||||
isUserInvited = true;
|
||||
} else {
|
||||
let hasInvitation = removeFromArray(user.invitations.guilds, { id: groupId });
|
||||
|
||||
if (hasInvitation) {
|
||||
isUserInvited = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUserInvited) throw new NotAuthorized(res.t('messageGroupRequiresInvite'));
|
||||
|
||||
await user.save();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/leave Leave a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName LeaveGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {string="remove-all","keep-all"} keep Query parameter - Whether to keep or not challenges' tasks. Defaults to keep-all
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
*/
|
||||
api.leaveGroup = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/leave',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
// When removing the user from challenges, should we keep the tasks?
|
||||
req.checkQuery('keep', res.t('keepOrRemoveAll')).optional().isIn(['keep-all', 'remove-all']);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: '-chat', requireMembership: true});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
// During quests, checke wheter user can leave
|
||||
if (group.type === 'party') {
|
||||
if (group.quest && group.quest.leader === user._id) {
|
||||
throw new NotAuthorized(res.t('questLeaderCannotLeaveGroup'));
|
||||
}
|
||||
|
||||
if (group.quest && group.quest.active && group.quest.members && group.quest.members[user._id]) {
|
||||
throw new NotAuthorized(res.t('cannotLeaveWhileActiveQuest'));
|
||||
}
|
||||
}
|
||||
|
||||
await group.leave(user, req.query.keep);
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
// Send an email to the removed user with an optional message from the leader
|
||||
function _sendMessageToRemoved (group, removedUser, message) {
|
||||
if (removedUser.preferences.emailNotifications.kickedGroup !== false) {
|
||||
sendTxnEmail(removedUser, `kicked-from-${group.type}`, [
|
||||
{name: 'GROUP_NAME', content: group.name},
|
||||
{name: 'MESSAGE', content: message},
|
||||
{name: 'GUILDS_LINK', content: '/#/options/groups/guilds/public'},
|
||||
{name: 'PARTY_WANTED_GUILD', content: '/#/options/groups/guilds/f2db2a7f-13c5-454d-b3ee-ea1f5089e601'},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/removeMember/:memberId Remove a member from a group
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName RemoveGroupMember
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
* @apiParam {UUID} memberId The _id of the member to remove
|
||||
* @apiParam {string} message Query parameter - The message to send to the removed members
|
||||
*
|
||||
* @apiSuccess {Object} data An empty object
|
||||
*/
|
||||
api.removeGroupMember = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/removeMember/:memberId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
req.checkParams('memberId', res.t('userIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: '-chat'}); // Do not fetch chat
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let uuid = req.params.memberId;
|
||||
|
||||
if (group.leader !== user._id) throw new NotAuthorized(res.t('onlyLeaderCanRemoveMember'));
|
||||
if (user._id === uuid) throw new NotAuthorized(res.t('memberCannotRemoveYourself'));
|
||||
|
||||
let member = await User.findOne({_id: uuid}).exec();
|
||||
|
||||
// We're removing the user from a guild or a party? is the user invited only?
|
||||
let isInGroup;
|
||||
if (member.party._id === group._id) {
|
||||
isInGroup = 'party';
|
||||
} else if (member.guilds.indexOf(group._id) !== -1) {
|
||||
isInGroup = 'guild';
|
||||
}
|
||||
|
||||
let isInvited;
|
||||
if (member.invitations.party && member.invitations.party.id === group._id) {
|
||||
isInvited = 'party';
|
||||
} else if (_.findIndex(member.invitations.guilds, {id: group._id}) !== -1) {
|
||||
isInvited = 'guild';
|
||||
}
|
||||
|
||||
if (isInGroup) {
|
||||
group.memberCount -= 1;
|
||||
|
||||
if (group.quest && group.quest.leader === member._id) {
|
||||
group.quest.key = undefined;
|
||||
group.quest.leader = undefined;
|
||||
} else if (group.quest && group.quest.members) {
|
||||
// remove member from quest
|
||||
group.quest.members[member._id] = undefined;
|
||||
group.markModified('quest.members');
|
||||
}
|
||||
|
||||
if (isInGroup === 'guild') {
|
||||
removeFromArray(member.guilds, group._id);
|
||||
}
|
||||
if (isInGroup === 'party') member.party._id = undefined; // TODO remove quest information too? Use group.leave()?
|
||||
|
||||
if (member.newMessages[group._id]) {
|
||||
member.newMessages[group._id] = undefined;
|
||||
member.markModified('newMessages');
|
||||
}
|
||||
|
||||
if (group.quest && group.quest.active && group.quest.leader === member._id) {
|
||||
member.items.quests[group.quest.key] += 1;
|
||||
}
|
||||
} else if (isInvited) {
|
||||
if (isInvited === 'guild') {
|
||||
removeFromArray(member.invitations.guilds, { id: group._id });
|
||||
}
|
||||
if (isInvited === 'party') {
|
||||
user.invitations.party = {};
|
||||
user.markModified('invitations.party');
|
||||
}
|
||||
} else {
|
||||
throw new NotFound(res.t('groupMemberNotFound'));
|
||||
}
|
||||
|
||||
let message = req.query.message;
|
||||
if (message) _sendMessageToRemoved(group, member, message);
|
||||
|
||||
await Bluebird.all([
|
||||
member.save(),
|
||||
group.save(),
|
||||
]);
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
async function _inviteByUUID (uuid, group, inviter, req, res) {
|
||||
let userToInvite = await User.findById(uuid).exec();
|
||||
|
||||
if (!userToInvite) {
|
||||
throw new NotFound(res.t('userWithIDNotFound', {userId: uuid}));
|
||||
}
|
||||
|
||||
if (group.type === 'guild') {
|
||||
if (_.contains(userToInvite.guilds, group._id)) {
|
||||
throw new NotAuthorized(res.t('userAlreadyInGroup'));
|
||||
}
|
||||
if (_.find(userToInvite.invitations.guilds, {id: group._id})) {
|
||||
throw new NotAuthorized(res.t('userAlreadyInvitedToGroup'));
|
||||
}
|
||||
userToInvite.invitations.guilds.push({id: group._id, name: group.name, inviter: inviter._id});
|
||||
} else if (group.type === 'party') {
|
||||
if (userToInvite.invitations.party.id) {
|
||||
throw new NotAuthorized(res.t('userAlreadyPendingInvitation'));
|
||||
}
|
||||
|
||||
if (userToInvite.party._id) {
|
||||
let userParty = await Group.getGroup({user: userToInvite, groupId: 'party', fields: 'memberCount'});
|
||||
|
||||
// Allow user to be invited to a new party when they're partying solo
|
||||
if (userParty.memberCount !== 1) throw new NotAuthorized(res.t('userAlreadyInAParty'));
|
||||
}
|
||||
|
||||
userToInvite.invitations.party = {id: group._id, name: group.name, inviter: inviter._id};
|
||||
}
|
||||
|
||||
let groupLabel = group.type === 'guild' ? 'Guild' : 'Party';
|
||||
let groupTemplate = group.type === 'guild' ? 'guild' : 'party';
|
||||
if (userToInvite.preferences.emailNotifications[`invited${groupLabel}`] !== false) {
|
||||
let emailVars = [
|
||||
{name: 'INVITER', content: inviter.profile.name},
|
||||
];
|
||||
|
||||
if (group.type === 'guild') {
|
||||
emailVars.push(
|
||||
{name: 'GUILD_NAME', content: group.name},
|
||||
{name: 'GUILD_URL', content: '/#/options/groups/guilds/public'}
|
||||
);
|
||||
} else {
|
||||
emailVars.push(
|
||||
{name: 'PARTY_NAME', content: group.name},
|
||||
{name: 'PARTY_URL', content: '/#/options/groups/party'}
|
||||
);
|
||||
}
|
||||
|
||||
sendTxnEmail(userToInvite, `invited-${groupTemplate}`, emailVars);
|
||||
}
|
||||
|
||||
sendPushNotification(
|
||||
userToInvite,
|
||||
common.i18n.t(group.type === 'guild' ? 'invitedGuild' : 'invitedParty'),
|
||||
group.name
|
||||
);
|
||||
|
||||
let userInvited = await userToInvite.save();
|
||||
if (group.type === 'guild') {
|
||||
return userInvited.invitations.guilds[userToInvite.invitations.guilds.length - 1];
|
||||
} else if (group.type === 'party') {
|
||||
return userInvited.invitations.party;
|
||||
}
|
||||
}
|
||||
|
||||
async function _inviteByEmail (invite, group, inviter, req, res) {
|
||||
let userReturnInfo;
|
||||
|
||||
if (!invite.email) throw new BadRequest(res.t('inviteMissingEmail'));
|
||||
|
||||
let userToContact = await User.findOne({$or: [
|
||||
{'auth.local.email': invite.email},
|
||||
{'auth.facebook.emails.value': invite.email},
|
||||
]})
|
||||
.select({_id: true, 'preferences.emailNotifications': true})
|
||||
.exec();
|
||||
|
||||
if (userToContact) {
|
||||
userReturnInfo = await _inviteByUUID(userToContact._id, group, inviter, req, res);
|
||||
} else {
|
||||
userReturnInfo = invite.email;
|
||||
const groupQueryString = JSON.stringify({
|
||||
id: group._id,
|
||||
inviter: inviter._id,
|
||||
sentAt: Date.now(), // so we can let it expire
|
||||
});
|
||||
let link = `/static/front?groupInvite=${encrypt(groupQueryString)}`;
|
||||
|
||||
let variables = [
|
||||
{name: 'LINK', content: link},
|
||||
{name: 'INVITER', content: req.body.inviter || inviter.profile.name},
|
||||
];
|
||||
|
||||
if (group.type === 'guild') {
|
||||
variables.push({name: 'GUILD_NAME', content: group.name});
|
||||
}
|
||||
|
||||
// Check for the email address not to be unsubscribed
|
||||
let userIsUnsubscribed = await EmailUnsubscription.findOne({email: invite.email}).exec();
|
||||
let groupLabel = group.type === 'guild' ? '-guild' : '';
|
||||
if (!userIsUnsubscribed) sendTxnEmail(invite, `invite-friend${groupLabel}`, variables);
|
||||
}
|
||||
|
||||
return userReturnInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/invite Invite users to a group using their UUIDs or email addresses
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName InviteToGroup
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted)
|
||||
*
|
||||
* @apiParam {array} emails Body parameter - An array of emails addresses to invite (optional)
|
||||
* @apiParam {array} uuids Body parameter - An array of uuids to invite (optional)
|
||||
* @apiParam {string} inviter Body parameter - The inviters' name (optional)
|
||||
*
|
||||
* @apiSuccess {array} data The invites
|
||||
*/
|
||||
api.inviteToGroup = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/invite',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: '-chat'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
|
||||
let uuids = req.body.uuids;
|
||||
let emails = req.body.emails;
|
||||
|
||||
let uuidsIsArray = Array.isArray(uuids);
|
||||
let emailsIsArray = Array.isArray(emails);
|
||||
|
||||
if (!uuids && !emails) {
|
||||
throw new BadRequest(res.t('canOnlyInviteEmailUuid'));
|
||||
}
|
||||
|
||||
let results = [];
|
||||
let totalInvites = 0;
|
||||
|
||||
if (uuids) {
|
||||
if (!uuidsIsArray) {
|
||||
throw new BadRequest(res.t('uuidsMustBeAnArray'));
|
||||
} else {
|
||||
totalInvites += uuids.length;
|
||||
}
|
||||
}
|
||||
|
||||
if (emails) {
|
||||
if (!emailsIsArray) {
|
||||
throw new BadRequest(res.t('emailsMustBeAnArray'));
|
||||
} else {
|
||||
totalInvites += emails.length;
|
||||
}
|
||||
}
|
||||
|
||||
if (totalInvites > INVITES_LIMIT) {
|
||||
throw new BadRequest(res.t('canOnlyInviteMaxInvites', {maxInvites: INVITES_LIMIT}));
|
||||
}
|
||||
|
||||
if (uuids) {
|
||||
let uuidInvites = uuids.map((uuid) => _inviteByUUID(uuid, group, user, req, res));
|
||||
let uuidResults = await Bluebird.all(uuidInvites);
|
||||
results.push(...uuidResults);
|
||||
}
|
||||
|
||||
if (emails) {
|
||||
let emailInvites = emails.map((invite) => _inviteByEmail(invite, group, user, req, res));
|
||||
let emailResults = await Bluebird.all(emailInvites);
|
||||
results.push(...emailResults);
|
||||
}
|
||||
|
||||
res.respond(200, results);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
183
website/server/controllers/api-v3/hall.js
Normal file
183
website/server/controllers/api-v3/hall.js
Normal file
@@ -0,0 +1,183 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import { ensureAdmin } from '../../middlewares/api-v3/ensureAccessRight';
|
||||
import { model as User } from '../../models/user';
|
||||
import {
|
||||
NotFound,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import _ from 'lodash';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/hall/patrons Get all patrons
|
||||
* @apiDescription Only the first 50 patrons are returned. More can be accessed passing ?page=n
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetPatrons
|
||||
* @apiGroup Hall
|
||||
*
|
||||
* @apiParam {Number} page Query Parameter - The result page. Default is 0
|
||||
*
|
||||
* @apiSuccess {Array} data An array of patrons
|
||||
*/
|
||||
api.getPatrons = {
|
||||
method: 'GET',
|
||||
url: '/hall/patrons',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkQuery('page', res.t('pageMustBeNumber')).optional().isNumeric();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let page = req.query.page ? Number(req.query.page) : 0;
|
||||
const perPage = 50;
|
||||
|
||||
let patrons = await User
|
||||
.find({
|
||||
'backer.tier': {$gt: 0},
|
||||
})
|
||||
.select('contributor backer profile.name')
|
||||
.sort('-backer.tier')
|
||||
.skip(page * perPage)
|
||||
.limit(perPage)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
res.respond(200, patrons);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/hall/heroes Get all Heroes
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetHeroes
|
||||
* @apiGroup Hall
|
||||
*
|
||||
* @apiSuccess {Array} data An array of heroes
|
||||
*/
|
||||
api.getHeroes = {
|
||||
method: 'GET',
|
||||
url: '/hall/heroes',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let heroes = await User
|
||||
.find({
|
||||
'contributor.level': {$gt: 0},
|
||||
})
|
||||
.select('contributor backer profile.name')
|
||||
.sort('-contributor.level')
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
res.respond(200, heroes);
|
||||
},
|
||||
};
|
||||
|
||||
// Note, while the following routes are called getHero / updateHero
|
||||
// they can be used by admins to get/update any user
|
||||
|
||||
const heroAdminFields = 'contributor balance profile.name purchased items auth';
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/hall/heroes/:heroId Get any user ("hero") given the UUID
|
||||
* @apiDescription Must be an admin to make this request.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetHero
|
||||
* @apiGroup Hall
|
||||
*
|
||||
* @apiSuccess {Object} data The user object
|
||||
*/
|
||||
api.getHero = {
|
||||
method: 'GET',
|
||||
url: '/hall/heroes/:heroId',
|
||||
middlewares: [authWithHeaders(), ensureAdmin],
|
||||
async handler (req, res) {
|
||||
let heroId = req.params.heroId;
|
||||
|
||||
req.checkParams('heroId', res.t('heroIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let hero = await User
|
||||
.findById(heroId)
|
||||
.select(heroAdminFields)
|
||||
.exec();
|
||||
|
||||
if (!hero) throw new NotFound(res.t('userWithIDNotFound', {userId: heroId}));
|
||||
let heroRes = hero.toJSON({minimize: true});
|
||||
// supply to the possible absence of hero.contributor
|
||||
// if we didn't pass minimize: true it would have returned all fields as empty
|
||||
if (!heroRes.contributor) heroRes.contributor = {};
|
||||
res.respond(200, heroRes);
|
||||
},
|
||||
};
|
||||
|
||||
// e.g., tier 5 gives 4 gems. Tier 8 = moderator. Tier 9 = staff
|
||||
const gemsPerTier = {1: 3, 2: 3, 3: 3, 4: 4, 5: 4, 6: 4, 7: 4, 8: 0, 9: 0};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/hall/heroes/:heroId Update any user ("hero")
|
||||
* @apiDescription Must be an admin to make this request.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateHero
|
||||
* @apiGroup Hall
|
||||
*
|
||||
* @apiSuccess {Object} data The updated user object
|
||||
*/
|
||||
api.updateHero = {
|
||||
method: 'PUT',
|
||||
url: '/hall/heroes/:heroId',
|
||||
middlewares: [authWithHeaders(), ensureAdmin],
|
||||
async handler (req, res) {
|
||||
let heroId = req.params.heroId;
|
||||
let updateData = req.body;
|
||||
|
||||
req.checkParams('heroId', res.t('heroIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let hero = await User.findById(heroId).exec();
|
||||
if (!hero) throw new NotFound(res.t('userWithIDNotFound', {userId: heroId}));
|
||||
|
||||
if (updateData.balance) hero.balance = updateData.balance;
|
||||
|
||||
// give them gems if they got an higher level
|
||||
let newTier = updateData.contributor && updateData.contributor.level; // tier = level in this context
|
||||
let oldTier = hero.contributor && hero.contributor.level || 0;
|
||||
if (newTier > oldTier) {
|
||||
hero.flags.contributor = true;
|
||||
let tierDiff = newTier - oldTier; // can be 2+ tier increases at once
|
||||
while (tierDiff) {
|
||||
hero.balance += gemsPerTier[newTier] / 4; // balance is in $
|
||||
tierDiff--;
|
||||
newTier--; // give them gems for the next tier down if they weren't aready that tier
|
||||
}
|
||||
}
|
||||
|
||||
if (updateData.contributor) _.assign(hero.contributor, updateData.contributor);
|
||||
if (updateData.purchased && updateData.purchased.ads) hero.purchased.ads = updateData.purchased.ads;
|
||||
|
||||
// give them the Dragon Hydra pet if they're above level 6
|
||||
if (hero.contributor.level >= 6) hero.items.pets['Dragon-Hydra'] = 5;
|
||||
if (updateData.itemPath && updateData.itemVal &&
|
||||
updateData.itemPath.indexOf('items.') === 0 &&
|
||||
User.schema.paths[updateData.itemPath]) {
|
||||
_.set(hero, updateData.itemPath, updateData.itemVal); // Sanitization at 5c30944 (deemed unnecessary)
|
||||
}
|
||||
|
||||
if (updateData.auth && _.isBoolean(updateData.auth.blocked)) hero.auth.blocked = updateData.auth.blocked;
|
||||
|
||||
let savedHero = await hero.save();
|
||||
let heroJSON = savedHero.toJSON();
|
||||
let responseHero = {_id: heroJSON._id}; // only respond with important fields
|
||||
heroAdminFields.split(' ').forEach(field => {
|
||||
_.set(responseHero, field, _.get(heroJSON, field));
|
||||
});
|
||||
|
||||
res.respond(200, responseHero);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
4
website/server/controllers/api-v3/iap.js
Normal file
4
website/server/controllers/api-v3/iap.js
Normal file
@@ -0,0 +1,4 @@
|
||||
// NOTE: this file is only used because the mobile apps expect IAP routes
|
||||
// to be found at /api/v3/iap instead of /iap.
|
||||
|
||||
module.exports = require('../top-level/payments/iap');
|
||||
364
website/server/controllers/api-v3/members.js
Normal file
364
website/server/controllers/api-v3/members.js
Normal file
@@ -0,0 +1,364 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import {
|
||||
model as User,
|
||||
publicFields as memberFields,
|
||||
nameFields,
|
||||
} from '../../models/user';
|
||||
import { model as Group } from '../../models/group';
|
||||
import { model as Challenge } from '../../models/challenge';
|
||||
import {
|
||||
NotFound,
|
||||
NotAuthorized,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import * as Tasks from '../../models/task';
|
||||
import {
|
||||
getUserInfo,
|
||||
sendTxn as sendTxnEmail,
|
||||
} from '../../libs/api-v3/email';
|
||||
import Bluebird from 'bluebird';
|
||||
import sendPushNotification from '../../libs/api-v3/pushNotifications';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/members/:memberId Get a member profile
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetMember
|
||||
* @apiGroup Member
|
||||
*
|
||||
* @apiParam {UUID} memberId The member's id
|
||||
*
|
||||
* @apiSuccess {object} data The member object
|
||||
*/
|
||||
api.getMember = {
|
||||
method: 'GET',
|
||||
url: '/members/:memberId',
|
||||
middlewares: [],
|
||||
async handler (req, res) {
|
||||
req.checkParams('memberId', res.t('memberIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let memberId = req.params.memberId;
|
||||
|
||||
let member = await User
|
||||
.findById(memberId)
|
||||
.select(memberFields)
|
||||
.exec();
|
||||
|
||||
if (!member) throw new NotFound(res.t('userWithIDNotFound', {userId: memberId}));
|
||||
|
||||
// manually call toJSON with minimize: true so empty paths aren't returned
|
||||
res.respond(200, member.toJSON({minimize: true}));
|
||||
},
|
||||
};
|
||||
|
||||
// Return a request handler for getMembersForGroup / getInvitesForGroup / getMembersForChallenge
|
||||
// type is `invites` or `members`
|
||||
function _getMembersForItem (type) {
|
||||
if (['group-members', 'group-invites', 'challenge-members'].indexOf(type) === -1) {
|
||||
throw new Error('Type must be one of "group-members", "group-invites", "challenge-members"');
|
||||
}
|
||||
|
||||
return async function handleGetMembersForItem (req, res) {
|
||||
if (type === 'challenge-members') {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
} else {
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
}
|
||||
req.checkQuery('lastId').optional().notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let groupId = req.params.groupId;
|
||||
let challengeId = req.params.challengeId;
|
||||
let lastId = req.query.lastId;
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
let group;
|
||||
|
||||
if (type === 'challenge-members') {
|
||||
challenge = await Challenge.findById(challengeId).select('_id type leader group').exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
// optionalMembership is set to true because even if you're not member of the group you may be able to access the challenge
|
||||
// for example if you've been booted from it, are the leader or a site admin
|
||||
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'));
|
||||
} else {
|
||||
group = await Group.getGroup({user, groupId, fields: '_id type'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
}
|
||||
|
||||
let query = {};
|
||||
let fields = nameFields;
|
||||
|
||||
if (type === 'challenge-members') {
|
||||
query.challenges = challenge._id;
|
||||
} else if (type === 'group-members') {
|
||||
if (group.type === 'guild') {
|
||||
query.guilds = group._id;
|
||||
} else {
|
||||
query['party._id'] = group._id; // group._id and not groupId because groupId could be === 'party'
|
||||
|
||||
if (req.query.includeAllPublicFields === 'true') {
|
||||
fields = memberFields;
|
||||
}
|
||||
}
|
||||
} else if (type === 'group-invites') {
|
||||
if (group.type === 'guild') { // eslint-disable-line no-lonely-if
|
||||
query['invitations.guilds.id'] = group._id;
|
||||
} else {
|
||||
query['invitations.party.id'] = group._id; // group._id and not groupId because groupId could be === 'party'
|
||||
}
|
||||
}
|
||||
|
||||
if (lastId) query._id = {$gt: lastId};
|
||||
|
||||
let members = await User
|
||||
.find(query)
|
||||
.sort({_id: 1})
|
||||
.limit(30)
|
||||
.select(fields)
|
||||
.exec();
|
||||
|
||||
// manually call toJSON with minimize: true so empty paths aren't returned
|
||||
res.respond(200, members.map(member => member.toJSON({minimize: true})));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/groups/:groupId/members Get members for a group
|
||||
* @apiDescription With a limit of 30 member per request. To get all members run requests against this routes (updating the lastId query parameter) until you get less than 30 results.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetMembersForGroup
|
||||
* @apiGroup Member
|
||||
*
|
||||
* @apiParam {UUID} groupId The group id
|
||||
* @apiParam {UUID} lastId Query parameter to specify the last member returned in a previous request to this route and get the next batch of results
|
||||
* @apiParam {boolean} includeAllPublicFields Query parameter available only when fetching a party. If === `true` then all public fields for members will be returned (liek when making a request for a single member)
|
||||
*
|
||||
* @apiSuccess {array} data An array of members, sorted by _id
|
||||
*/
|
||||
api.getMembersForGroup = {
|
||||
method: 'GET',
|
||||
url: '/groups/:groupId/members',
|
||||
middlewares: [authWithHeaders()],
|
||||
handler: _getMembersForItem('group-members'),
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/groups/:groupId/invites Get invites for a group
|
||||
* @apiDescription With a limit of 30 member per request. To get all invites run requests against this routes (updating the lastId query parameter) until you get less than 30 results.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetInvitesForGroup
|
||||
* @apiGroup Member
|
||||
*
|
||||
* @apiParam {UUID} groupId The group id
|
||||
* @apiParam {UUID} lastId Query parameter to specify the last invite returned in a previous request to this route and get the next batch of results
|
||||
*
|
||||
* @apiSuccess {array} data An array of invites, sorted by _id
|
||||
*/
|
||||
api.getInvitesForGroup = {
|
||||
method: 'GET',
|
||||
url: '/groups/:groupId/invites',
|
||||
middlewares: [authWithHeaders()],
|
||||
handler: _getMembersForItem('group-invites'),
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/challenges/:challengeId/members Get members for a challenge
|
||||
* @apiDescription With a limit of 30 member per request. To get all members run requests against this routes (updating the lastId query parameter) until you get less than 30 results.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetMembersForChallenge
|
||||
* @apiGroup Member
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge id
|
||||
* @apiParam {UUID} lastId Query parameter to specify the last member returned in a previous request to this route and get the next batch of results
|
||||
*
|
||||
* @apiSuccess {array} data An array of members, sorted by _id
|
||||
*/
|
||||
api.getMembersForChallenge = {
|
||||
method: 'GET',
|
||||
url: '/challenges/:challengeId/members',
|
||||
middlewares: [authWithHeaders()],
|
||||
handler: _getMembersForItem('challenge-members'),
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/challenges/:challengeId/members/:memberId Get a challenge member progress
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetChallenge
|
||||
* @apiGroup Challenge
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
* @apiParam {UUID} member The member _id
|
||||
*
|
||||
* @apiSuccess {object} data Return an object with member _id, profile.name and a tasks object with the challenge tasks for the member
|
||||
*/
|
||||
api.getChallengeMemberProgress = {
|
||||
method: 'GET',
|
||||
url: '/challenges/:challengeId/members/:memberId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('memberId', res.t('memberIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
let memberId = req.params.memberId;
|
||||
|
||||
let member = await User.findById(memberId).select(`${nameFields} challenges`).exec();
|
||||
if (!member) throw new NotFound(res.t('userWithIDNotFound', {userId: memberId}));
|
||||
|
||||
let challenge = await Challenge.findById(challengeId).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
|
||||
// optionalMembership is set to true because even if you're not member of the group you may be able to access the challenge
|
||||
// for example if you've been booted from it, are the leader or a site admin
|
||||
let 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'));
|
||||
if (!challenge.isMember(member)) throw new NotFound(res.t('challengeMemberNotFound'));
|
||||
|
||||
let chalTasks = await Tasks.Task.find({
|
||||
userId: memberId,
|
||||
'challenge.id': challengeId,
|
||||
})
|
||||
.select('-tags') // We don't want to return the tags publicly TODO same for other data?
|
||||
.exec();
|
||||
|
||||
// manually call toJSON with minimize: true so empty paths aren't returned
|
||||
let response = member.toJSON({minimize: true});
|
||||
delete response.challenges;
|
||||
response.tasks = chalTasks.map(chalTask => chalTask.toJSON({minimize: true}));
|
||||
res.respond(200, response);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {posts} /members/send-private-message Send a private message to a member
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName SendPrivateMessage
|
||||
* @apiGroup Members
|
||||
*
|
||||
* @apiParam {String} message Body parameter - The message
|
||||
* @apiParam {UUID} toUserId Body parameter - The user to contact
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.sendPrivateMessage = {
|
||||
method: 'POST',
|
||||
url: '/members/send-private-message',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkBody('message', res.t('messageRequired')).notEmpty();
|
||||
req.checkBody('toUserId', res.t('toUserIDRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let sender = res.locals.user;
|
||||
let message = req.body.message;
|
||||
|
||||
let receiver = await User.findById(req.body.toUserId).exec();
|
||||
if (!receiver) throw new NotFound(res.t('userNotFound'));
|
||||
|
||||
let userBlockedSender = receiver.inbox.blocks.indexOf(sender._id) !== -1;
|
||||
let userIsBlockBySender = sender.inbox.blocks.indexOf(receiver._id) !== -1;
|
||||
let userOptedOutOfMessaging = receiver.inbox.optOut;
|
||||
|
||||
if (userBlockedSender || userIsBlockBySender || userOptedOutOfMessaging) {
|
||||
throw new NotAuthorized(res.t('notAuthorizedToSendMessageToThisUser'));
|
||||
}
|
||||
|
||||
await sender.sendMessage(receiver, message);
|
||||
|
||||
if (receiver.preferences.emailNotifications.newPM !== false) {
|
||||
sendTxnEmail(receiver, 'new-pm', [
|
||||
{name: 'SENDER', content: getUserInfo(sender, ['name']).name},
|
||||
{name: 'PMS_INBOX_URL', content: '/#/options/groups/inbox'},
|
||||
]);
|
||||
}
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {posts} /members/transfer-gems Send a gem gift to a member
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName TransferGems
|
||||
* @apiGroup Members
|
||||
*
|
||||
* @apiParam {String} message Body parameter The message
|
||||
* @apiParam {UUID} toUserId Body parameter The toUser _id
|
||||
* @apiParam {Integer} gemAmount Body parameter The number of gems to send
|
||||
*
|
||||
* @apiSuccess {Object} data An empty Object
|
||||
*/
|
||||
api.transferGems = {
|
||||
method: 'POST',
|
||||
url: '/members/transfer-gems',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkBody('toUserId', res.t('toUserIDRequired')).notEmpty().isUUID();
|
||||
req.checkBody('gemAmount', res.t('gemAmountRequired')).notEmpty().isInt();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let sender = res.locals.user;
|
||||
|
||||
let receiver = await User.findById(req.body.toUserId).exec();
|
||||
if (!receiver) throw new NotFound(res.t('userNotFound'));
|
||||
|
||||
if (receiver._id === sender._id) {
|
||||
throw new NotAuthorized(res.t('cannotSendGemsToYourself'));
|
||||
}
|
||||
|
||||
let gemAmount = req.body.gemAmount;
|
||||
let amount = gemAmount / 4;
|
||||
|
||||
if (amount <= 0 || sender.balance < amount) {
|
||||
throw new NotAuthorized(res.t('badAmountOfGemsToSend'));
|
||||
}
|
||||
|
||||
receiver.balance += amount;
|
||||
sender.balance -= amount;
|
||||
let promises = [receiver.save(), sender.save()];
|
||||
await Bluebird.all(promises);
|
||||
|
||||
let message = res.t('privateMessageGiftIntro', {
|
||||
receiverName: receiver.profile.name,
|
||||
senderName: sender.profile.name,
|
||||
});
|
||||
message += res.t('privateMessageGiftGemsMessage', {gemAmount});
|
||||
|
||||
if (req.body.message) {
|
||||
message += req.body.message;
|
||||
}
|
||||
|
||||
await sender.sendMessage(receiver, message);
|
||||
|
||||
let byUsername = getUserInfo(sender, ['name']).name;
|
||||
|
||||
if (receiver.preferences.emailNotifications.giftedGems !== false) {
|
||||
sendTxnEmail(receiver, 'gifted-gems', [
|
||||
{name: 'GIFTER', content: byUsername},
|
||||
{name: 'X_GEMS_GIFTED', content: gemAmount},
|
||||
]);
|
||||
}
|
||||
|
||||
sendPushNotification(sender, res.t('giftedGems'), res.t('giftedGemsInfo', { amount: gemAmount, name: byUsername }));
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
module.exports = api;
|
||||
40
website/server/controllers/api-v3/modelsPaths.js
Normal file
40
website/server/controllers/api-v3/modelsPaths.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import mongoose from 'mongoose';
|
||||
|
||||
let api = {};
|
||||
|
||||
let tasksModels = ['habit', 'daily', 'todo', 'reward'];
|
||||
let allModels = ['user', 'tag', 'challenge', 'group'].concat(tasksModels);
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/models/:model/paths Get all paths for the specified model
|
||||
* @apiDescription Doesn't require authentication
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetUserModelPaths
|
||||
* @apiGroup Meta
|
||||
*
|
||||
* @apiParam {string="user","group","challenge","tag","habit","daily","todo","reward"} model The name of the model
|
||||
*
|
||||
* @apiSuccess {object} data A key-value object made of fieldPath: fieldType (like {'field.nested': Boolean})
|
||||
*/
|
||||
api.getModelPaths = {
|
||||
method: 'GET',
|
||||
url: '/models/:model/paths',
|
||||
async handler (req, res) {
|
||||
req.checkParams('model', res.t('modelNotFound')).notEmpty().isIn(allModels);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let model = req.params.model;
|
||||
// tasks models are lowercase, the others have the first letter uppercase (User, Group)
|
||||
if (tasksModels.indexOf(model) === -1) {
|
||||
model = model.charAt(0).toUpperCase() + model.slice(1);
|
||||
}
|
||||
|
||||
model = mongoose.model(model);
|
||||
|
||||
res.respond(200, model.getModelPaths());
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
451
website/server/controllers/api-v3/quests.js
Normal file
451
website/server/controllers/api-v3/quests.js
Normal file
@@ -0,0 +1,451 @@
|
||||
import _ from 'lodash';
|
||||
import Bluebird from 'bluebird';
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import analytics from '../../libs/api-v3/analyticsService';
|
||||
import {
|
||||
model as Group,
|
||||
} from '../../models/group';
|
||||
import { model as User } from '../../models/user';
|
||||
import {
|
||||
NotFound,
|
||||
NotAuthorized,
|
||||
BadRequest,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import {
|
||||
getUserInfo,
|
||||
sendTxn as sendTxnEmail,
|
||||
} from '../../libs/api-v3/email';
|
||||
import common from '../../../../common';
|
||||
import sendPushNotification from '../../libs/api-v3/pushNotifications';
|
||||
|
||||
const questScrolls = common.content.quests;
|
||||
|
||||
function canStartQuestAutomatically (group) {
|
||||
// If all members are either true (accepted) or false (rejected) return true
|
||||
// If any member is null/undefined (undecided) return false
|
||||
return _.every(group.quest.members, _.isBoolean);
|
||||
}
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/invite Invite users to a quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName InviteToQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
* @apiParam {string} questKey
|
||||
*
|
||||
* @apiSuccess {Object} data Quest object
|
||||
*/
|
||||
api.inviteToQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/invite/:questKey',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let questKey = req.params.questKey;
|
||||
let quest = questScrolls[questKey];
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: 'type quest'});
|
||||
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!quest) throw new NotFound(res.t('questNotFound', { key: questKey }));
|
||||
if (!user.items.quests[questKey]) throw new NotAuthorized(res.t('questNotOwned'));
|
||||
if (user.stats.lvl < quest.lvl) throw new NotAuthorized(res.t('questLevelTooHigh', { level: quest.lvl }));
|
||||
if (group.quest.key) throw new NotAuthorized(res.t('questAlreadyUnderway'));
|
||||
|
||||
let members = await User.find({
|
||||
'party._id': group._id,
|
||||
_id: {$ne: user._id},
|
||||
}).select('auth.facebook auth.local preferences.emailNotifications profile.name pushDevices')
|
||||
.exec();
|
||||
|
||||
group.markModified('quest');
|
||||
group.quest.key = questKey;
|
||||
group.quest.leader = user._id;
|
||||
group.quest.members = {};
|
||||
group.quest.members[user._id] = true;
|
||||
|
||||
user.party.quest.RSVPNeeded = false;
|
||||
user.party.quest.key = questKey;
|
||||
|
||||
await User.update({
|
||||
'party._id': group._id,
|
||||
_id: {$ne: user._id},
|
||||
}, {
|
||||
$set: {
|
||||
'party.quest.RSVPNeeded': true,
|
||||
'party.quest.key': questKey,
|
||||
},
|
||||
}, {multi: true}).exec();
|
||||
|
||||
_.each(members, (member) => {
|
||||
group.quest.members[member._id] = null;
|
||||
});
|
||||
|
||||
if (canStartQuestAutomatically(group)) {
|
||||
await group.startQuest(user);
|
||||
}
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
user.save(),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
|
||||
// send out invites
|
||||
let inviterVars = getUserInfo(user, ['name', 'email']);
|
||||
let membersToEmail = members.filter(member => {
|
||||
// send push notifications while filtering members before sending emails
|
||||
sendPushNotification(
|
||||
member,
|
||||
common.i18n.t('questInvitationTitle'),
|
||||
common.i18n.t('questInvitationInfo', { quest: quest.text() })
|
||||
);
|
||||
|
||||
return member.preferences.emailNotifications.invitedQuest !== false;
|
||||
});
|
||||
sendTxnEmail(membersToEmail, `invite-${quest.boss ? 'boss' : 'collection'}-quest`, [
|
||||
{name: 'QUEST_NAME', content: quest.text()},
|
||||
{name: 'INVITER', content: inviterVars.name},
|
||||
{name: 'PARTY_URL', content: '/#/options/groups/party'},
|
||||
]);
|
||||
|
||||
// track that the inviting user has accepted the quest
|
||||
analytics.track('quest', {
|
||||
category: 'behavior',
|
||||
owner: true,
|
||||
response: 'accept',
|
||||
gaLabel: 'accept',
|
||||
questName: questKey,
|
||||
uuid: user._id,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/accept Accept a pending quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AcceptQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.acceptQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/accept',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: 'type quest'});
|
||||
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.key) throw new NotFound(res.t('questInviteNotFound'));
|
||||
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyUnderway'));
|
||||
if (group.quest.members[user._id]) throw new BadRequest(res.t('questAlreadyAccepted'));
|
||||
|
||||
group.markModified('quest');
|
||||
group.quest.members[user._id] = true;
|
||||
user.party.quest.RSVPNeeded = false;
|
||||
|
||||
if (canStartQuestAutomatically(group)) {
|
||||
await group.startQuest(user);
|
||||
}
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
user.save(),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
|
||||
// track that a user has accepted the quest
|
||||
analytics.track('quest', {
|
||||
category: 'behavior',
|
||||
owner: false,
|
||||
response: 'accept',
|
||||
gaLabel: 'accept',
|
||||
questName: group.quest.key,
|
||||
uuid: user._id,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/reject Reject a quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName RejectQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.rejectQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/reject',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: 'type quest'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.key) throw new NotFound(res.t('questInvitationDoesNotExist'));
|
||||
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyUnderway'));
|
||||
if (group.quest.members[user._id]) throw new BadRequest(res.t('questAlreadyAccepted'));
|
||||
if (group.quest.members[user._id] === false) throw new BadRequest(res.t('questAlreadyRejected'));
|
||||
|
||||
group.quest.members[user._id] = false;
|
||||
group.markModified('quest.members');
|
||||
|
||||
user.party.quest = Group.cleanQuestProgress();
|
||||
user.markModified('party.quest');
|
||||
|
||||
if (canStartQuestAutomatically(group)) {
|
||||
await group.startQuest(user);
|
||||
}
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
user.save(),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
|
||||
analytics.track('quest', {
|
||||
category: 'behavior',
|
||||
owner: false,
|
||||
response: 'reject',
|
||||
gaLabel: 'reject',
|
||||
questName: group.quest.key,
|
||||
uuid: user._id,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/force-start Force-start a pending quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ForceQuestStart
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.forceStart = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/force-start',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId: req.params.groupId, fields: 'type quest leader'});
|
||||
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.key) throw new NotFound(res.t('questNotPending'));
|
||||
if (group.quest.active) throw new NotAuthorized(res.t('questAlreadyUnderway'));
|
||||
if (!(user._id === group.quest.leader || user._id === group.leader)) throw new NotAuthorized(res.t('questOrGroupLeaderOnlyStartQuest'));
|
||||
|
||||
group.markModified('quest');
|
||||
|
||||
await group.startQuest(user);
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
user.save(),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
|
||||
analytics.track('quest', {
|
||||
category: 'behavior',
|
||||
owner: user._id === group.quest.leader,
|
||||
response: 'force-start',
|
||||
gaLabel: 'force-start',
|
||||
questName: group.quest.key,
|
||||
uuid: user._id,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/cancel Cancels a quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CancelQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.cancelQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/cancel',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
// Cancel a quest BEFORE it has begun (i.e., in the invitation stage)
|
||||
// Quest scroll has not yet left quest owner's inventory so no need to return it.
|
||||
// Do not wipe quest progress for members because they'll want it to be applied to the next quest that's started.
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId, fields: 'type leader quest'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.key) throw new NotFound(res.t('questInvitationDoesNotExist'));
|
||||
if (user._id !== group.leader && group.quest.leader !== user._id) throw new NotAuthorized(res.t('onlyLeaderCancelQuest'));
|
||||
if (group.quest.active) throw new NotAuthorized(res.t('cantCancelActiveQuest'));
|
||||
|
||||
group.quest = Group.cleanGroupQuest();
|
||||
group.markModified('quest');
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
User.update(
|
||||
{'party._id': groupId},
|
||||
{$set: {'party.quest': Group.cleanQuestProgress()}},
|
||||
{multi: true}
|
||||
),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/abort Abort the current quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AbortQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.abortQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/abort',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
// Abort a quest AFTER it has begun (see questCancel for BEFORE)
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId, fields: 'type quest leader'});
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.active) throw new NotFound(res.t('noActiveQuestToAbort'));
|
||||
if (user._id !== group.leader && user._id !== group.quest.leader) throw new NotAuthorized(res.t('onlyLeaderAbortQuest'));
|
||||
|
||||
let memberUpdates = User.update({
|
||||
'party._id': groupId,
|
||||
}, {
|
||||
$set: {'party.quest': Group.cleanQuestProgress()},
|
||||
}, {multi: true}).exec();
|
||||
|
||||
let questLeaderUpdate = User.update({
|
||||
_id: group.quest.leader,
|
||||
}, {
|
||||
$inc: {
|
||||
[`items.quests.${group.quest.key}`]: 1, // give back the quest to the quest leader
|
||||
},
|
||||
}).exec();
|
||||
|
||||
group.quest = Group.cleanGroupQuest();
|
||||
group.markModified('quest');
|
||||
|
||||
let [groupSaved] = await Bluebird.all([group.save(), memberUpdates, questLeaderUpdate]);
|
||||
|
||||
res.respond(200, groupSaved.quest);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/groups/:groupId/quests/leave Leaves the active quest
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName LeaveQuest
|
||||
* @apiGroup Group
|
||||
*
|
||||
* @apiParam {string} groupId The group _id (or 'party')
|
||||
*
|
||||
* @apiSuccess {Object} data Quest Object
|
||||
*/
|
||||
api.leaveQuest = {
|
||||
method: 'POST',
|
||||
url: '/groups/:groupId/quests/leave',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let groupId = req.params.groupId;
|
||||
|
||||
req.checkParams('groupId', res.t('groupIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let group = await Group.getGroup({user, groupId, fields: 'type quest'});
|
||||
|
||||
if (!group) throw new NotFound(res.t('groupNotFound'));
|
||||
if (group.type !== 'party') throw new NotAuthorized(res.t('guildQuestsNotSupported'));
|
||||
if (!group.quest.active) throw new NotFound(res.t('noActiveQuestToLeave'));
|
||||
if (group.quest.leader === user._id) throw new NotAuthorized(res.t('questLeaderCannotLeaveQuest'));
|
||||
if (!group.quest.members[user._id]) throw new NotAuthorized(res.t('notPartOfQuest'));
|
||||
|
||||
group.quest.members[user._id] = false;
|
||||
group.markModified('quest.members');
|
||||
|
||||
user.party.quest = Group.cleanQuestProgress();
|
||||
user.markModified('party.quest');
|
||||
|
||||
let [savedGroup] = await Bluebird.all([
|
||||
group.save(),
|
||||
user.save(),
|
||||
]);
|
||||
|
||||
res.respond(200, savedGroup.quest);
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
21
website/server/controllers/api-v3/status.js
Normal file
21
website/server/controllers/api-v3/status.js
Normal file
@@ -0,0 +1,21 @@
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/status Get Habitica's API status
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetStatus
|
||||
* @apiGroup Status
|
||||
*
|
||||
* @apiSuccess {status} data.status 'up' if everything is ok
|
||||
*/
|
||||
api.getStatus = {
|
||||
method: 'GET',
|
||||
url: '/status',
|
||||
async handler (req, res) {
|
||||
res.respond(200, {
|
||||
status: 'up',
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
190
website/server/controllers/api-v3/tags.js
Normal file
190
website/server/controllers/api-v3/tags.js
Normal file
@@ -0,0 +1,190 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import { model as Tag } from '../../models/tag';
|
||||
import * as Tasks from '../../models/task';
|
||||
import {
|
||||
NotFound,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import _ from 'lodash';
|
||||
import { removeFromArray } from '../../libs/api-v3/collectionManipulators';
|
||||
|
||||
let api = {};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tags Create a new tag
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CreateTag
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiSuccess {Object} data The newly created tag
|
||||
*/
|
||||
api.createTag = {
|
||||
method: 'POST',
|
||||
url: '/tags',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
user.tags.push(Tag.sanitize(req.body));
|
||||
let savedUser = await user.save();
|
||||
|
||||
let l = savedUser.tags.length;
|
||||
let tag = savedUser.tags[l - 1];
|
||||
res.respond(201, tag);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/tag Get a user's tags
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetTags
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiSuccess {Array} data An array of tags
|
||||
*/
|
||||
api.getTags = {
|
||||
method: 'GET',
|
||||
url: '/tags',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
res.respond(200, user.tags);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/tags/:tagId Get a tag given its id
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetTag
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiParam {UUID} tagId The tag _id
|
||||
*
|
||||
* @apiSuccess {object} data The tag object
|
||||
*/
|
||||
api.getTag = {
|
||||
method: 'GET',
|
||||
url: '/tags/:tagId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let tag = _.find(user.tags, {id: req.params.tagId});
|
||||
if (!tag) throw new NotFound(res.t('tagNotFound'));
|
||||
res.respond(200, tag);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/tag/:tagId Update a tag
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateTag
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiParam {UUID} tagId The tag _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated tag
|
||||
*/
|
||||
api.updateTag = {
|
||||
method: 'PUT',
|
||||
url: '/tags/:tagId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let tagId = req.params.tagId;
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let tag = _.find(user.tags, {id: tagId});
|
||||
if (!tag) throw new NotFound(res.t('tagNotFound'));
|
||||
|
||||
_.merge(tag, Tag.sanitize(req.body));
|
||||
|
||||
let savedUser = await user.save();
|
||||
res.respond(200, _.find(savedUser.tags, {id: tagId}));
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/reorder-tags Reorder a tag
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ReorderTags
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiParam {tagId} UUID Id of the tag to move
|
||||
* @apiParam {to} number Position the tag is moving to
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.reorderTags = {
|
||||
method: 'POST',
|
||||
url: '/reorder-tags',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkBody('to', res.t('toRequired')).notEmpty();
|
||||
req.checkBody('tagId', res.t('tagIdRequired')).notEmpty();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let tagIndex = _.findIndex(user.tags, function findTag (tag) {
|
||||
return tag.id === req.body.tagId;
|
||||
});
|
||||
if (tagIndex === -1) throw new NotFound(res.t('tagNotFound'));
|
||||
user.tags.splice(req.body.to, 0, user.tags.splice(tagIndex, 1)[0]);
|
||||
|
||||
await user.save();
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/tag/:tagId Delete a user tag given its id
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName DeleteTag
|
||||
* @apiGroup Tag
|
||||
*
|
||||
* @apiParam {UUID} tagId The tag _id
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.deleteTag = {
|
||||
method: 'DELETE',
|
||||
url: '/tags/:tagId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let tag = removeFromArray(user.tags, { id: req.params.tagId });
|
||||
if (!tag) throw new NotFound(res.t('tagNotFound'));
|
||||
|
||||
// Remove from all the tasks TODO test
|
||||
await Tasks.Task.update({
|
||||
userId: user._id,
|
||||
}, {
|
||||
$pull: {
|
||||
tags: tag.id,
|
||||
},
|
||||
}, {multi: true}).exec();
|
||||
|
||||
await user.save();
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
971
website/server/controllers/api-v3/tasks.js
Normal file
971
website/server/controllers/api-v3/tasks.js
Normal file
@@ -0,0 +1,971 @@
|
||||
import { authWithHeaders } from '../../middlewares/api-v3/auth';
|
||||
import { sendTaskWebhook } from '../../libs/api-v3/webhook';
|
||||
import { removeFromArray } from '../../libs/api-v3/collectionManipulators';
|
||||
import * as Tasks from '../../models/task';
|
||||
import { model as Challenge } from '../../models/challenge';
|
||||
import { model as Group } from '../../models/group';
|
||||
import {
|
||||
NotFound,
|
||||
NotAuthorized,
|
||||
BadRequest,
|
||||
} from '../../libs/api-v3/errors';
|
||||
import common from '../../../../common';
|
||||
import Bluebird from 'bluebird';
|
||||
import _ from 'lodash';
|
||||
import logger from '../../libs/api-v3/logger';
|
||||
|
||||
let api = {};
|
||||
|
||||
// challenge must be passed only when a challenge task is being created
|
||||
async function _createTasks (req, res, user, challenge) {
|
||||
let toSave = Array.isArray(req.body) ? req.body : [req.body];
|
||||
|
||||
toSave = toSave.map(taskData => {
|
||||
// Validate that task.type is valid
|
||||
if (!taskData || Tasks.tasksTypes.indexOf(taskData.type) === -1) throw new BadRequest(res.t('invalidTaskType'));
|
||||
|
||||
let taskType = taskData.type;
|
||||
let newTask = new Tasks[taskType](Tasks.Task.sanitize(taskData));
|
||||
|
||||
if (challenge) {
|
||||
newTask.challenge.id = challenge.id;
|
||||
} else {
|
||||
newTask.userId = user._id;
|
||||
}
|
||||
|
||||
// Validate that the task is valid and throw if it isn't
|
||||
// otherwise since we're saving user/challenge and task in parallel it could save the user/challenge with a tasksOrder that doens't match reality
|
||||
let validationErrors = newTask.validateSync();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
// Otherwise update the user/challenge
|
||||
(challenge || user).tasksOrder[`${taskType}s`].unshift(newTask._id);
|
||||
|
||||
return newTask;
|
||||
}).map(task => task.save({ // If all tasks are valid (this is why it's not in the previous .map()), save everything, withough running validation again
|
||||
validateBeforeSave: false,
|
||||
}));
|
||||
|
||||
toSave.unshift((challenge || user).save());
|
||||
|
||||
let tasks = await Bluebird.all(toSave);
|
||||
tasks.splice(0, 1); // Remove user or challenge
|
||||
return tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/user Create a new task belonging to the user
|
||||
* @apiDescription Can be passed an object to create a single task or an array of objects to create multiple tasks.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CreateUserTasks
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiSuccess data An object if a single task was created, otherwise an array of tasks
|
||||
*/
|
||||
api.createUserTasks = {
|
||||
method: 'POST',
|
||||
url: '/tasks/user',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let tasks = await _createTasks(req, res, res.locals.user);
|
||||
res.respond(201, tasks.length === 1 ? tasks[0] : tasks);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/challenge/:challengeId Create a new task belonging to a challenge
|
||||
* @apiDescription Can be passed an object to create a single task or an array of objects to create multiple tasks.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName CreateChallengeTasks
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} challengeId The id of the challenge the new task(s) will belong to
|
||||
*
|
||||
* @apiSuccess data An object if a single task was created, otherwise an array of tasks
|
||||
*/
|
||||
api.createChallengeTasks = {
|
||||
method: 'POST',
|
||||
url: '/tasks/challenge/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let reqValidationErrors = req.validationErrors();
|
||||
if (reqValidationErrors) throw reqValidationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let challenge = await Challenge.findOne({_id: challengeId}).exec();
|
||||
|
||||
// If the challenge does not exist, or if it exists but user is not the leader -> throw error
|
||||
if (!challenge || user.challenges.indexOf(challengeId) === -1) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
|
||||
let tasks = await _createTasks(req, res, user, challenge);
|
||||
|
||||
res.respond(201, tasks.length === 1 ? tasks[0] : tasks);
|
||||
|
||||
// If adding tasks to a challenge -> sync users
|
||||
if (challenge) challenge.addTasks(tasks);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
// challenge must be passed only when a challenge task is being created
|
||||
async function _getTasks (req, res, user, challenge) {
|
||||
let query = challenge ? {'challenge.id': challenge.id, userId: {$exists: false}} : {userId: user._id};
|
||||
let type = req.query.type;
|
||||
|
||||
if (type) {
|
||||
if (type === 'todos') {
|
||||
query.completed = false; // Exclude completed todos
|
||||
query.type = 'todo';
|
||||
} else if (type === 'completedTodos') {
|
||||
query = Tasks.Task.find({
|
||||
userId: user._id,
|
||||
type: 'todo',
|
||||
completed: true,
|
||||
}).limit(30).sort({ // TODO add ability to pick more than 30 completed todos
|
||||
dateCompleted: -1,
|
||||
});
|
||||
} else {
|
||||
query.type = type.slice(0, -1); // removing the final "s"
|
||||
}
|
||||
} else {
|
||||
query.$or = [ // Exclude completed todos
|
||||
{type: 'todo', completed: false},
|
||||
{type: {$in: ['habit', 'daily', 'reward']}},
|
||||
];
|
||||
}
|
||||
|
||||
let tasks = await Tasks.Task.find(query).exec();
|
||||
|
||||
// Order tasks based on tasksOrder
|
||||
if (type && type !== 'completedTodos') {
|
||||
let order = (challenge || user).tasksOrder[type];
|
||||
let orderedTasks = new Array(tasks.length);
|
||||
let unorderedTasks = []; // what we want to add later
|
||||
|
||||
tasks.forEach((task, index) => {
|
||||
let taskId = task._id;
|
||||
let i = order[index] === taskId ? index : order.indexOf(taskId);
|
||||
if (i === -1) {
|
||||
unorderedTasks.push(task);
|
||||
} else {
|
||||
orderedTasks[i] = task;
|
||||
}
|
||||
});
|
||||
|
||||
// Remove empty values from the array and add any unordered task
|
||||
orderedTasks = _.compact(orderedTasks).concat(unorderedTasks);
|
||||
res.respond(200, orderedTasks);
|
||||
} else {
|
||||
res.respond(200, tasks);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/tasks/user Get a user's tasks
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetUserTasks
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {string="habits","dailys","todos","rewards","completedTodos"} type Optional query parameter to return just a type of tasks. By default all types will be returned except completed todos that must be requested separately.
|
||||
*
|
||||
* @apiSuccess {Array} data An array of tasks
|
||||
*/
|
||||
api.getUserTasks = {
|
||||
method: 'GET',
|
||||
url: '/tasks/user',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let types = Tasks.tasksTypes.map(type => `${type}s`);
|
||||
types.push('completedTodos');
|
||||
req.checkQuery('type', res.t('invalidTaskType')).optional().isIn(types);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
return await _getTasks(req, res, res.locals.user);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/tasks/challenge/:challengeId Get a challenge's tasks
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetChallengeTasks
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} challengeId The id of the challenge from which to retrieve the tasks
|
||||
* @apiParam {string="habits","dailys","todos","rewards"} type Optional query parameter to return just a type of tasks
|
||||
*
|
||||
* @apiSuccess {Array} data An array of tasks
|
||||
*/
|
||||
api.getChallengeTasks = {
|
||||
method: 'GET',
|
||||
url: '/tasks/challenge/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
let types = Tasks.tasksTypes.map(type => `${type}s`);
|
||||
req.checkQuery('type', res.t('invalidTaskType')).optional().isIn(types);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let challenge = await Challenge.findOne({_id: challengeId}).select('group leader tasksOrder').exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
let 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'));
|
||||
|
||||
return await _getTasks(req, res, res.locals.user, challenge);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {get} /api/v3/task/:taskId Get a task
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName GetTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
*
|
||||
* @apiSuccess {object} data The task object
|
||||
*/
|
||||
api.getTask = {
|
||||
method: 'GET',
|
||||
url: '/tasks/:taskId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
}).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
let challenge = await Challenge.find({_id: task.challenge.id}).select('leader').exec();
|
||||
if (!challenge || (user.challenges.indexOf(task.challenge.id) === -1 && challenge.leader !== user._id && !user.contributor.admin)) { // eslint-disable-line no-extra-parens
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
|
||||
res.respond(200, task);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/task/:taskId Update a task
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.updateTask = {
|
||||
method: 'PUT',
|
||||
url: '/tasks/:taskId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
}).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
challenge = await Challenge.findOne({_id: task.challenge.id}).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
|
||||
// we have to convert task to an object because otherwise things don't get merged correctly. Bad for performances?
|
||||
let [updatedTaskObj] = common.ops.updateTask(task.toObject(), req);
|
||||
|
||||
|
||||
// Sanitize differently user tasks linked to a challenge
|
||||
let sanitizedObj;
|
||||
|
||||
if (!challenge && task.userId && task.challenge && task.challenge.id) {
|
||||
sanitizedObj = Tasks.Task.sanitizeUserChallengeTask(updatedTaskObj);
|
||||
} else {
|
||||
sanitizedObj = Tasks.Task.sanitize(updatedTaskObj);
|
||||
}
|
||||
|
||||
_.assign(task, sanitizedObj);
|
||||
// console.log(task.modifiedPaths(), task.toObject().repeat === tep)
|
||||
// repeat is always among modifiedPaths because mongoose changes the other of the keys when using .toObject()
|
||||
// see https://github.com/Automattic/mongoose/issues/2749
|
||||
|
||||
let savedTask = await task.save();
|
||||
res.respond(200, savedTask);
|
||||
if (challenge) challenge.updateTask(savedTask);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
function _generateWebhookTaskData (task, direction, delta, stats, user) {
|
||||
let extendedStats = _.extend(stats, {
|
||||
toNextLevel: common.tnl(user.stats.lvl),
|
||||
maxHealth: common.maxHealth,
|
||||
maxMP: common.statsComputed(user).maxMP,
|
||||
});
|
||||
|
||||
let userData = {
|
||||
_id: user._id,
|
||||
_tmp: user._tmp,
|
||||
stats: extendedStats,
|
||||
};
|
||||
|
||||
let taskData = {
|
||||
details: task,
|
||||
direction,
|
||||
delta,
|
||||
};
|
||||
|
||||
return {
|
||||
task: taskData,
|
||||
user: userData,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/tasks/:taskId/score/:direction Score a task
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ScoreTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {string="up","down"} direction The direction for scoring the task
|
||||
*
|
||||
* @apiSuccess {object} data._tmp If an item was dropped it'll be returned in te _tmp object
|
||||
* @apiSuccess {number} data.delta
|
||||
* @apiSuccess {object} data The user stats
|
||||
*/
|
||||
api.scoreTask = {
|
||||
method: 'POST',
|
||||
url: '/tasks/:taskId/score/:direction',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('direction', res.t('directionUpDown')).notEmpty().isIn(['up', 'down']);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let direction = req.params.direction;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
|
||||
let wasCompleted = task.completed;
|
||||
|
||||
let [delta] = common.ops.scoreTask({task, user, direction}, req);
|
||||
// Drop system (don't run on the client, as it would only be discarded since ops are sent to the API, not the results)
|
||||
if (direction === 'up') user.fns.randomDrop({task, delta}, req);
|
||||
|
||||
// If a todo was completed or uncompleted move it in or out of the user.tasksOrder.todos list
|
||||
// TODO move to common code?
|
||||
if (task.type === 'todo') {
|
||||
if (!wasCompleted && task.completed) {
|
||||
removeFromArray(user.tasksOrder.todos, task._id);
|
||||
} else if (wasCompleted && !task.completed) {
|
||||
let hasTask = removeFromArray(user.tasksOrder.todos, task._id);
|
||||
if (!hasTask) {
|
||||
user.tasksOrder.todos.push(task._id);
|
||||
} // If for some reason it hadn't been removed previously don't do anything
|
||||
}
|
||||
}
|
||||
|
||||
let results = await Bluebird.all([
|
||||
user.save(),
|
||||
task.save(),
|
||||
]);
|
||||
|
||||
let savedUser = results[0];
|
||||
|
||||
let userStats = savedUser.stats.toJSON();
|
||||
let resJsonData = _.extend({delta, _tmp: user._tmp}, userStats);
|
||||
res.respond(200, resJsonData);
|
||||
|
||||
sendTaskWebhook(user.preferences.webhooks, _generateWebhookTaskData(task, direction, delta, userStats, user));
|
||||
|
||||
if (task.challenge.id && task.challenge.taskId && !task.challenge.broken && task.type !== 'reward') {
|
||||
// Wrapping everything in a try/catch block because if an error occurs using `await` it MUST NOT bubble up because the request has already been handled
|
||||
try {
|
||||
let chalTask = await Tasks.Task.findOne({
|
||||
_id: task.challenge.taskId,
|
||||
}).exec();
|
||||
|
||||
await chalTask.scoreChallengeTask(delta);
|
||||
} catch (e) {
|
||||
logger.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/:taskId/move/to/:position Move a task to a new position
|
||||
* @apiDescription Note: completed To-Dos are not sortable, do not appear in user.tasksOrder.todos, and are ordered by date of completion.
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName MoveTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {Number} position Query parameter - Where to move the task (-1 means push to bottom). First position is 0
|
||||
*
|
||||
* @apiSuccess {array} data The new tasks order (user.tasksOrder.{task.type}s)
|
||||
*/
|
||||
api.moveTask = {
|
||||
method: 'POST',
|
||||
url: '/tasks/:taskId/move/to/:position',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('position', res.t('positionRequired')).notEmpty().isNumeric();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let to = Number(req.params.position);
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
if (task.type === 'todo' && task.completed) throw new BadRequest(res.t('cantMoveCompletedTodo'));
|
||||
let order = user.tasksOrder[`${task.type}s`];
|
||||
let currentIndex = order.indexOf(task._id);
|
||||
|
||||
// If for some reason the task isn't ordered (should never happen), push it in the new position
|
||||
// if the task is moved to a non existing position
|
||||
// or if the task is moved to position -1 (push to bottom)
|
||||
// -> push task at end of list
|
||||
if (!order[to] && to !== -1) {
|
||||
order.push(task._id);
|
||||
} else {
|
||||
if (currentIndex !== -1) order.splice(currentIndex, 1);
|
||||
if (to === -1) {
|
||||
order.push(task._id);
|
||||
} else {
|
||||
order.splice(to, 0, task._id);
|
||||
}
|
||||
}
|
||||
|
||||
await user.save();
|
||||
res.respond(200, order);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/:taskId/checklist Add an item to the task's checklist
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AddChecklistItem
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.addChecklistItem = {
|
||||
method: 'POST',
|
||||
url: '/tasks/:taskId/checklist',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
}).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
challenge = await Challenge.findOne({_id: task.challenge.id}).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
|
||||
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
|
||||
|
||||
task.checklist.push(Tasks.Task.sanitizeChecklist(req.body));
|
||||
let savedTask = await task.save();
|
||||
|
||||
res.respond(200, savedTask);
|
||||
if (challenge) challenge.updateTask(savedTask);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/:taskId/checklist/:itemId/score Score a checklist item
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ScoreChecklistItem
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {UUID} itemId The checklist item _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.scoreCheckListItem = {
|
||||
method: 'POST',
|
||||
url: '/tasks/:taskId/checklist/:itemId/score',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
|
||||
|
||||
let item = _.find(task.checklist, {id: req.params.itemId});
|
||||
|
||||
if (!item) throw new NotFound(res.t('checklistItemNotFound'));
|
||||
item.completed = !item.completed;
|
||||
let savedTask = await task.save();
|
||||
|
||||
res.respond(200, savedTask);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {put} /api/v3/tasks/:taskId/checklist/:itemId Update a checklist item
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UpdateChecklistItem
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {UUID} itemId The checklist item _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.updateChecklistItem = {
|
||||
method: 'PUT',
|
||||
url: '/tasks/:taskId/checklist/:itemId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
}).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
challenge = await Challenge.findOne({_id: task.challenge.id}).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
|
||||
|
||||
let item = _.find(task.checklist, {id: req.params.itemId});
|
||||
if (!item) throw new NotFound(res.t('checklistItemNotFound'));
|
||||
|
||||
_.merge(item, Tasks.Task.sanitizeChecklist(req.body));
|
||||
let savedTask = await task.save();
|
||||
|
||||
res.respond(200, savedTask);
|
||||
if (challenge) challenge.updateTask(savedTask);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/tasks/:taskId/checklist/:itemId Remove a checklist item
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName RemoveChecklistItem
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {UUID} itemId The checklist item _id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.removeChecklistItem = {
|
||||
method: 'DELETE',
|
||||
url: '/tasks/:taskId/checklist/:itemId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('itemId', res.t('itemIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
}).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
challenge = await Challenge.findOne({_id: task.challenge.id}).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
}
|
||||
if (task.type !== 'daily' && task.type !== 'todo') throw new BadRequest(res.t('checklistOnlyDailyTodo'));
|
||||
|
||||
let hasItem = removeFromArray(task.checklist, { id: req.params.itemId });
|
||||
if (!hasItem) throw new NotFound(res.t('checklistItemNotFound'));
|
||||
|
||||
let savedTask = await task.save();
|
||||
res.respond(200, savedTask);
|
||||
if (challenge) challenge.updateTask(savedTask);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/:taskId/tags/:tagId Add a tag to a task
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName AddTagToTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {UUID} tagId The tag id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.addTagToTask = {
|
||||
method: 'POST',
|
||||
url: '/tasks/:taskId/tags/:tagId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
let userTags = user.tags.map(tag => tag.id);
|
||||
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID().isIn(userTags);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
let tagId = req.params.tagId;
|
||||
|
||||
let alreadyTagged = task.tags.indexOf(tagId) !== -1;
|
||||
if (alreadyTagged) throw new BadRequest(res.t('alreadyTagged'));
|
||||
|
||||
task.tags.push(tagId);
|
||||
|
||||
let savedTask = await task.save();
|
||||
res.respond(200, savedTask);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/tasks/:taskId/tags/:tagId Remove a tag from atask
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName RemoveTagFromTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {UUID} tagId The tag id
|
||||
*
|
||||
* @apiSuccess {object} data The updated task
|
||||
*/
|
||||
api.removeTagFromTask = {
|
||||
method: 'DELETE',
|
||||
url: '/tasks/:taskId/tags/:tagId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkParams('tagId', res.t('tagIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: req.params.taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
|
||||
let hasTag = removeFromArray(task.tags, req.params.tagId);
|
||||
if (!hasTag) throw new NotFound(res.t('tagNotFound'));
|
||||
|
||||
let savedTask = await task.save();
|
||||
res.respond(200, savedTask);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/unlink-all/:challengeId Unlink all tasks from a challenge
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UnlinkAllTasks
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} challengeId The challenge _id
|
||||
* @apiParam {string} keep Query parameter - keep-all or remove-all
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.unlinkAllTasks = {
|
||||
method: 'POST',
|
||||
url: '/tasks/unlink-all/:challengeId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('challengeId', res.t('challengeIdRequired')).notEmpty().isUUID();
|
||||
req.checkQuery('keep', res.t('keepOrRemoveAll')).notEmpty().isIn(['keep-all', 'remove-all']);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let keep = req.query.keep;
|
||||
let challengeId = req.params.challengeId;
|
||||
|
||||
let tasks = await Tasks.Task.find({
|
||||
'challenge.id': challengeId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
let validTasks = tasks.every(task => {
|
||||
return task.challenge.broken;
|
||||
});
|
||||
|
||||
if (!validTasks) throw new BadRequest(res.t('cantOnlyUnlinkChalTask'));
|
||||
|
||||
if (keep === 'keep-all') {
|
||||
await Bluebird.all(tasks.map(task => {
|
||||
task.challenge = {};
|
||||
return task.save();
|
||||
}));
|
||||
} else { // remove
|
||||
let toSave = [];
|
||||
|
||||
tasks.forEach(task => {
|
||||
if (task.type !== 'todo' || !task.completed) { // eslint-disable-line no-lonely-if
|
||||
removeFromArray(user.tasksOrder[`${task.type}s`], task._id);
|
||||
}
|
||||
|
||||
toSave.push(task.remove());
|
||||
});
|
||||
|
||||
toSave.push(user.save());
|
||||
|
||||
await Bluebird.all(toSave);
|
||||
}
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/unlink-one/:taskId Unlink a challenge task
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName UnlinkOneTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
* @apiParam {string} keep Query parameter - keep or remove
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.unlinkOneTask = {
|
||||
method: 'POST',
|
||||
url: '/tasks/unlink-one/:taskId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
req.checkQuery('keep', res.t('keepOrRemove')).notEmpty().isIn(['keep', 'remove']);
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let user = res.locals.user;
|
||||
let keep = req.query.keep;
|
||||
let taskId = req.params.taskId;
|
||||
|
||||
let task = await Tasks.Task.findOne({
|
||||
_id: taskId,
|
||||
userId: user._id,
|
||||
}).exec();
|
||||
|
||||
if (!task) throw new NotFound(res.t('taskNotFound'));
|
||||
if (!task.challenge.id) throw new BadRequest(res.t('cantOnlyUnlinkChalTask'));
|
||||
if (!task.challenge.broken) throw new BadRequest(res.t('cantOnlyUnlinkChalTask'));
|
||||
|
||||
if (keep === 'keep') {
|
||||
task.challenge = {};
|
||||
await task.save();
|
||||
} else { // remove
|
||||
if (task.type !== 'todo' || !task.completed) { // eslint-disable-line no-lonely-if
|
||||
removeFromArray(user.tasksOrder[`${task.type}s`], taskId);
|
||||
await Bluebird.all([user.save(), task.remove()]);
|
||||
} else {
|
||||
await task.remove();
|
||||
}
|
||||
}
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {post} /api/v3/tasks/clearCompletedTodos Delete user's completed todos
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName ClearCompletedTodos
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.clearCompletedTodos = {
|
||||
method: 'POST',
|
||||
url: '/tasks/clearCompletedTodos',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
|
||||
// Clear completed todos
|
||||
// Do not delete challenges completed todos unless the task is broken
|
||||
await Tasks.Task.remove({
|
||||
userId: user._id,
|
||||
type: 'todo',
|
||||
completed: true,
|
||||
$or: [
|
||||
{'challenge.id': {$exists: false}},
|
||||
{'challenge.broken': {$exists: true}},
|
||||
],
|
||||
}).exec();
|
||||
|
||||
res.respond(200, {});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @api {delete} /api/v3/tasks/:taskId Delete a task given its id
|
||||
* @apiVersion 3.0.0
|
||||
* @apiName DeleteTask
|
||||
* @apiGroup Task
|
||||
*
|
||||
* @apiParam {UUID} taskId The task _id
|
||||
*
|
||||
* @apiSuccess {object} data An empty object
|
||||
*/
|
||||
api.deleteTask = {
|
||||
method: 'DELETE',
|
||||
url: '/tasks/:taskId',
|
||||
middlewares: [authWithHeaders()],
|
||||
async handler (req, res) {
|
||||
let user = res.locals.user;
|
||||
let challenge;
|
||||
|
||||
req.checkParams('taskId', res.t('taskIdRequired')).notEmpty().isUUID();
|
||||
|
||||
let validationErrors = req.validationErrors();
|
||||
if (validationErrors) throw validationErrors;
|
||||
|
||||
let taskId = req.params.taskId;
|
||||
let task = await Tasks.Task.findById(taskId).exec();
|
||||
|
||||
if (!task) {
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (!task.userId) { // If the task belongs to a challenge make sure the user has rights
|
||||
challenge = await Challenge.findOne({_id: task.challenge.id}).exec();
|
||||
if (!challenge) throw new NotFound(res.t('challengeNotFound'));
|
||||
if (challenge.leader !== user._id) throw new NotAuthorized(res.t('onlyChalLeaderEditTasks'));
|
||||
} else if (task.userId !== user._id) { // If the task is owned by a user make it's the current one
|
||||
throw new NotFound(res.t('taskNotFound'));
|
||||
} else if (task.userId && task.challenge.id && !task.challenge.broken) {
|
||||
throw new NotAuthorized(res.t('cantDeleteChallengeTasks'));
|
||||
}
|
||||
|
||||
if (task.type !== 'todo' || !task.completed) {
|
||||
removeFromArray((challenge || user).tasksOrder[`${task.type}s`], taskId);
|
||||
await Bluebird.all([(challenge || user).save(), task.remove()]);
|
||||
} else {
|
||||
await task.remove();
|
||||
}
|
||||
|
||||
res.respond(200, {});
|
||||
if (challenge) challenge.removeTask(task);
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = api;
|
||||
1358
website/server/controllers/api-v3/user.js
Normal file
1358
website/server/controllers/api-v3/user.js
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user