users.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. /**
  7. * A User in wekan
  8. */
  9. Users.attachSchema(new SimpleSchema({
  10. username: {
  11. /**
  12. * the username of the user
  13. */
  14. type: String,
  15. optional: true,
  16. autoValue() { // eslint-disable-line consistent-return
  17. if (this.isInsert && !this.isSet) {
  18. const name = this.field('profile.fullname');
  19. if (name.isSet) {
  20. return name.value.toLowerCase().replace(/\s/g, '');
  21. }
  22. }
  23. },
  24. },
  25. emails: {
  26. /**
  27. * the list of emails attached to a user
  28. */
  29. type: [Object],
  30. optional: true,
  31. },
  32. 'emails.$.address': {
  33. /**
  34. * The email address
  35. */
  36. type: String,
  37. regEx: SimpleSchema.RegEx.Email,
  38. },
  39. 'emails.$.verified': {
  40. /**
  41. * Has the email been verified
  42. */
  43. type: Boolean,
  44. },
  45. createdAt: {
  46. /**
  47. * creation date of the user
  48. */
  49. type: Date,
  50. autoValue() { // eslint-disable-line consistent-return
  51. if (this.isInsert) {
  52. return new Date();
  53. } else {
  54. this.unset();
  55. }
  56. },
  57. },
  58. profile: {
  59. /**
  60. * profile settings
  61. */
  62. type: Object,
  63. optional: true,
  64. autoValue() { // eslint-disable-line consistent-return
  65. if (this.isInsert && !this.isSet) {
  66. return {
  67. boardView: 'board-view-lists',
  68. };
  69. }
  70. },
  71. },
  72. 'profile.avatarUrl': {
  73. /**
  74. * URL of the avatar of the user
  75. */
  76. type: String,
  77. optional: true,
  78. },
  79. 'profile.emailBuffer': {
  80. /**
  81. * list of email buffers of the user
  82. */
  83. type: [String],
  84. optional: true,
  85. },
  86. 'profile.fullname': {
  87. /**
  88. * full name of the user
  89. */
  90. type: String,
  91. optional: true,
  92. },
  93. 'profile.hiddenSystemMessages': {
  94. /**
  95. * does the user wants to hide system messages?
  96. */
  97. type: Boolean,
  98. optional: true,
  99. },
  100. 'profile.initials': {
  101. /**
  102. * initials of the user
  103. */
  104. type: String,
  105. optional: true,
  106. },
  107. 'profile.invitedBoards': {
  108. /**
  109. * board IDs the user has been invited to
  110. */
  111. type: [String],
  112. optional: true,
  113. },
  114. 'profile.language': {
  115. /**
  116. * language of the user
  117. */
  118. type: String,
  119. optional: true,
  120. },
  121. 'profile.notifications': {
  122. /**
  123. * enabled notifications for the user
  124. */
  125. type: [String],
  126. optional: true,
  127. },
  128. 'profile.showCardsCountAt': {
  129. /**
  130. * showCardCountAt field of the user
  131. */
  132. type: Number,
  133. optional: true,
  134. },
  135. 'profile.starredBoards': {
  136. /**
  137. * list of starred board IDs
  138. */
  139. type: [String],
  140. optional: true,
  141. },
  142. 'profile.icode': {
  143. /**
  144. * icode
  145. */
  146. type: String,
  147. optional: true,
  148. },
  149. 'profile.boardView': {
  150. /**
  151. * boardView field of the user
  152. */
  153. type: String,
  154. optional: true,
  155. allowedValues: [
  156. 'board-view-lists',
  157. 'board-view-swimlanes',
  158. 'board-view-cal',
  159. ],
  160. },
  161. 'profile.templatesBoardId': {
  162. /**
  163. * Reference to the templates board
  164. */
  165. type: String,
  166. defaultValue: '',
  167. },
  168. 'profile.cardTemplatesSwimlaneId': {
  169. /**
  170. * Reference to the card templates swimlane Id
  171. */
  172. type: String,
  173. defaultValue: '',
  174. },
  175. 'profile.listTemplatesSwimlaneId': {
  176. /**
  177. * Reference to the list templates swimlane Id
  178. */
  179. type: String,
  180. defaultValue: '',
  181. },
  182. 'profile.boardTemplatesSwimlaneId': {
  183. /**
  184. * Reference to the board templates swimlane Id
  185. */
  186. type: String,
  187. defaultValue: '',
  188. },
  189. services: {
  190. /**
  191. * services field of the user
  192. */
  193. type: Object,
  194. optional: true,
  195. blackbox: true,
  196. },
  197. heartbeat: {
  198. /**
  199. * last time the user has been seen
  200. */
  201. type: Date,
  202. optional: true,
  203. },
  204. isAdmin: {
  205. /**
  206. * is the user an admin of the board?
  207. */
  208. type: Boolean,
  209. optional: true,
  210. },
  211. createdThroughApi: {
  212. /**
  213. * was the user created through the API?
  214. */
  215. type: Boolean,
  216. optional: true,
  217. },
  218. loginDisabled: {
  219. /**
  220. * loginDisabled field of the user
  221. */
  222. type: Boolean,
  223. optional: true,
  224. },
  225. 'authenticationMethod': {
  226. /**
  227. * authentication method of the user
  228. */
  229. type: String,
  230. optional: false,
  231. defaultValue: 'password',
  232. },
  233. }));
  234. Users.allow({
  235. update(userId) {
  236. const user = Users.findOne(userId);
  237. return user && Meteor.user().isAdmin;
  238. },
  239. });
  240. // Search a user in the complete server database by its name or username. This
  241. // is used for instance to add a new user to a board.
  242. const searchInFields = ['username', 'profile.fullname'];
  243. Users.initEasySearch(searchInFields, {
  244. use: 'mongo-db',
  245. returnFields: [...searchInFields, 'profile.avatarUrl'],
  246. });
  247. if (Meteor.isClient) {
  248. Users.helpers({
  249. isBoardMember() {
  250. const board = Boards.findOne(Session.get('currentBoard'));
  251. return board && board.hasMember(this._id);
  252. },
  253. isNotNoComments() {
  254. const board = Boards.findOne(Session.get('currentBoard'));
  255. return board && board.hasMember(this._id) && !board.hasNoComments(this._id);
  256. },
  257. isNoComments() {
  258. const board = Boards.findOne(Session.get('currentBoard'));
  259. return board && board.hasNoComments(this._id);
  260. },
  261. isNotCommentOnly() {
  262. const board = Boards.findOne(Session.get('currentBoard'));
  263. return board && board.hasMember(this._id) && !board.hasCommentOnly(this._id);
  264. },
  265. isCommentOnly() {
  266. const board = Boards.findOne(Session.get('currentBoard'));
  267. return board && board.hasCommentOnly(this._id);
  268. },
  269. isBoardAdmin() {
  270. const board = Boards.findOne(Session.get('currentBoard'));
  271. return board && board.hasAdmin(this._id);
  272. },
  273. });
  274. }
  275. Users.helpers({
  276. boards() {
  277. return Boards.find({ 'members.userId': this._id });
  278. },
  279. starredBoards() {
  280. const {starredBoards = []} = this.profile;
  281. return Boards.find({archived: false, _id: {$in: starredBoards}});
  282. },
  283. hasStarred(boardId) {
  284. const {starredBoards = []} = this.profile;
  285. return _.contains(starredBoards, boardId);
  286. },
  287. invitedBoards() {
  288. const {invitedBoards = []} = this.profile;
  289. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  290. },
  291. isInvitedTo(boardId) {
  292. const {invitedBoards = []} = this.profile;
  293. return _.contains(invitedBoards, boardId);
  294. },
  295. hasTag(tag) {
  296. const {tags = []} = this.profile;
  297. return _.contains(tags, tag);
  298. },
  299. hasNotification(activityId) {
  300. const {notifications = []} = this.profile;
  301. return _.contains(notifications, activityId);
  302. },
  303. hasHiddenSystemMessages() {
  304. const profile = this.profile || {};
  305. return profile.hiddenSystemMessages || false;
  306. },
  307. getEmailBuffer() {
  308. const {emailBuffer = []} = this.profile;
  309. return emailBuffer;
  310. },
  311. getInitials() {
  312. const profile = this.profile || {};
  313. if (profile.initials)
  314. return profile.initials;
  315. else if (profile.fullname) {
  316. return profile.fullname.split(/\s+/).reduce((memo, word) => {
  317. return memo + word[0];
  318. }, '').toUpperCase();
  319. } else {
  320. return this.username[0].toUpperCase();
  321. }
  322. },
  323. getLimitToShowCardsCount() {
  324. const profile = this.profile || {};
  325. return profile.showCardsCountAt;
  326. },
  327. getName() {
  328. const profile = this.profile || {};
  329. return profile.fullname || this.username;
  330. },
  331. getLanguage() {
  332. const profile = this.profile || {};
  333. return profile.language || 'en';
  334. },
  335. getTemplatesBoardId() {
  336. return this.profile.templatesBoardId;
  337. },
  338. getTemplatesBoardSlug() {
  339. return Boards.findOne(this.profile.templatesBoardId).slug;
  340. },
  341. });
  342. Users.mutations({
  343. toggleBoardStar(boardId) {
  344. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  345. return {
  346. [queryKind]: {
  347. 'profile.starredBoards': boardId,
  348. },
  349. };
  350. },
  351. addInvite(boardId) {
  352. return {
  353. $addToSet: {
  354. 'profile.invitedBoards': boardId,
  355. },
  356. };
  357. },
  358. removeInvite(boardId) {
  359. return {
  360. $pull: {
  361. 'profile.invitedBoards': boardId,
  362. },
  363. };
  364. },
  365. addTag(tag) {
  366. return {
  367. $addToSet: {
  368. 'profile.tags': tag,
  369. },
  370. };
  371. },
  372. removeTag(tag) {
  373. return {
  374. $pull: {
  375. 'profile.tags': tag,
  376. },
  377. };
  378. },
  379. toggleTag(tag) {
  380. if (this.hasTag(tag))
  381. this.removeTag(tag);
  382. else
  383. this.addTag(tag);
  384. },
  385. toggleSystem(value = false) {
  386. return {
  387. $set: {
  388. 'profile.hiddenSystemMessages': !value,
  389. },
  390. };
  391. },
  392. addNotification(activityId) {
  393. return {
  394. $addToSet: {
  395. 'profile.notifications': activityId,
  396. },
  397. };
  398. },
  399. removeNotification(activityId) {
  400. return {
  401. $pull: {
  402. 'profile.notifications': activityId,
  403. },
  404. };
  405. },
  406. addEmailBuffer(text) {
  407. return {
  408. $addToSet: {
  409. 'profile.emailBuffer': text,
  410. },
  411. };
  412. },
  413. clearEmailBuffer() {
  414. return {
  415. $set: {
  416. 'profile.emailBuffer': [],
  417. },
  418. };
  419. },
  420. setAvatarUrl(avatarUrl) {
  421. return {$set: {'profile.avatarUrl': avatarUrl}};
  422. },
  423. setShowCardsCountAt(limit) {
  424. return {$set: {'profile.showCardsCountAt': limit}};
  425. },
  426. setBoardView(view) {
  427. return {
  428. $set : {
  429. 'profile.boardView': view,
  430. },
  431. };
  432. },
  433. });
  434. Meteor.methods({
  435. setUsername(username, userId) {
  436. check(username, String);
  437. const nUsersWithUsername = Users.find({username}).count();
  438. if (nUsersWithUsername > 0) {
  439. throw new Meteor.Error('username-already-taken');
  440. } else {
  441. Users.update(userId, {$set: {username}});
  442. }
  443. },
  444. toggleSystemMessages() {
  445. const user = Meteor.user();
  446. user.toggleSystem(user.hasHiddenSystemMessages());
  447. },
  448. changeLimitToShowCardsCount(limit) {
  449. check(limit, Number);
  450. Meteor.user().setShowCardsCountAt(limit);
  451. },
  452. setEmail(email, userId) {
  453. check(email, String);
  454. const existingUser = Users.findOne({'emails.address': email}, {fields: {_id: 1}});
  455. if (existingUser) {
  456. throw new Meteor.Error('email-already-taken');
  457. } else {
  458. Users.update(userId, {
  459. $set: {
  460. emails: [{
  461. address: email,
  462. verified: false,
  463. }],
  464. },
  465. });
  466. }
  467. },
  468. setUsernameAndEmail(username, email, userId) {
  469. check(username, String);
  470. check(email, String);
  471. check(userId, String);
  472. Meteor.call('setUsername', username, userId);
  473. Meteor.call('setEmail', email, userId);
  474. },
  475. setPassword(newPassword, userId) {
  476. check(userId, String);
  477. check(newPassword, String);
  478. if(Meteor.user().isAdmin){
  479. Accounts.setPassword(userId, newPassword);
  480. }
  481. },
  482. });
  483. if (Meteor.isServer) {
  484. Meteor.methods({
  485. // we accept userId, username, email
  486. inviteUserToBoard(username, boardId) {
  487. check(username, String);
  488. check(boardId, String);
  489. const inviter = Meteor.user();
  490. const board = Boards.findOne(boardId);
  491. const allowInvite = inviter &&
  492. board &&
  493. board.members &&
  494. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  495. _.where(board.members, {userId: inviter._id})[0].isActive &&
  496. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  497. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  498. this.unblock();
  499. const posAt = username.indexOf('@');
  500. let user = null;
  501. if (posAt >= 0) {
  502. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  503. } else {
  504. user = Users.findOne(username) || Users.findOne({username});
  505. }
  506. if (user) {
  507. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  508. } else {
  509. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  510. if (Settings.findOne().disableRegistration) throw new Meteor.Error('error-user-notCreated');
  511. // Set in lowercase email before creating account
  512. const email = username.toLowerCase();
  513. username = email.substring(0, posAt);
  514. const newUserId = Accounts.createUser({username, email});
  515. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  516. // assume new user speak same language with inviter
  517. if (inviter.profile && inviter.profile.language) {
  518. Users.update(newUserId, {
  519. $set: {
  520. 'profile.language': inviter.profile.language,
  521. },
  522. });
  523. }
  524. Accounts.sendEnrollmentEmail(newUserId);
  525. user = Users.findOne(newUserId);
  526. }
  527. board.addMember(user._id);
  528. user.addInvite(boardId);
  529. try {
  530. const params = {
  531. user: user.username,
  532. inviter: inviter.username,
  533. board: board.title,
  534. url: board.absoluteUrl(),
  535. };
  536. const lang = user.getLanguage();
  537. Email.send({
  538. to: user.emails[0].address.toLowerCase(),
  539. from: Accounts.emailTemplates.from,
  540. subject: TAPi18n.__('email-invite-subject', params, lang),
  541. text: TAPi18n.__('email-invite-text', params, lang),
  542. });
  543. } catch (e) {
  544. throw new Meteor.Error('email-fail', e.message);
  545. }
  546. return {username: user.username, email: user.emails[0].address};
  547. },
  548. });
  549. Accounts.onCreateUser((options, user) => {
  550. const userCount = Users.find().count();
  551. if (!isSandstorm && userCount === 0) {
  552. user.isAdmin = true;
  553. return user;
  554. }
  555. if (user.services.oidc) {
  556. const email = user.services.oidc.email.toLowerCase();
  557. user.username = user.services.oidc.username;
  558. user.emails = [{ address: email, verified: true }];
  559. const initials = user.services.oidc.fullname.match(/\b[a-zA-Z]/g).join('').toUpperCase();
  560. user.profile = { initials, fullname: user.services.oidc.fullname, boardView: 'board-view-lists' };
  561. user.authenticationMethod = 'oauth2';
  562. // see if any existing user has this email address or username, otherwise create new
  563. const existingUser = Meteor.users.findOne({$or: [{'emails.address': email}, {'username':user.username}]});
  564. if (!existingUser)
  565. return user;
  566. // copy across new service info
  567. const service = _.keys(user.services)[0];
  568. existingUser.services[service] = user.services[service];
  569. existingUser.emails = user.emails;
  570. existingUser.username = user.username;
  571. existingUser.profile = user.profile;
  572. existingUser.authenticationMethod = user.authenticationMethod;
  573. Meteor.users.remove({_id: existingUser._id}); // remove existing record
  574. return existingUser;
  575. }
  576. if (options.from === 'admin') {
  577. user.createdThroughApi = true;
  578. return user;
  579. }
  580. const disableRegistration = Settings.findOne().disableRegistration;
  581. // If this is the first Authentication by the ldap and self registration disabled
  582. if (disableRegistration && options && options.ldap) {
  583. user.authenticationMethod = 'ldap';
  584. return user;
  585. }
  586. // If self registration enabled
  587. if (!disableRegistration) {
  588. return user;
  589. }
  590. if (!options || !options.profile) {
  591. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  592. }
  593. const invitationCode = InvitationCodes.findOne({
  594. code: options.profile.invitationcode,
  595. email: options.email,
  596. valid: true,
  597. });
  598. if (!invitationCode) {
  599. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  600. } else {
  601. user.profile = {icode: options.profile.invitationcode};
  602. user.profile.boardView = 'board-view-lists';
  603. // Deletes the invitation code after the user was created successfully.
  604. setTimeout(Meteor.bindEnvironment(() => {
  605. InvitationCodes.remove({'_id': invitationCode._id});
  606. }), 200);
  607. return user;
  608. }
  609. });
  610. }
  611. if (Meteor.isServer) {
  612. // Let mongoDB ensure username unicity
  613. Meteor.startup(() => {
  614. Users._collection._ensureIndex({
  615. username: 1,
  616. }, {unique: true});
  617. });
  618. // Each board document contains the de-normalized number of users that have
  619. // starred it. If the user star or unstar a board, we need to update this
  620. // counter.
  621. // We need to run this code on the server only, otherwise the incrementation
  622. // will be done twice.
  623. Users.after.update(function (userId, user, fieldNames) {
  624. // The `starredBoards` list is hosted on the `profile` field. If this
  625. // field hasn't been modificated we don't need to run this hook.
  626. if (!_.contains(fieldNames, 'profile'))
  627. return;
  628. // To calculate a diff of board starred ids, we get both the previous
  629. // and the newly board ids list
  630. function getStarredBoardsIds(doc) {
  631. return doc.profile && doc.profile.starredBoards;
  632. }
  633. const oldIds = getStarredBoardsIds(this.previous);
  634. const newIds = getStarredBoardsIds(user);
  635. // The _.difference(a, b) method returns the values from a that are not in
  636. // b. We use it to find deleted and newly inserted ids by using it in one
  637. // direction and then in the other.
  638. function incrementBoards(boardsIds, inc) {
  639. boardsIds.forEach((boardId) => {
  640. Boards.update(boardId, {$inc: {stars: inc}});
  641. });
  642. }
  643. incrementBoards(_.difference(oldIds, newIds), -1);
  644. incrementBoards(_.difference(newIds, oldIds), +1);
  645. });
  646. const fakeUserId = new Meteor.EnvironmentVariable();
  647. const getUserId = CollectionHooks.getUserId;
  648. CollectionHooks.getUserId = () => {
  649. return fakeUserId.get() || getUserId();
  650. };
  651. if (!isSandstorm) {
  652. Users.after.insert((userId, doc) => {
  653. const fakeUser = {
  654. extendAutoValueContext: {
  655. userId: doc._id,
  656. },
  657. };
  658. fakeUserId.withValue(doc._id, () => {
  659. // Insert the Welcome Board
  660. Boards.insert({
  661. title: TAPi18n.__('welcome-board'),
  662. permission: 'private',
  663. }, fakeUser, (err, boardId) => {
  664. Swimlanes.insert({
  665. title: TAPi18n.__('welcome-swimlane'),
  666. boardId,
  667. sort: 1,
  668. }, fakeUser);
  669. ['welcome-list1', 'welcome-list2'].forEach((title, titleIndex) => {
  670. Lists.insert({title: TAPi18n.__(title), boardId, sort: titleIndex}, fakeUser);
  671. });
  672. });
  673. Boards.insert({
  674. title: TAPi18n.__('templates'),
  675. permission: 'private',
  676. type: 'template-container'
  677. }, fakeUser, (err, boardId) => {
  678. // Insert the reference to our templates board
  679. Users.update(fakeUserId.get(), {$set: {'profile.templatesBoardId': boardId}});
  680. // Insert the card templates swimlane
  681. Swimlanes.insert({
  682. title: TAPi18n.__('card-templates-swimlane'),
  683. boardId,
  684. sort: 1,
  685. type: 'template-container',
  686. }, fakeUser, (err, swimlaneId) => {
  687. // Insert the reference to out card templates swimlane
  688. Users.update(fakeUserId.get(), {$set: {'profile.cardTemplatesSwimlaneId': swimlaneId}});
  689. });
  690. // Insert the list templates swimlane
  691. Swimlanes.insert({
  692. title: TAPi18n.__('list-templates-swimlane'),
  693. boardId,
  694. sort: 2,
  695. type: 'template-container',
  696. }, fakeUser, (err, swimlaneId) => {
  697. // Insert the reference to out list templates swimlane
  698. Users.update(fakeUserId.get(), {$set: {'profile.listTemplatesSwimlaneId': swimlaneId}});
  699. });
  700. // Insert the board templates swimlane
  701. Swimlanes.insert({
  702. title: TAPi18n.__('board-templates-swimlane'),
  703. boardId,
  704. sort: 3,
  705. type: 'template-container',
  706. }, fakeUser, (err, swimlaneId) => {
  707. // Insert the reference to out board templates swimlane
  708. Users.update(fakeUserId.get(), {$set: {'profile.boardTemplatesSwimlaneId': swimlaneId}});
  709. });
  710. });
  711. });
  712. });
  713. }
  714. Users.after.insert((userId, doc) => {
  715. if (doc.createdThroughApi) {
  716. // The admin user should be able to create a user despite disabling registration because
  717. // it is two different things (registration and creation).
  718. // So, when a new user is created via the api (only admin user can do that) one must avoid
  719. // the disableRegistration check.
  720. // Issue : https://github.com/wekan/wekan/issues/1232
  721. // PR : https://github.com/wekan/wekan/pull/1251
  722. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  723. return;
  724. }
  725. //invite user to corresponding boards
  726. const disableRegistration = Settings.findOne().disableRegistration;
  727. // If ldap, bypass the inviation code if the self registration isn't allowed.
  728. // TODO : pay attention if ldap field in the user model change to another content ex : ldap field to connection_type
  729. if (doc.authenticationMethod !== 'ldap' && disableRegistration) {
  730. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  731. if (!invitationCode) {
  732. throw new Meteor.Error('error-invitation-code-not-exist');
  733. } else {
  734. invitationCode.boardsToBeInvited.forEach((boardId) => {
  735. const board = Boards.findOne(boardId);
  736. board.addMember(doc._id);
  737. });
  738. if (!doc.profile) {
  739. doc.profile = {};
  740. }
  741. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  742. Users.update(doc._id, {$set: {profile: doc.profile}});
  743. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  744. }
  745. }
  746. });
  747. }
  748. // USERS REST API
  749. if (Meteor.isServer) {
  750. // Middleware which checks that API is enabled.
  751. JsonRoutes.Middleware.use(function (req, res, next) {
  752. const api = req.url.search('api');
  753. if (api === 1 && process.env.WITH_API === 'true' || api === -1){
  754. return next();
  755. }
  756. else {
  757. res.writeHead(301, {Location: '/'});
  758. return res.end();
  759. }
  760. });
  761. /**
  762. * @operation get_current_user
  763. *
  764. * @summary returns the current user
  765. * @return_type Users
  766. */
  767. JsonRoutes.add('GET', '/api/user', function(req, res) {
  768. try {
  769. Authentication.checkLoggedIn(req.userId);
  770. const data = Meteor.users.findOne({ _id: req.userId});
  771. delete data.services;
  772. JsonRoutes.sendResult(res, {
  773. code: 200,
  774. data,
  775. });
  776. }
  777. catch (error) {
  778. JsonRoutes.sendResult(res, {
  779. code: 200,
  780. data: error,
  781. });
  782. }
  783. });
  784. /**
  785. * @operation get_all_users
  786. *
  787. * @summary return all the users
  788. *
  789. * @description Only the admin user (the first user) can call the REST API.
  790. * @return_type [{ _id: string,
  791. * username: string}]
  792. */
  793. JsonRoutes.add('GET', '/api/users', function (req, res) {
  794. try {
  795. Authentication.checkUserId(req.userId);
  796. JsonRoutes.sendResult(res, {
  797. code: 200,
  798. data: Meteor.users.find({}).map(function (doc) {
  799. return { _id: doc._id, username: doc.username };
  800. }),
  801. });
  802. }
  803. catch (error) {
  804. JsonRoutes.sendResult(res, {
  805. code: 200,
  806. data: error,
  807. });
  808. }
  809. });
  810. /**
  811. * @operation get_user
  812. *
  813. * @summary get a given user
  814. *
  815. * @description Only the admin user (the first user) can call the REST API.
  816. *
  817. * @param {string} userId the user ID
  818. * @return_type Users
  819. */
  820. JsonRoutes.add('GET', '/api/users/:userId', function (req, res) {
  821. try {
  822. Authentication.checkUserId(req.userId);
  823. const id = req.params.userId;
  824. JsonRoutes.sendResult(res, {
  825. code: 200,
  826. data: Meteor.users.findOne({ _id: id }),
  827. });
  828. }
  829. catch (error) {
  830. JsonRoutes.sendResult(res, {
  831. code: 200,
  832. data: error,
  833. });
  834. }
  835. });
  836. /**
  837. * @operation edit_user
  838. *
  839. * @summary edit a given user
  840. *
  841. * @description Only the admin user (the first user) can call the REST API.
  842. *
  843. * Possible values for *action*:
  844. * - `takeOwnership`: The admin takes the ownership of ALL boards of the user (archived and not archived) where the user is admin on.
  845. * - `disableLogin`: Disable a user (the user is not allowed to login and his login tokens are purged)
  846. * - `enableLogin`: Enable a user
  847. *
  848. * @param {string} userId the user ID
  849. * @param {string} action the action
  850. * @return_type {_id: string,
  851. * title: string}
  852. */
  853. JsonRoutes.add('PUT', '/api/users/:userId', function (req, res) {
  854. try {
  855. Authentication.checkUserId(req.userId);
  856. const id = req.params.userId;
  857. const action = req.body.action;
  858. let data = Meteor.users.findOne({ _id: id });
  859. if (data !== undefined) {
  860. if (action === 'takeOwnership') {
  861. data = Boards.find({
  862. 'members.userId': id,
  863. 'members.isAdmin': true,
  864. }).map(function(board) {
  865. if (board.hasMember(req.userId)) {
  866. board.removeMember(req.userId);
  867. }
  868. board.changeOwnership(id, req.userId);
  869. return {
  870. _id: board._id,
  871. title: board.title,
  872. };
  873. });
  874. } else {
  875. if ((action === 'disableLogin') && (id !== req.userId)) {
  876. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  877. } else if (action === 'enableLogin') {
  878. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  879. }
  880. data = Meteor.users.findOne({ _id: id });
  881. }
  882. }
  883. JsonRoutes.sendResult(res, {
  884. code: 200,
  885. data,
  886. });
  887. }
  888. catch (error) {
  889. JsonRoutes.sendResult(res, {
  890. code: 200,
  891. data: error,
  892. });
  893. }
  894. });
  895. /**
  896. * @operation add_board_member
  897. * @tag Boards
  898. *
  899. * @summary Add New Board Member with Role
  900. *
  901. * @description Only the admin user (the first user) can call the REST API.
  902. *
  903. * **Note**: see [Boards.set_board_member_permission](#set_board_member_permission)
  904. * to later change the permissions.
  905. *
  906. * @param {string} boardId the board ID
  907. * @param {string} userId the user ID
  908. * @param {boolean} isAdmin is the user an admin of the board
  909. * @param {boolean} isNoComments disable comments
  910. * @param {boolean} isCommentOnly only enable comments
  911. * @return_type {_id: string,
  912. * title: string}
  913. */
  914. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/add', function (req, res) {
  915. try {
  916. Authentication.checkUserId(req.userId);
  917. const userId = req.params.userId;
  918. const boardId = req.params.boardId;
  919. const action = req.body.action;
  920. const {isAdmin, isNoComments, isCommentOnly} = req.body;
  921. let data = Meteor.users.findOne({ _id: userId });
  922. if (data !== undefined) {
  923. if (action === 'add') {
  924. data = Boards.find({
  925. _id: boardId,
  926. }).map(function(board) {
  927. if (!board.hasMember(userId)) {
  928. board.addMember(userId);
  929. function isTrue(data){
  930. return data.toLowerCase() === 'true';
  931. }
  932. board.setMemberPermission(userId, isTrue(isAdmin), isTrue(isNoComments), isTrue(isCommentOnly), userId);
  933. }
  934. return {
  935. _id: board._id,
  936. title: board.title,
  937. };
  938. });
  939. }
  940. }
  941. JsonRoutes.sendResult(res, {
  942. code: 200,
  943. data: query,
  944. });
  945. }
  946. catch (error) {
  947. JsonRoutes.sendResult(res, {
  948. code: 200,
  949. data: error,
  950. });
  951. }
  952. });
  953. /**
  954. * @operation remove_board_member
  955. * @tag Boards
  956. *
  957. * @summary Remove Member from Board
  958. *
  959. * @description Only the admin user (the first user) can call the REST API.
  960. *
  961. * @param {string} boardId the board ID
  962. * @param {string} userId the user ID
  963. * @param {string} action the action (needs to be `remove`)
  964. * @return_type {_id: string,
  965. * title: string}
  966. */
  967. JsonRoutes.add('POST', '/api/boards/:boardId/members/:userId/remove', function (req, res) {
  968. try {
  969. Authentication.checkUserId(req.userId);
  970. const userId = req.params.userId;
  971. const boardId = req.params.boardId;
  972. const action = req.body.action;
  973. let data = Meteor.users.findOne({ _id: userId });
  974. if (data !== undefined) {
  975. if (action === 'remove') {
  976. data = Boards.find({
  977. _id: boardId,
  978. }).map(function(board) {
  979. if (board.hasMember(userId)) {
  980. board.removeMember(userId);
  981. }
  982. return {
  983. _id: board._id,
  984. title: board.title,
  985. };
  986. });
  987. }
  988. }
  989. JsonRoutes.sendResult(res, {
  990. code: 200,
  991. data: query,
  992. });
  993. }
  994. catch (error) {
  995. JsonRoutes.sendResult(res, {
  996. code: 200,
  997. data: error,
  998. });
  999. }
  1000. });
  1001. /**
  1002. * @operation new_user
  1003. *
  1004. * @summary Create a new user
  1005. *
  1006. * @description Only the admin user (the first user) can call the REST API.
  1007. *
  1008. * @param {string} username the new username
  1009. * @param {string} email the email of the new user
  1010. * @param {string} password the password of the new user
  1011. * @return_type {_id: string}
  1012. */
  1013. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  1014. try {
  1015. Authentication.checkUserId(req.userId);
  1016. const id = Accounts.createUser({
  1017. username: req.body.username,
  1018. email: req.body.email,
  1019. password: req.body.password,
  1020. from: 'admin',
  1021. });
  1022. JsonRoutes.sendResult(res, {
  1023. code: 200,
  1024. data: {
  1025. _id: id,
  1026. },
  1027. });
  1028. }
  1029. catch (error) {
  1030. JsonRoutes.sendResult(res, {
  1031. code: 200,
  1032. data: error,
  1033. });
  1034. }
  1035. });
  1036. /**
  1037. * @operation delete_user
  1038. *
  1039. * @summary Delete a user
  1040. *
  1041. * @description Only the admin user (the first user) can call the REST API.
  1042. *
  1043. * @param {string} userId the ID of the user to delete
  1044. * @return_type {_id: string}
  1045. */
  1046. JsonRoutes.add('DELETE', '/api/users/:userId', function (req, res) {
  1047. try {
  1048. Authentication.checkUserId(req.userId);
  1049. const id = req.params.userId;
  1050. Meteor.users.remove({ _id: id });
  1051. JsonRoutes.sendResult(res, {
  1052. code: 200,
  1053. data: {
  1054. _id: id,
  1055. },
  1056. });
  1057. }
  1058. catch (error) {
  1059. JsonRoutes.sendResult(res, {
  1060. code: 200,
  1061. data: error,
  1062. });
  1063. }
  1064. });
  1065. }