users.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. // Sandstorm context is detected using the METEOR_SETTINGS environment variable
  2. // in the package definition.
  3. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  4. Meteor.settings.public.sandstorm;
  5. Users = Meteor.users;
  6. Users.attachSchema(new SimpleSchema({
  7. username: {
  8. type: String,
  9. optional: true,
  10. autoValue() { // eslint-disable-line consistent-return
  11. if (this.isInsert && !this.isSet) {
  12. const name = this.field('profile.fullname');
  13. if (name.isSet) {
  14. return name.value.toLowerCase().replace(/\s/g, '');
  15. }
  16. }
  17. },
  18. },
  19. emails: {
  20. type: [Object],
  21. optional: true,
  22. },
  23. 'emails.$.address': {
  24. type: String,
  25. regEx: SimpleSchema.RegEx.Email,
  26. },
  27. 'emails.$.verified': {
  28. type: Boolean,
  29. },
  30. createdAt: {
  31. type: Date,
  32. autoValue() { // eslint-disable-line consistent-return
  33. if (this.isInsert) {
  34. return new Date();
  35. } else {
  36. this.unset();
  37. }
  38. },
  39. },
  40. profile: {
  41. type: Object,
  42. optional: true,
  43. autoValue() { // eslint-disable-line consistent-return
  44. if (this.isInsert && !this.isSet) {
  45. return {
  46. boardView: 'board-view-lists',
  47. };
  48. }
  49. },
  50. },
  51. 'profile.avatarUrl': {
  52. type: String,
  53. optional: true,
  54. },
  55. 'profile.emailBuffer': {
  56. type: [String],
  57. optional: true,
  58. },
  59. 'profile.fullname': {
  60. type: String,
  61. optional: true,
  62. },
  63. 'profile.hiddenSystemMessages': {
  64. type: Boolean,
  65. optional: true,
  66. },
  67. 'profile.initials': {
  68. type: String,
  69. optional: true,
  70. },
  71. 'profile.invitedBoards': {
  72. type: [String],
  73. optional: true,
  74. },
  75. 'profile.language': {
  76. type: String,
  77. optional: true,
  78. },
  79. 'profile.notifications': {
  80. type: [String],
  81. optional: true,
  82. },
  83. 'profile.showCardsCountAt': {
  84. type: Number,
  85. optional: true,
  86. },
  87. 'profile.starredBoards': {
  88. type: [String],
  89. optional: true,
  90. },
  91. 'profile.tags': {
  92. type: [String],
  93. optional: true,
  94. },
  95. 'profile.icode': {
  96. type: String,
  97. optional: true,
  98. },
  99. 'profile.boardView': {
  100. type: String,
  101. optional: true,
  102. allowedValues: [
  103. 'board-view-lists',
  104. 'board-view-swimlanes',
  105. 'board-view-cal',
  106. ],
  107. },
  108. services: {
  109. type: Object,
  110. optional: true,
  111. blackbox: true,
  112. },
  113. heartbeat: {
  114. type: Date,
  115. optional: true,
  116. },
  117. isAdmin: {
  118. type: Boolean,
  119. optional: true,
  120. },
  121. createdThroughApi: {
  122. type: Boolean,
  123. optional: true,
  124. },
  125. loginDisabled: {
  126. type: Boolean,
  127. optional: true,
  128. },
  129. // TODO : write a migration and check if using a ldap parameter is better than a connection_type parameter
  130. ldap: {
  131. type: Boolean,
  132. optional: true,
  133. },
  134. }));
  135. Users.allow({
  136. update(userId) {
  137. const user = Users.findOne(userId);
  138. return user && Meteor.user().isAdmin;
  139. },
  140. });
  141. // Search a user in the complete server database by its name or username. This
  142. // is used for instance to add a new user to a board.
  143. const searchInFields = ['username', 'profile.fullname'];
  144. Users.initEasySearch(searchInFields, {
  145. use: 'mongo-db',
  146. returnFields: [...searchInFields, 'profile.avatarUrl'],
  147. });
  148. if (Meteor.isClient) {
  149. Users.helpers({
  150. isBoardMember() {
  151. const board = Boards.findOne(Session.get('currentBoard'));
  152. return board && board.hasMember(this._id);
  153. },
  154. isNotNoComments() {
  155. const board = Boards.findOne(Session.get('currentBoard'));
  156. return board && board.hasMember(this._id) && !board.hasNoComments(this._id);
  157. },
  158. isNoComments() {
  159. const board = Boards.findOne(Session.get('currentBoard'));
  160. return board && board.hasNoComments(this._id);
  161. },
  162. isNotCommentOnly() {
  163. const board = Boards.findOne(Session.get('currentBoard'));
  164. return board && board.hasMember(this._id) && !board.hasCommentOnly(this._id);
  165. },
  166. isCommentOnly() {
  167. const board = Boards.findOne(Session.get('currentBoard'));
  168. return board && board.hasCommentOnly(this._id);
  169. },
  170. isBoardAdmin() {
  171. const board = Boards.findOne(Session.get('currentBoard'));
  172. return board && board.hasAdmin(this._id);
  173. },
  174. });
  175. }
  176. Users.helpers({
  177. boards() {
  178. return Boards.find({ 'members.userId': this._id });
  179. },
  180. starredBoards() {
  181. const {starredBoards = []} = this.profile;
  182. return Boards.find({archived: false, _id: {$in: starredBoards}});
  183. },
  184. hasStarred(boardId) {
  185. const {starredBoards = []} = this.profile;
  186. return _.contains(starredBoards, boardId);
  187. },
  188. invitedBoards() {
  189. const {invitedBoards = []} = this.profile;
  190. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  191. },
  192. isInvitedTo(boardId) {
  193. const {invitedBoards = []} = this.profile;
  194. return _.contains(invitedBoards, boardId);
  195. },
  196. hasTag(tag) {
  197. const {tags = []} = this.profile;
  198. return _.contains(tags, tag);
  199. },
  200. hasNotification(activityId) {
  201. const {notifications = []} = this.profile;
  202. return _.contains(notifications, activityId);
  203. },
  204. hasHiddenSystemMessages() {
  205. const profile = this.profile || {};
  206. return profile.hiddenSystemMessages || false;
  207. },
  208. getEmailBuffer() {
  209. const {emailBuffer = []} = this.profile;
  210. return emailBuffer;
  211. },
  212. getInitials() {
  213. const profile = this.profile || {};
  214. if (profile.initials)
  215. return profile.initials;
  216. else if (profile.fullname) {
  217. return profile.fullname.split(/\s+/).reduce((memo, word) => {
  218. return memo + word[0];
  219. }, '').toUpperCase();
  220. } else {
  221. return this.username[0].toUpperCase();
  222. }
  223. },
  224. getLimitToShowCardsCount() {
  225. const profile = this.profile || {};
  226. return profile.showCardsCountAt;
  227. },
  228. getName() {
  229. const profile = this.profile || {};
  230. return profile.fullname || this.username;
  231. },
  232. getLanguage() {
  233. const profile = this.profile || {};
  234. return profile.language || 'en';
  235. },
  236. });
  237. Users.mutations({
  238. toggleBoardStar(boardId) {
  239. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  240. return {
  241. [queryKind]: {
  242. 'profile.starredBoards': boardId,
  243. },
  244. };
  245. },
  246. addInvite(boardId) {
  247. return {
  248. $addToSet: {
  249. 'profile.invitedBoards': boardId,
  250. },
  251. };
  252. },
  253. removeInvite(boardId) {
  254. return {
  255. $pull: {
  256. 'profile.invitedBoards': boardId,
  257. },
  258. };
  259. },
  260. addTag(tag) {
  261. return {
  262. $addToSet: {
  263. 'profile.tags': tag,
  264. },
  265. };
  266. },
  267. removeTag(tag) {
  268. return {
  269. $pull: {
  270. 'profile.tags': tag,
  271. },
  272. };
  273. },
  274. toggleTag(tag) {
  275. if (this.hasTag(tag))
  276. this.removeTag(tag);
  277. else
  278. this.addTag(tag);
  279. },
  280. toggleSystem(value = false) {
  281. return {
  282. $set: {
  283. 'profile.hiddenSystemMessages': !value,
  284. },
  285. };
  286. },
  287. addNotification(activityId) {
  288. return {
  289. $addToSet: {
  290. 'profile.notifications': activityId,
  291. },
  292. };
  293. },
  294. removeNotification(activityId) {
  295. return {
  296. $pull: {
  297. 'profile.notifications': activityId,
  298. },
  299. };
  300. },
  301. addEmailBuffer(text) {
  302. return {
  303. $addToSet: {
  304. 'profile.emailBuffer': text,
  305. },
  306. };
  307. },
  308. clearEmailBuffer() {
  309. return {
  310. $set: {
  311. 'profile.emailBuffer': [],
  312. },
  313. };
  314. },
  315. setAvatarUrl(avatarUrl) {
  316. return {$set: {'profile.avatarUrl': avatarUrl}};
  317. },
  318. setShowCardsCountAt(limit) {
  319. return {$set: {'profile.showCardsCountAt': limit}};
  320. },
  321. setBoardView(view) {
  322. return {
  323. $set : {
  324. 'profile.boardView': view,
  325. },
  326. };
  327. },
  328. });
  329. Meteor.methods({
  330. setUsername(username, userId) {
  331. check(username, String);
  332. const nUsersWithUsername = Users.find({username}).count();
  333. if (nUsersWithUsername > 0) {
  334. throw new Meteor.Error('username-already-taken');
  335. } else {
  336. Users.update(userId, {$set: {username}});
  337. }
  338. },
  339. toggleSystemMessages() {
  340. const user = Meteor.user();
  341. user.toggleSystem(user.hasHiddenSystemMessages());
  342. },
  343. changeLimitToShowCardsCount(limit) {
  344. check(limit, Number);
  345. Meteor.user().setShowCardsCountAt(limit);
  346. },
  347. setEmail(email, userId) {
  348. check(email, String);
  349. const existingUser = Users.findOne({'emails.address': email}, {fields: {_id: 1}});
  350. if (existingUser) {
  351. throw new Meteor.Error('email-already-taken');
  352. } else {
  353. Users.update(userId, {
  354. $set: {
  355. emails: [{
  356. address: email,
  357. verified: false,
  358. }],
  359. },
  360. });
  361. }
  362. },
  363. setUsernameAndEmail(username, email, userId) {
  364. check(username, String);
  365. check(email, String);
  366. check(userId, String);
  367. Meteor.call('setUsername', username, userId);
  368. Meteor.call('setEmail', email, userId);
  369. },
  370. setPassword(newPassword, userId) {
  371. check(userId, String);
  372. check(newPassword, String);
  373. if(Meteor.user().isAdmin){
  374. Accounts.setPassword(userId, newPassword);
  375. }
  376. },
  377. });
  378. if (Meteor.isServer) {
  379. Meteor.methods({
  380. // we accept userId, username, email
  381. inviteUserToBoard(username, boardId) {
  382. check(username, String);
  383. check(boardId, String);
  384. const inviter = Meteor.user();
  385. const board = Boards.findOne(boardId);
  386. const allowInvite = inviter &&
  387. board &&
  388. board.members &&
  389. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  390. _.where(board.members, {userId: inviter._id})[0].isActive &&
  391. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  392. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  393. this.unblock();
  394. const posAt = username.indexOf('@');
  395. let user = null;
  396. if (posAt >= 0) {
  397. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  398. } else {
  399. user = Users.findOne(username) || Users.findOne({username});
  400. }
  401. if (user) {
  402. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  403. } else {
  404. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  405. if (Settings.findOne().disableRegistration) throw new Meteor.Error('error-user-notCreated');
  406. // Set in lowercase email before creating account
  407. const email = username.toLowerCase();
  408. username = email.substring(0, posAt);
  409. const newUserId = Accounts.createUser({username, email});
  410. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  411. // assume new user speak same language with inviter
  412. if (inviter.profile && inviter.profile.language) {
  413. Users.update(newUserId, {
  414. $set: {
  415. 'profile.language': inviter.profile.language,
  416. },
  417. });
  418. }
  419. Accounts.sendEnrollmentEmail(newUserId);
  420. user = Users.findOne(newUserId);
  421. }
  422. board.addMember(user._id);
  423. user.addInvite(boardId);
  424. try {
  425. const params = {
  426. user: user.username,
  427. inviter: inviter.username,
  428. board: board.title,
  429. url: board.absoluteUrl(),
  430. };
  431. const lang = user.getLanguage();
  432. Email.send({
  433. to: user.emails[0].address.toLowerCase(),
  434. from: Accounts.emailTemplates.from,
  435. subject: TAPi18n.__('email-invite-subject', params, lang),
  436. text: TAPi18n.__('email-invite-text', params, lang),
  437. });
  438. } catch (e) {
  439. throw new Meteor.Error('email-fail', e.message);
  440. }
  441. return {username: user.username, email: user.emails[0].address};
  442. },
  443. });
  444. Accounts.onCreateUser((options, user) => {
  445. const userCount = Users.find().count();
  446. if (!isSandstorm && userCount === 0) {
  447. user.isAdmin = true;
  448. return user;
  449. }
  450. if (user.services.oidc) {
  451. const email = user.services.oidc.email.toLowerCase();
  452. user.username = user.services.oidc.username;
  453. user.emails = [{ address: email, verified: true }];
  454. const initials = user.services.oidc.fullname.match(/\b[a-zA-Z]/g).join('').toUpperCase();
  455. user.profile = { initials, fullname: user.services.oidc.fullname };
  456. // see if any existing user has this email address or username, otherwise create new
  457. const existingUser = Meteor.users.findOne({$or: [{'emails.address': email}, {'username':user.username}]});
  458. if (!existingUser)
  459. return user;
  460. // copy across new service info
  461. const service = _.keys(user.services)[0];
  462. existingUser.services[service] = user.services[service];
  463. existingUser.emails = user.emails;
  464. existingUser.username = user.username;
  465. existingUser.profile = user.profile;
  466. Meteor.users.remove({_id: existingUser._id}); // remove existing record
  467. return existingUser;
  468. }
  469. if (options.from === 'admin') {
  470. user.createdThroughApi = true;
  471. return user;
  472. }
  473. const disableRegistration = Settings.findOne().disableRegistration;
  474. // If ldap, bypass the inviation code if the self registration isn't allowed.
  475. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  476. if (options.ldap || !disableRegistration) {
  477. user.ldap = true;
  478. return user;
  479. }
  480. if (!options || !options.profile) {
  481. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  482. }
  483. const invitationCode = InvitationCodes.findOne({
  484. code: options.profile.invitationcode,
  485. email: options.email,
  486. valid: true,
  487. });
  488. if (!invitationCode) {
  489. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  490. } else {
  491. user.profile = {icode: options.profile.invitationcode};
  492. user.profile.boardView = 'board-view-lists';
  493. // Deletes the invitation code after the user was created successfully.
  494. setTimeout(Meteor.bindEnvironment(() => {
  495. InvitationCodes.remove({'_id': invitationCode._id});
  496. }), 200);
  497. return user;
  498. }
  499. });
  500. }
  501. if (Meteor.isServer) {
  502. // Let mongoDB ensure username unicity
  503. Meteor.startup(() => {
  504. Users._collection._ensureIndex({
  505. username: 1,
  506. }, {unique: true});
  507. });
  508. // Each board document contains the de-normalized number of users that have
  509. // starred it. If the user star or unstar a board, we need to update this
  510. // counter.
  511. // We need to run this code on the server only, otherwise the incrementation
  512. // will be done twice.
  513. Users.after.update(function (userId, user, fieldNames) {
  514. // The `starredBoards` list is hosted on the `profile` field. If this
  515. // field hasn't been modificated we don't need to run this hook.
  516. if (!_.contains(fieldNames, 'profile'))
  517. return;
  518. // To calculate a diff of board starred ids, we get both the previous
  519. // and the newly board ids list
  520. function getStarredBoardsIds(doc) {
  521. return doc.profile && doc.profile.starredBoards;
  522. }
  523. const oldIds = getStarredBoardsIds(this.previous);
  524. const newIds = getStarredBoardsIds(user);
  525. // The _.difference(a, b) method returns the values from a that are not in
  526. // b. We use it to find deleted and newly inserted ids by using it in one
  527. // direction and then in the other.
  528. function incrementBoards(boardsIds, inc) {
  529. boardsIds.forEach((boardId) => {
  530. Boards.update(boardId, {$inc: {stars: inc}});
  531. });
  532. }
  533. incrementBoards(_.difference(oldIds, newIds), -1);
  534. incrementBoards(_.difference(newIds, oldIds), +1);
  535. });
  536. const fakeUserId = new Meteor.EnvironmentVariable();
  537. const getUserId = CollectionHooks.getUserId;
  538. CollectionHooks.getUserId = () => {
  539. return fakeUserId.get() || getUserId();
  540. };
  541. if (!isSandstorm) {
  542. Users.after.insert((userId, doc) => {
  543. const fakeUser = {
  544. extendAutoValueContext: {
  545. userId: doc._id,
  546. },
  547. };
  548. fakeUserId.withValue(doc._id, () => {
  549. // Insert the Welcome Board
  550. Boards.insert({
  551. title: TAPi18n.__('welcome-board'),
  552. permission: 'private',
  553. }, fakeUser, (err, boardId) => {
  554. Swimlanes.insert({
  555. title: TAPi18n.__('welcome-swimlane'),
  556. boardId,
  557. sort: 1,
  558. }, fakeUser);
  559. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  560. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  561. });
  562. });
  563. });
  564. });
  565. }
  566. Users.after.insert((userId, doc) => {
  567. if (doc.createdThroughApi) {
  568. // The admin user should be able to create a user despite disabling registration because
  569. // it is two different things (registration and creation).
  570. // So, when a new user is created via the api (only admin user can do that) one must avoid
  571. // the disableRegistration check.
  572. // Issue : https://github.com/wekan/wekan/issues/1232
  573. // PR : https://github.com/wekan/wekan/pull/1251
  574. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  575. return;
  576. }
  577. //invite user to corresponding boards
  578. const disableRegistration = Settings.findOne().disableRegistration;
  579. // If ldap, bypass the inviation code if the self registration isn't allowed.
  580. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  581. if (!doc.ldap && disableRegistration) {
  582. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  583. if (!invitationCode) {
  584. throw new Meteor.Error('error-invitation-code-not-exist');
  585. } else {
  586. invitationCode.boardsToBeInvited.forEach((boardId) => {
  587. const board = Boards.findOne(boardId);
  588. board.addMember(doc._id);
  589. });
  590. if (!doc.profile) {
  591. doc.profile = {};
  592. }
  593. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  594. Users.update(doc._id, {$set: {profile: doc.profile}});
  595. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  596. }
  597. }
  598. });
  599. }
  600. // USERS REST API
  601. if (Meteor.isServer) {
  602. // Middleware which checks that API is enabled.
  603. JsonRoutes.Middleware.use(function (req, res, next) {
  604. const api = req.url.search('api');
  605. if (api === 1 && process.env.WITH_API === 'true' || api === -1){
  606. return next();
  607. }
  608. else {
  609. res.writeHead(301, {Location: '/'});
  610. return res.end();
  611. }
  612. });
  613. JsonRoutes.add('GET', '/api/user', function(req, res) {
  614. try {
  615. Authentication.checkLoggedIn(req.userId);
  616. const data = Meteor.users.findOne({ _id: req.userId});
  617. delete data.services;
  618. JsonRoutes.sendResult(res, {
  619. code: 200,
  620. data,
  621. });
  622. }
  623. catch (error) {
  624. JsonRoutes.sendResult(res, {
  625. code: 200,
  626. data: error,
  627. });
  628. }
  629. });
  630. JsonRoutes.add('GET', '/api/users', function (req, res) {
  631. try {
  632. Authentication.checkUserId(req.userId);
  633. JsonRoutes.sendResult(res, {
  634. code: 200,
  635. data: Meteor.users.find({}).map(function (doc) {
  636. return { _id: doc._id, username: doc.username };
  637. }),
  638. });
  639. }
  640. catch (error) {
  641. JsonRoutes.sendResult(res, {
  642. code: 200,
  643. data: error,
  644. });
  645. }
  646. });
  647. JsonRoutes.add('GET', '/api/users/:id', function (req, res) {
  648. try {
  649. Authentication.checkUserId(req.userId);
  650. const id = req.params.id;
  651. JsonRoutes.sendResult(res, {
  652. code: 200,
  653. data: Meteor.users.findOne({ _id: id }),
  654. });
  655. }
  656. catch (error) {
  657. JsonRoutes.sendResult(res, {
  658. code: 200,
  659. data: error,
  660. });
  661. }
  662. });
  663. JsonRoutes.add('PUT', '/api/users/:id', function (req, res) {
  664. try {
  665. Authentication.checkUserId(req.userId);
  666. const id = req.params.id;
  667. const action = req.body.action;
  668. let data = Meteor.users.findOne({ _id: id });
  669. if (data !== undefined) {
  670. if (action === 'takeOwnership') {
  671. data = Boards.find({
  672. 'members.userId': id,
  673. 'members.isAdmin': true,
  674. }).map(function(board) {
  675. if (board.hasMember(req.userId)) {
  676. board.removeMember(req.userId);
  677. }
  678. board.changeOwnership(id, req.userId);
  679. return {
  680. _id: board._id,
  681. title: board.title,
  682. };
  683. });
  684. } else {
  685. if ((action === 'disableLogin') && (id !== req.userId)) {
  686. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  687. } else if (action === 'enableLogin') {
  688. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  689. }
  690. data = Meteor.users.findOne({ _id: id });
  691. }
  692. }
  693. JsonRoutes.sendResult(res, {
  694. code: 200,
  695. data,
  696. });
  697. }
  698. catch (error) {
  699. JsonRoutes.sendResult(res, {
  700. code: 200,
  701. data: error,
  702. });
  703. }
  704. });
  705. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function (req, res) {
  706. try {
  707. Authentication.checkUserId(req.userId);
  708. const userId = req.params.userId;
  709. const boardId = req.params.boardId;
  710. const action = req.body.action;
  711. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  712. let data = Meteor.users.findOne({ _id: userId });
  713. if (data !== undefined) {
  714. if (action === 'add') {
  715. data = Boards.find({
  716. _id: boardId,
  717. }).map(function(board) {
  718. if (!board.hasMember(userId)) {
  719. board.addMember(userId);
  720. function isTrue(data){
  721. return data.toLowerCase() === 'true';
  722. }
  723. board.setMemberPermission(userId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), userId);
  724. }
  725. return {
  726. _id: board._id,
  727. title: board.title,
  728. };
  729. });
  730. }
  731. }
  732. JsonRoutes.sendResult(res, {
  733. code: 200,
  734. data: query,
  735. });
  736. }
  737. catch (error) {
  738. JsonRoutes.sendResult(res, {
  739. code: 200,
  740. data: error,
  741. });
  742. }
  743. });
  744. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/remove', function (req, res) {
  745. try {
  746. Authentication.checkUserId(req.userId);
  747. const userId = req.params.userId;
  748. const boardId = req.params.boardId;
  749. const action = req.body.action;
  750. let data = Meteor.users.findOne({ _id: userId });
  751. if (data !== undefined) {
  752. if (action === 'remove') {
  753. data = Boards.find({
  754. _id: boardId,
  755. }).map(function(board) {
  756. if (board.hasMember(userId)) {
  757. board.removeMember(userId);
  758. }
  759. return {
  760. _id: board._id,
  761. title: board.title,
  762. };
  763. });
  764. }
  765. }
  766. JsonRoutes.sendResult(res, {
  767. code: 200,
  768. data: query,
  769. });
  770. }
  771. catch (error) {
  772. JsonRoutes.sendResult(res, {
  773. code: 200,
  774. data: error,
  775. });
  776. }
  777. });
  778. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  779. try {
  780. Authentication.checkUserId(req.userId);
  781. const id = Accounts.createUser({
  782. username: req.body.username,
  783. email: req.body.email,
  784. password: req.body.password,
  785. from: 'admin',
  786. });
  787. JsonRoutes.sendResult(res, {
  788. code: 200,
  789. data: {
  790. _id: id,
  791. },
  792. });
  793. }
  794. catch (error) {
  795. JsonRoutes.sendResult(res, {
  796. code: 200,
  797. data: error,
  798. });
  799. }
  800. });
  801. JsonRoutes.add('DELETE', '/api/users/:id', function (req, res) {
  802. try {
  803. Authentication.checkUserId(req.userId);
  804. const id = req.params.id;
  805. Meteor.users.remove({ _id: id });
  806. JsonRoutes.sendResult(res, {
  807. code: 200,
  808. data: {
  809. _id: id,
  810. },
  811. });
  812. }
  813. catch (error) {
  814. JsonRoutes.sendResult(res, {
  815. code: 200,
  816. data: error,
  817. });
  818. }
  819. });
  820. }