users.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 ldap, bypass the inviation code if the self registration isn't allowed.
  473. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  474. if (options.ldap || !disableRegistration) {
  475. user.authenticationMethod = 'ldap';
  476. return user;
  477. }
  478. if (!options || !options.profile) {
  479. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  480. }
  481. const invitationCode = InvitationCodes.findOne({
  482. code: options.profile.invitationcode,
  483. email: options.email,
  484. valid: true,
  485. });
  486. if (!invitationCode) {
  487. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  488. } else {
  489. user.profile = {icode: options.profile.invitationcode};
  490. user.profile.boardView = 'board-view-lists';
  491. // Deletes the invitation code after the user was created successfully.
  492. setTimeout(Meteor.bindEnvironment(() => {
  493. InvitationCodes.remove({'_id': invitationCode._id});
  494. }), 200);
  495. return user;
  496. }
  497. });
  498. }
  499. if (Meteor.isServer) {
  500. // Let mongoDB ensure username unicity
  501. Meteor.startup(() => {
  502. Users._collection._ensureIndex({
  503. username: 1,
  504. }, {unique: true});
  505. });
  506. // Each board document contains the de-normalized number of users that have
  507. // starred it. If the user star or unstar a board, we need to update this
  508. // counter.
  509. // We need to run this code on the server only, otherwise the incrementation
  510. // will be done twice.
  511. Users.after.update(function (userId, user, fieldNames) {
  512. // The `starredBoards` list is hosted on the `profile` field. If this
  513. // field hasn't been modificated we don't need to run this hook.
  514. if (!_.contains(fieldNames, 'profile'))
  515. return;
  516. // To calculate a diff of board starred ids, we get both the previous
  517. // and the newly board ids list
  518. function getStarredBoardsIds(doc) {
  519. return doc.profile && doc.profile.starredBoards;
  520. }
  521. const oldIds = getStarredBoardsIds(this.previous);
  522. const newIds = getStarredBoardsIds(user);
  523. // The _.difference(a, b) method returns the values from a that are not in
  524. // b. We use it to find deleted and newly inserted ids by using it in one
  525. // direction and then in the other.
  526. function incrementBoards(boardsIds, inc) {
  527. boardsIds.forEach((boardId) => {
  528. Boards.update(boardId, {$inc: {stars: inc}});
  529. });
  530. }
  531. incrementBoards(_.difference(oldIds, newIds), -1);
  532. incrementBoards(_.difference(newIds, oldIds), +1);
  533. });
  534. const fakeUserId = new Meteor.EnvironmentVariable();
  535. const getUserId = CollectionHooks.getUserId;
  536. CollectionHooks.getUserId = () => {
  537. return fakeUserId.get() || getUserId();
  538. };
  539. if (!isSandstorm) {
  540. Users.after.insert((userId, doc) => {
  541. const fakeUser = {
  542. extendAutoValueContext: {
  543. userId: doc._id,
  544. },
  545. };
  546. fakeUserId.withValue(doc._id, () => {
  547. // Insert the Welcome Board
  548. Boards.insert({
  549. title: TAPi18n.__('welcome-board'),
  550. permission: 'private',
  551. }, fakeUser, (err, boardId) => {
  552. Swimlanes.insert({
  553. title: TAPi18n.__('welcome-swimlane'),
  554. boardId,
  555. sort: 1,
  556. }, fakeUser);
  557. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  558. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  559. });
  560. });
  561. });
  562. });
  563. }
  564. Users.after.insert((userId, doc) => {
  565. if (doc.createdThroughApi) {
  566. // The admin user should be able to create a user despite disabling registration because
  567. // it is two different things (registration and creation).
  568. // So, when a new user is created via the api (only admin user can do that) one must avoid
  569. // the disableRegistration check.
  570. // Issue : https://github.com/wekan/wekan/issues/1232
  571. // PR : https://github.com/wekan/wekan/pull/1251
  572. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  573. return;
  574. }
  575. //invite user to corresponding boards
  576. const disableRegistration = Settings.findOne().disableRegistration;
  577. // If ldap, bypass the inviation code if the self registration isn't allowed.
  578. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  579. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  580. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  581. if (!invitationCode) {
  582. throw new Meteor.Error('error-invitation-code-not-exist');
  583. } else {
  584. invitationCode.boardsToBeInvited.forEach((boardId) => {
  585. const board = Boards.findOne(boardId);
  586. board.addMember(doc._id);
  587. });
  588. if (!doc.profile) {
  589. doc.profile = {};
  590. }
  591. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  592. Users.update(doc._id, {$set: {profile: doc.profile}});
  593. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  594. }
  595. }
  596. });
  597. }
  598. // USERS REST API
  599. if (Meteor.isServer) {
  600. // Middleware which checks that API is enabled.
  601. JsonRoutes.Middleware.use(function (req, res, next) {
  602. const api = req.url.search('api');
  603. if (api === 1 && process.env.WITH_API === 'true' || api === -1){
  604. return next();
  605. }
  606. else {
  607. res.writeHead(301, {Location: '/'});
  608. return res.end();
  609. }
  610. });
  611. JsonRoutes.add('GET', '/api/user', function(req, res) {
  612. try {
  613. Authentication.checkLoggedIn(req.userId);
  614. const data = Meteor.users.findOne({ _id: req.userId});
  615. delete data.services;
  616. JsonRoutes.sendResult(res, {
  617. code: 200,
  618. data,
  619. });
  620. }
  621. catch (error) {
  622. JsonRoutes.sendResult(res, {
  623. code: 200,
  624. data: error,
  625. });
  626. }
  627. });
  628. JsonRoutes.add('GET', '/api/users', function (req, res) {
  629. try {
  630. Authentication.checkUserId(req.userId);
  631. JsonRoutes.sendResult(res, {
  632. code: 200,
  633. data: Meteor.users.find({}).map(function (doc) {
  634. return { _id: doc._id, username: doc.username };
  635. }),
  636. });
  637. }
  638. catch (error) {
  639. JsonRoutes.sendResult(res, {
  640. code: 200,
  641. data: error,
  642. });
  643. }
  644. });
  645. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  646. try {
  647. Authentication.checkUserId(req.userId);
  648. const id = req.params.userId;
  649. JsonRoutes.sendResult(res, {
  650. code: 200,
  651. data: Meteor.users.findOne({ _id: id }),
  652. });
  653. }
  654. catch (error) {
  655. JsonRoutes.sendResult(res, {
  656. code: 200,
  657. data: error,
  658. });
  659. }
  660. });
  661. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  662. try {
  663. Authentication.checkUserId(req.userId);
  664. const id = req.params.userId;
  665. const action = req.body.action;
  666. let data = Meteor.users.findOne({ _id: id });
  667. if (data !== undefined) {
  668. if (action === 'takeOwnership') {
  669. data = Boards.find({
  670. 'members.userId': id,
  671. 'members.isAdmin': true,
  672. }).map(function(board) {
  673. if (board.hasMember(req.userId)) {
  674. board.removeMember(req.userId);
  675. }
  676. board.changeOwnership(id, req.userId);
  677. return {
  678. _id: board._id,
  679. title: board.title,
  680. };
  681. });
  682. } else {
  683. if ((action === 'disableLogin') && (id !== req.userId)) {
  684. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  685. } else if (action === 'enableLogin') {
  686. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  687. }
  688. data = Meteor.users.findOne({ _id: id });
  689. }
  690. }
  691. JsonRoutes.sendResult(res, {
  692. code: 200,
  693. data,
  694. });
  695. }
  696. catch (error) {
  697. JsonRoutes.sendResult(res, {
  698. code: 200,
  699. data: error,
  700. });
  701. }
  702. });
  703. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function (req, res) {
  704. try {
  705. Authentication.checkUserId(req.userId);
  706. const userId = req.params.userId;
  707. const boardId = req.params.boardId;
  708. const action = req.body.action;
  709. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  710. let data = Meteor.users.findOne({ _id: userId });
  711. if (data !== undefined) {
  712. if (action === 'add') {
  713. data = Boards.find({
  714. _id: boardId,
  715. }).map(function(board) {
  716. if (!board.hasMember(userId)) {
  717. board.addMember(userId);
  718. function isTrue(data){
  719. return data.toLowerCase() === 'true';
  720. }
  721. board.setMemberPermission(userId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), userId);
  722. }
  723. return {
  724. _id: board._id,
  725. title: board.title,
  726. };
  727. });
  728. }
  729. }
  730. JsonRoutes.sendResult(res, {
  731. code: 200,
  732. data: query,
  733. });
  734. }
  735. catch (error) {
  736. JsonRoutes.sendResult(res, {
  737. code: 200,
  738. data: error,
  739. });
  740. }
  741. });
  742. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/remove', function (req, res) {
  743. try {
  744. Authentication.checkUserId(req.userId);
  745. const userId = req.params.userId;
  746. const boardId = req.params.boardId;
  747. const action = req.body.action;
  748. let data = Meteor.users.findOne({ _id: userId });
  749. if (data !== undefined) {
  750. if (action === 'remove') {
  751. data = Boards.find({
  752. _id: boardId,
  753. }).map(function(board) {
  754. if (board.hasMember(userId)) {
  755. board.removeMember(userId);
  756. }
  757. return {
  758. _id: board._id,
  759. title: board.title,
  760. };
  761. });
  762. }
  763. }
  764. JsonRoutes.sendResult(res, {
  765. code: 200,
  766. data: query,
  767. });
  768. }
  769. catch (error) {
  770. JsonRoutes.sendResult(res, {
  771. code: 200,
  772. data: error,
  773. });
  774. }
  775. });
  776. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  777. try {
  778. Authentication.checkUserId(req.userId);
  779. const id = Accounts.createUser({
  780. username: req.body.username,
  781. email: req.body.email,
  782. password: req.body.password,
  783. from: 'admin',
  784. });
  785. JsonRoutes.sendResult(res, {
  786. code: 200,
  787. data: {
  788. _id: id,
  789. },
  790. });
  791. }
  792. catch (error) {
  793. JsonRoutes.sendResult(res, {
  794. code: 200,
  795. data: error,
  796. });
  797. }
  798. });
  799. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  800. try {
  801. Authentication.checkUserId(req.userId);
  802. const id = req.params.userId;
  803. Meteor.users.remove({ _id: id });
  804. JsonRoutes.sendResult(res, {
  805. code: 200,
  806. data: {
  807. _id: id,
  808. },
  809. });
  810. }
  811. catch (error) {
  812. JsonRoutes.sendResult(res, {
  813. code: 200,
  814. data: error,
  815. });
  816. }
  817. });
  818. }