users.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. }
  47. },
  48. },
  49. 'profile.avatarUrl': {
  50. type: String,
  51. optional: true,
  52. },
  53. 'profile.emailBuffer': {
  54. type: [String],
  55. optional: true,
  56. },
  57. 'profile.fullname': {
  58. type: String,
  59. optional: true,
  60. },
  61. 'profile.hiddenSystemMessages': {
  62. type: Boolean,
  63. optional: true,
  64. },
  65. 'profile.initials': {
  66. type: String,
  67. optional: true,
  68. },
  69. 'profile.invitedBoards': {
  70. type: [String],
  71. optional: true,
  72. },
  73. 'profile.language': {
  74. type: String,
  75. optional: true,
  76. },
  77. 'profile.notifications': {
  78. type: [String],
  79. optional: true,
  80. },
  81. 'profile.showCardsCountAt': {
  82. type: Number,
  83. optional: true,
  84. },
  85. 'profile.starredBoards': {
  86. type: [String],
  87. optional: true,
  88. },
  89. 'profile.tags': {
  90. type: [String],
  91. optional: true,
  92. },
  93. 'profile.icode': {
  94. type: String,
  95. optional: true,
  96. },
  97. services: {
  98. type: Object,
  99. optional: true,
  100. blackbox: true,
  101. },
  102. heartbeat: {
  103. type: Date,
  104. optional: true,
  105. },
  106. isAdmin: {
  107. type: Boolean,
  108. optional: true,
  109. },
  110. createdThroughApi: {
  111. type: Boolean,
  112. optional: true,
  113. },
  114. loginDisabled: {
  115. type: Boolean,
  116. optional: true,
  117. },
  118. }));
  119. Users.allow({
  120. update(userId) {
  121. const user = Users.findOne(userId);
  122. return user && Meteor.user().isAdmin;
  123. },
  124. });
  125. // Search a user in the complete server database by its name or username. This
  126. // is used for instance to add a new user to a board.
  127. const searchInFields = ['username', 'profile.fullname'];
  128. Users.initEasySearch(searchInFields, {
  129. use: 'mongo-db',
  130. returnFields: [...searchInFields, 'profile.avatarUrl'],
  131. });
  132. if (Meteor.isClient) {
  133. Users.helpers({
  134. isBoardMember() {
  135. const board = Boards.findOne(Session.get('currentBoard'));
  136. return board && board.hasMember(this._id);
  137. },
  138. isNotCommentOnly() {
  139. const board = Boards.findOne(Session.get('currentBoard'));
  140. return board && board.hasMember(this._id) && !board.hasCommentOnly(this._id);
  141. },
  142. isCommentOnly() {
  143. const board = Boards.findOne(Session.get('currentBoard'));
  144. return board && board.hasCommentOnly(this._id);
  145. },
  146. isBoardAdmin() {
  147. const board = Boards.findOne(Session.get('currentBoard'));
  148. return board && board.hasAdmin(this._id);
  149. },
  150. });
  151. }
  152. Users.helpers({
  153. boards() {
  154. return Boards.find({ 'members.userId': this._id });
  155. },
  156. starredBoards() {
  157. const {starredBoards = []} = this.profile;
  158. return Boards.find({archived: false, _id: {$in: starredBoards}});
  159. },
  160. hasStarred(boardId) {
  161. const {starredBoards = []} = this.profile;
  162. return _.contains(starredBoards, boardId);
  163. },
  164. invitedBoards() {
  165. const {invitedBoards = []} = this.profile;
  166. return Boards.find({archived: false, _id: {$in: invitedBoards}});
  167. },
  168. isInvitedTo(boardId) {
  169. const {invitedBoards = []} = this.profile;
  170. return _.contains(invitedBoards, boardId);
  171. },
  172. hasTag(tag) {
  173. const {tags = []} = this.profile;
  174. return _.contains(tags, tag);
  175. },
  176. hasNotification(activityId) {
  177. const {notifications = []} = this.profile;
  178. return _.contains(notifications, activityId);
  179. },
  180. hasHiddenSystemMessages() {
  181. const profile = this.profile || {};
  182. return profile.hiddenSystemMessages || false;
  183. },
  184. getEmailBuffer() {
  185. const {emailBuffer = []} = this.profile;
  186. return emailBuffer;
  187. },
  188. getInitials() {
  189. const profile = this.profile || {};
  190. if (profile.initials)
  191. return profile.initials;
  192. else if (profile.fullname) {
  193. return profile.fullname.split(/\s+/).reduce((memo, word) => {
  194. return memo + word[0];
  195. }, '').toUpperCase();
  196. } else {
  197. return this.username[0].toUpperCase();
  198. }
  199. },
  200. getLimitToShowCardsCount() {
  201. const profile = this.profile || {};
  202. return profile.showCardsCountAt;
  203. },
  204. getName() {
  205. const profile = this.profile || {};
  206. return profile.fullname || this.username;
  207. },
  208. getLanguage() {
  209. const profile = this.profile || {};
  210. return profile.language || 'en';
  211. },
  212. });
  213. Users.mutations({
  214. toggleBoardStar(boardId) {
  215. const queryKind = this.hasStarred(boardId) ? '$pull' : '$addToSet';
  216. return {
  217. [queryKind]: {
  218. 'profile.starredBoards': boardId,
  219. },
  220. };
  221. },
  222. addInvite(boardId) {
  223. return {
  224. $addToSet: {
  225. 'profile.invitedBoards': boardId,
  226. },
  227. };
  228. },
  229. removeInvite(boardId) {
  230. return {
  231. $pull: {
  232. 'profile.invitedBoards': boardId,
  233. },
  234. };
  235. },
  236. addTag(tag) {
  237. return {
  238. $addToSet: {
  239. 'profile.tags': tag,
  240. },
  241. };
  242. },
  243. removeTag(tag) {
  244. return {
  245. $pull: {
  246. 'profile.tags': tag,
  247. },
  248. };
  249. },
  250. toggleTag(tag) {
  251. if (this.hasTag(tag))
  252. this.removeTag(tag);
  253. else
  254. this.addTag(tag);
  255. },
  256. toggleSystem(value = false) {
  257. return {
  258. $set: {
  259. 'profile.hiddenSystemMessages': !value,
  260. },
  261. };
  262. },
  263. addNotification(activityId) {
  264. return {
  265. $addToSet: {
  266. 'profile.notifications': activityId,
  267. },
  268. };
  269. },
  270. removeNotification(activityId) {
  271. return {
  272. $pull: {
  273. 'profile.notifications': activityId,
  274. },
  275. };
  276. },
  277. addEmailBuffer(text) {
  278. return {
  279. $addToSet: {
  280. 'profile.emailBuffer': text,
  281. },
  282. };
  283. },
  284. clearEmailBuffer() {
  285. return {
  286. $set: {
  287. 'profile.emailBuffer': [],
  288. },
  289. };
  290. },
  291. setAvatarUrl(avatarUrl) {
  292. return {$set: {'profile.avatarUrl': avatarUrl}};
  293. },
  294. setShowCardsCountAt(limit) {
  295. return {$set: {'profile.showCardsCountAt': limit}};
  296. },
  297. });
  298. Meteor.methods({
  299. setUsername(username, userId) {
  300. check(username, String);
  301. const nUsersWithUsername = Users.find({username}).count();
  302. if (nUsersWithUsername > 0) {
  303. throw new Meteor.Error('username-already-taken');
  304. } else {
  305. Users.update(userId, {$set: {username}});
  306. }
  307. },
  308. toggleSystemMessages() {
  309. const user = Meteor.user();
  310. user.toggleSystem(user.hasHiddenSystemMessages());
  311. },
  312. changeLimitToShowCardsCount(limit) {
  313. check(limit, Number);
  314. Meteor.user().setShowCardsCountAt(limit);
  315. },
  316. setEmail(email, userId) {
  317. check(email, String);
  318. const existingUser = Users.findOne({'emails.address': email}, {fields: {_id: 1}});
  319. if (existingUser) {
  320. throw new Meteor.Error('email-already-taken');
  321. } else {
  322. Users.update(userId, {
  323. $set: {
  324. emails: [{
  325. address: email,
  326. verified: false,
  327. }],
  328. },
  329. });
  330. }
  331. },
  332. setUsernameAndEmail(username, email, userId) {
  333. check(username, String);
  334. check(email, String);
  335. check(userId, String);
  336. Meteor.call('setUsername', username, userId);
  337. Meteor.call('setEmail', email, userId);
  338. },
  339. setPassword(newPassword, userId) {
  340. check(userId, String);
  341. check(newPassword, String);
  342. if(Meteor.user().isAdmin){
  343. Accounts.setPassword(userId, newPassword);
  344. }
  345. },
  346. });
  347. if (Meteor.isServer) {
  348. Meteor.methods({
  349. // we accept userId, username, email
  350. inviteUserToBoard(username, boardId) {
  351. check(username, String);
  352. check(boardId, String);
  353. const inviter = Meteor.user();
  354. const board = Boards.findOne(boardId);
  355. const allowInvite = inviter &&
  356. board &&
  357. board.members &&
  358. _.contains(_.pluck(board.members, 'userId'), inviter._id) &&
  359. _.where(board.members, {userId: inviter._id})[0].isActive &&
  360. _.where(board.members, {userId: inviter._id})[0].isAdmin;
  361. if (!allowInvite) throw new Meteor.Error('error-board-notAMember');
  362. this.unblock();
  363. const posAt = username.indexOf('@');
  364. let user = null;
  365. if (posAt >= 0) {
  366. user = Users.findOne({emails: {$elemMatch: {address: username}}});
  367. } else {
  368. user = Users.findOne(username) || Users.findOne({username});
  369. }
  370. if (user) {
  371. if (user._id === inviter._id) throw new Meteor.Error('error-user-notAllowSelf');
  372. } else {
  373. if (posAt <= 0) throw new Meteor.Error('error-user-doesNotExist');
  374. if (Settings.findOne().disableRegistration) throw new Meteor.Error('error-user-notCreated');
  375. // Set in lowercase email before creating account
  376. const email = username.toLowerCase();
  377. username = email.substring(0, posAt);
  378. const newUserId = Accounts.createUser({username, email});
  379. if (!newUserId) throw new Meteor.Error('error-user-notCreated');
  380. // assume new user speak same language with inviter
  381. if (inviter.profile && inviter.profile.language) {
  382. Users.update(newUserId, {
  383. $set: {
  384. 'profile.language': inviter.profile.language,
  385. },
  386. });
  387. }
  388. Accounts.sendEnrollmentEmail(newUserId);
  389. user = Users.findOne(newUserId);
  390. }
  391. board.addMember(user._id);
  392. user.addInvite(boardId);
  393. try {
  394. const params = {
  395. user: user.username,
  396. inviter: inviter.username,
  397. board: board.title,
  398. url: board.absoluteUrl(),
  399. };
  400. const lang = user.getLanguage();
  401. Email.send({
  402. to: user.emails[0].address.toLowerCase(),
  403. from: Accounts.emailTemplates.from,
  404. subject: TAPi18n.__('email-invite-subject', params, lang),
  405. text: TAPi18n.__('email-invite-text', params, lang),
  406. });
  407. } catch (e) {
  408. throw new Meteor.Error('email-fail', e.message);
  409. }
  410. return {username: user.username, email: user.emails[0].address};
  411. },
  412. });
  413. Accounts.onCreateUser((options, user) => {
  414. const userCount = Users.find().count();
  415. if (!isSandstorm && userCount === 0) {
  416. user.isAdmin = true;
  417. return user;
  418. }
  419. if (options.from === 'admin') {
  420. user.createdThroughApi = true;
  421. return user;
  422. }
  423. const disableRegistration = Settings.findOne().disableRegistration;
  424. if (!disableRegistration) {
  425. return user;
  426. }
  427. if (!options || !options.profile) {
  428. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  429. }
  430. const invitationCode = InvitationCodes.findOne({
  431. code: options.profile.invitationcode,
  432. email: options.email,
  433. valid: true,
  434. });
  435. if (!invitationCode) {
  436. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  437. } else {
  438. user.profile = {icode: options.profile.invitationcode};
  439. }
  440. return user;
  441. });
  442. }
  443. if (Meteor.isServer) {
  444. // Let mongoDB ensure username unicity
  445. Meteor.startup(() => {
  446. Users._collection._ensureIndex({
  447. username: 1,
  448. }, {unique: true});
  449. });
  450. // Each board document contains the de-normalized number of users that have
  451. // starred it. If the user star or unstar a board, we need to update this
  452. // counter.
  453. // We need to run this code on the server only, otherwise the incrementation
  454. // will be done twice.
  455. Users.after.update(function (userId, user, fieldNames) {
  456. // The `starredBoards` list is hosted on the `profile` field. If this
  457. // field hasn't been modificated we don't need to run this hook.
  458. if (!_.contains(fieldNames, 'profile'))
  459. return;
  460. // To calculate a diff of board starred ids, we get both the previous
  461. // and the newly board ids list
  462. function getStarredBoardsIds(doc) {
  463. return doc.profile && doc.profile.starredBoards;
  464. }
  465. const oldIds = getStarredBoardsIds(this.previous);
  466. const newIds = getStarredBoardsIds(user);
  467. // The _.difference(a, b) method returns the values from a that are not in
  468. // b. We use it to find deleted and newly inserted ids by using it in one
  469. // direction and then in the other.
  470. function incrementBoards(boardsIds, inc) {
  471. boardsIds.forEach((boardId) => {
  472. Boards.update(boardId, {$inc: {stars: inc}});
  473. });
  474. }
  475. incrementBoards(_.difference(oldIds, newIds), -1);
  476. incrementBoards(_.difference(newIds, oldIds), +1);
  477. });
  478. const fakeUserId = new Meteor.EnvironmentVariable();
  479. const getUserId = CollectionHooks.getUserId;
  480. CollectionHooks.getUserId = () => {
  481. return fakeUserId.get() || getUserId();
  482. };
  483. if (!isSandstorm) {
  484. Users.after.insert((userId, doc) => {
  485. const fakeUser = {
  486. extendAutoValueContext: {
  487. userId: doc._id,
  488. },
  489. };
  490. fakeUserId.withValue(doc._id, () => {
  491. // Insert the Welcome Board
  492. Boards.insert({
  493. title: TAPi18n.__('welcome-board'),
  494. permission: 'private',
  495. }, fakeUser, (err, boardId) => {
  496. ['welcome-list1', 'welcome-list2'].forEach((title) => {
  497. Lists.insert({title: TAPi18n.__(title), boardId}, fakeUser);
  498. });
  499. });
  500. });
  501. });
  502. }
  503. Users.after.insert((userId, doc) => {
  504. if (doc.createdThroughApi) {
  505. // The admin user should be able to create a user despite disabling registration because
  506. // it is two different things (registration and creation).
  507. // So, when a new user is created via the api (only admin user can do that) one must avoid
  508. // the disableRegistration check.
  509. // Issue : https://github.com/wekan/wekan/issues/1232
  510. // PR : https://github.com/wekan/wekan/pull/1251
  511. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  512. return;
  513. }
  514. //invite user to corresponding boards
  515. const disableRegistration = Settings.findOne().disableRegistration;
  516. if (disableRegistration) {
  517. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  518. if (!invitationCode) {
  519. throw new Meteor.Error('error-invitation-code-not-exist');
  520. } else {
  521. invitationCode.boardsToBeInvited.forEach((boardId) => {
  522. const board = Boards.findOne(boardId);
  523. board.addMember(doc._id);
  524. });
  525. if (!doc.profile) {
  526. doc.profile = {};
  527. }
  528. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  529. Users.update(doc._id, {$set: {profile: doc.profile}});
  530. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  531. }
  532. }
  533. });
  534. }
  535. // USERS REST API
  536. if (Meteor.isServer) {
  537. JsonRoutes.add('GET', '/api/user', function(req, res, next) {
  538. try {
  539. Authentication.checkLoggedIn(req.userId);
  540. const data = Meteor.users.findOne({ _id: req.userId});
  541. delete data.services;
  542. JsonRoutes.sendResult(res, {
  543. code: 200,
  544. data,
  545. });
  546. }
  547. catch (error) {
  548. JsonRoutes.sendResult(res, {
  549. code: 200,
  550. data: error,
  551. });
  552. }
  553. });
  554. JsonRoutes.add('GET', '/api/users', function (req, res, next) {
  555. try {
  556. Authentication.checkUserId(req.userId);
  557. JsonRoutes.sendResult(res, {
  558. code: 200,
  559. data: Meteor.users.find({}).map(function (doc) {
  560. return { _id: doc._id, username: doc.username };
  561. }),
  562. });
  563. }
  564. catch (error) {
  565. JsonRoutes.sendResult(res, {
  566. code: 200,
  567. data: error,
  568. });
  569. }
  570. });
  571. JsonRoutes.add('GET', '/api/users/:id', function (req, res, next) {
  572. try {
  573. Authentication.checkUserId(req.userId);
  574. const id = req.params.id;
  575. JsonRoutes.sendResult(res, {
  576. code: 200,
  577. data: Meteor.users.findOne({ _id: id }),
  578. });
  579. }
  580. catch (error) {
  581. JsonRoutes.sendResult(res, {
  582. code: 200,
  583. data: error,
  584. });
  585. }
  586. });
  587. JsonRoutes.add('PUT', '/api/users/:id', function (req, res, next) {
  588. try {
  589. Authentication.checkUserId(req.userId);
  590. const id = req.params.id;
  591. const action = req.body.action;
  592. let data = Meteor.users.findOne({ _id: id });
  593. if (data !== undefined) {
  594. if (action === 'takeOwnership') {
  595. data = Boards.find({
  596. 'members.userId': id,
  597. 'members.isAdmin': true,
  598. }).map(function(board) {
  599. if (board.hasMember(req.userId)) {
  600. board.removeMember(req.userId);
  601. }
  602. board.changeOwnership(id, req.userId);
  603. return {
  604. _id: board._id,
  605. title: board.title,
  606. };
  607. });
  608. } else {
  609. if ((action === 'disableLogin') && (id !== req.userId)) {
  610. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  611. } else if (action === 'enableLogin') {
  612. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  613. }
  614. data = Meteor.users.findOne({ _id: id });
  615. }
  616. }
  617. JsonRoutes.sendResult(res, {
  618. code: 200,
  619. data,
  620. });
  621. }
  622. catch (error) {
  623. JsonRoutes.sendResult(res, {
  624. code: 200,
  625. data: error,
  626. });
  627. }
  628. });
  629. JsonRoutes.add('POST', '/api/users/', function (req, res, next) {
  630. try {
  631. Authentication.checkUserId(req.userId);
  632. const id = Accounts.createUser({
  633. username: req.body.username,
  634. email: req.body.email,
  635. password: req.body.password,
  636. from: 'admin',
  637. });
  638. JsonRoutes.sendResult(res, {
  639. code: 200,
  640. data: {
  641. _id: id,
  642. },
  643. });
  644. }
  645. catch (error) {
  646. JsonRoutes.sendResult(res, {
  647. code: 200,
  648. data: error,
  649. });
  650. }
  651. });
  652. JsonRoutes.add('DELETE', '/api/users/:id', function (req, res, next) {
  653. try {
  654. Authentication.checkUserId(req.userId);
  655. const id = req.params.id;
  656. Meteor.users.remove({ _id: id });
  657. JsonRoutes.sendResult(res, {
  658. code: 200,
  659. data: {
  660. _id: id,
  661. },
  662. });
  663. }
  664. catch (error) {
  665. JsonRoutes.sendResult(res, {
  666. code: 200,
  667. data: error,
  668. });
  669. }
  670. });
  671. }