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