users.js 24 KB

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