users.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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 (user.services.oidc) {
  420. var email = user.services.oidc.email.toLowerCase();
  421. user.username = user.services.oidc.username;
  422. user.emails = [{ address: email,
  423. verified: true }];
  424. var initials = user.services.oidc.fullname.match(/\b[a-zA-Z]/g).join('').toUpperCase();
  425. user.profile = { initials: initials, fullname: user.services.oidc.fullname };
  426. // see if any existing user has this email address or username, otherwise create new
  427. var existingUser = Meteor.users.findOne({$or: [{'emails.address': email}, {'username':user.username}]});
  428. console.log("user to create : ");
  429. console.log(user);
  430. if (!existingUser)
  431. return user;
  432. // copy across new service info
  433. var service = _.keys(user.services)[0];
  434. existingUser.services[service] = user.services[service];
  435. existingUser.emails = user.emails;
  436. existingUser.username = user.username;
  437. existingUser.profile = user.profile;
  438. Meteor.users.remove({_id: existingUser._id}); // remove existing record
  439. return existingUser;
  440. }
  441. if (options.from === 'admin') {
  442. user.createdThroughApi = true;
  443. return user;
  444. }
  445. const disableRegistration = Settings.findOne().disableRegistration;
  446. if (!disableRegistration) {
  447. return user;
  448. }
  449. if (!options || !options.profile) {
  450. throw new Meteor.Error('error-invitation-code-blank', 'The invitation code is required');
  451. }
  452. const invitationCode = InvitationCodes.findOne({
  453. code: options.profile.invitationcode,
  454. email: options.email,
  455. valid: true,
  456. });
  457. if (!invitationCode) {
  458. throw new Meteor.Error('error-invitation-code-not-exist', 'The invitation code doesn\'t exist');
  459. } else {
  460. user.profile = {icode: options.profile.invitationcode};
  461. }
  462. return user;
  463. });
  464. }
  465. if (Meteor.isServer) {
  466. // Let mongoDB ensure username unicity
  467. Meteor.startup(() => {
  468. Users._collection._ensureIndex({
  469. username: 1,
  470. }, {unique: true});
  471. });
  472. // Each board document contains the de-normalized number of users that have
  473. // starred it. If the user star or unstar a board, we need to update this
  474. // counter.
  475. // We need to run this code on the server only, otherwise the incrementation
  476. // will be done twice.
  477. Users.after.update(function (userId, user, fieldNames) {
  478. // The `starredBoards` list is hosted on the `profile` field. If this
  479. // field hasn't been modificated we don't need to run this hook.
  480. if (!_.contains(fieldNames, 'profile'))
  481. return;
  482. // To calculate a diff of board starred ids, we get both the previous
  483. // and the newly board ids list
  484. function getStarredBoardsIds(doc) {
  485. return doc.profile && doc.profile.starredBoards;
  486. }
  487. const oldIds = getStarredBoardsIds(this.previous);
  488. const newIds = getStarredBoardsIds(user);
  489. // The _.difference(a, b) method returns the values from a that are not in
  490. // b. We use it to find deleted and newly inserted ids by using it in one
  491. // direction and then in the other.
  492. function incrementBoards(boardsIds, inc) {
  493. boardsIds.forEach((boardId) => {
  494. Boards.update(boardId, {$inc: {stars: inc}});
  495. });
  496. }
  497. incrementBoards(_.difference(oldIds, newIds), -1);
  498. incrementBoards(_.difference(newIds, oldIds), +1);
  499. });
  500. const fakeUserId = new Meteor.EnvironmentVariable();
  501. const getUserId = CollectionHooks.getUserId;
  502. CollectionHooks.getUserId = () => {
  503. return fakeUserId.get() || getUserId();
  504. };
  505. if (!isSandstorm) {
  506. Users.after.insert((userId, doc) => {
  507. const fakeUser = {
  508. extendAutoValueContext: {
  509. userId: doc._id,
  510. },
  511. };
  512. fakeUserId.withValue(doc._id, () => {
  513. // Insert the Welcome Board
  514. Boards.insert({
  515. title: TAPi18n.__('welcome-board'),
  516. permission: 'private',
  517. }, fakeUser, (err, boardId) => {
  518. Swimlanes.insert({
  519. title: TAPi18n.__('welcome-swimlane'),
  520. boardId,
  521. }, fakeUser);
  522. ['welcome-list1', 'welcome-list2'].forEach((title) => {
  523. Lists.insert({title: TAPi18n.__(title), boardId}, fakeUser);
  524. });
  525. });
  526. });
  527. });
  528. }
  529. Users.after.insert((userId, doc) => {
  530. if (doc.createdThroughApi) {
  531. // The admin user should be able to create a user despite disabling registration because
  532. // it is two different things (registration and creation).
  533. // So, when a new user is created via the api (only admin user can do that) one must avoid
  534. // the disableRegistration check.
  535. // Issue : https://github.com/wekan/wekan/issues/1232
  536. // PR : https://github.com/wekan/wekan/pull/1251
  537. Users.update(doc._id, {$set: {createdThroughApi: ''}});
  538. return;
  539. }
  540. //invite user to corresponding boards
  541. const disableRegistration = Settings.findOne().disableRegistration;
  542. if (disableRegistration) {
  543. const invitationCode = InvitationCodes.findOne({code: doc.profile.icode, valid: true});
  544. if (!invitationCode) {
  545. throw new Meteor.Error('error-invitation-code-not-exist');
  546. } else {
  547. invitationCode.boardsToBeInvited.forEach((boardId) => {
  548. const board = Boards.findOne(boardId);
  549. board.addMember(doc._id);
  550. });
  551. if (!doc.profile) {
  552. doc.profile = {};
  553. }
  554. doc.profile.invitedBoards = invitationCode.boardsToBeInvited;
  555. Users.update(doc._id, {$set: {profile: doc.profile}});
  556. InvitationCodes.update(invitationCode._id, {$set: {valid: false}});
  557. }
  558. }
  559. });
  560. }
  561. // USERS REST API
  562. if (Meteor.isServer) {
  563. JsonRoutes.add('GET', '/api/user', function(req, res) {
  564. try {
  565. Authentication.checkLoggedIn(req.userId);
  566. const data = Meteor.users.findOne({ _id: req.userId});
  567. delete data.services;
  568. JsonRoutes.sendResult(res, {
  569. code: 200,
  570. data,
  571. });
  572. }
  573. catch (error) {
  574. JsonRoutes.sendResult(res, {
  575. code: 200,
  576. data: error,
  577. });
  578. }
  579. });
  580. JsonRoutes.add('GET', '/api/users', function (req, res) {
  581. try {
  582. Authentication.checkUserId(req.userId);
  583. JsonRoutes.sendResult(res, {
  584. code: 200,
  585. data: Meteor.users.find({}).map(function (doc) {
  586. return { _id: doc._id, username: doc.username };
  587. }),
  588. });
  589. }
  590. catch (error) {
  591. JsonRoutes.sendResult(res, {
  592. code: 200,
  593. data: error,
  594. });
  595. }
  596. });
  597. JsonRoutes.add('GET', '/api/users/:id', function (req, res) {
  598. try {
  599. Authentication.checkUserId(req.userId);
  600. const id = req.params.id;
  601. JsonRoutes.sendResult(res, {
  602. code: 200,
  603. data: Meteor.users.findOne({ _id: id }),
  604. });
  605. }
  606. catch (error) {
  607. JsonRoutes.sendResult(res, {
  608. code: 200,
  609. data: error,
  610. });
  611. }
  612. });
  613. JsonRoutes.add('PUT', '/api/users/:id', function (req, res) {
  614. try {
  615. Authentication.checkUserId(req.userId);
  616. const id = req.params.id;
  617. const action = req.body.action;
  618. let data = Meteor.users.findOne({ _id: id });
  619. if (data !== undefined) {
  620. if (action === 'takeOwnership') {
  621. data = Boards.find({
  622. 'members.userId': id,
  623. 'members.isAdmin': true,
  624. }).map(function(board) {
  625. if (board.hasMember(req.userId)) {
  626. board.removeMember(req.userId);
  627. }
  628. board.changeOwnership(id, req.userId);
  629. return {
  630. _id: board._id,
  631. title: board.title,
  632. };
  633. });
  634. } else {
  635. if ((action === 'disableLogin') && (id !== req.userId)) {
  636. Users.update({ _id: id }, { $set: { loginDisabled: true, 'services.resume.loginTokens': '' } });
  637. } else if (action === 'enableLogin') {
  638. Users.update({ _id: id }, { $set: { loginDisabled: '' } });
  639. }
  640. data = Meteor.users.findOne({ _id: id });
  641. }
  642. }
  643. JsonRoutes.sendResult(res, {
  644. code: 200,
  645. data,
  646. });
  647. }
  648. catch (error) {
  649. JsonRoutes.sendResult(res, {
  650. code: 200,
  651. data: error,
  652. });
  653. }
  654. });
  655. JsonRoutes.add('POST', '/api/users/', function (req, res) {
  656. try {
  657. Authentication.checkUserId(req.userId);
  658. const id = Accounts.createUser({
  659. username: req.body.username,
  660. email: req.body.email,
  661. password: req.body.password,
  662. from: 'admin',
  663. });
  664. JsonRoutes.sendResult(res, {
  665. code: 200,
  666. data: {
  667. _id: id,
  668. },
  669. });
  670. }
  671. catch (error) {
  672. JsonRoutes.sendResult(res, {
  673. code: 200,
  674. data: error,
  675. });
  676. }
  677. });
  678. JsonRoutes.add('DELETE', '/api/users/:id', function (req, res) {
  679. try {
  680. Authentication.checkUserId(req.userId);
  681. const id = req.params.id;
  682. Meteor.users.remove({ _id: id });
  683. JsonRoutes.sendResult(res, {
  684. code: 200,
  685. data: {
  686. _id: id,
  687. },
  688. });
  689. }
  690. catch (error) {
  691. JsonRoutes.sendResult(res, {
  692. code: 200,
  693. data: error,
  694. });
  695. }
  696. });
  697. }