users.js 17 KB

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