sync.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import _ from 'underscore';
  2. import SyncedCron from 'meteor/percolate:synced-cron';
  3. import LDAP from './ldap';
  4. import { log_debug, log_info, log_warn, log_error } from './logger';
  5. Object.defineProperty(Object.prototype, "getLDAPValue", {
  6. value: function (prop) {
  7. const self = this;
  8. for (let key in self) {
  9. if (key.toLowerCase() == prop.toLowerCase()) {
  10. return self[key];
  11. }
  12. }
  13. },
  14. enumerable: false
  15. });
  16. export function slug(text) {
  17. if (LDAP.settings_get('LDAP_UTF8_NAMES_SLUGIFY') !== true) {
  18. return text;
  19. }
  20. text = slugify(text, '.');
  21. return text.replace(/[^0-9a-z-_.]/g, '');
  22. }
  23. function templateVarHandler (variable, object) {
  24. const templateRegex = /#{([\w\-]+)}/gi;
  25. let match = templateRegex.exec(variable);
  26. let tmpVariable = variable;
  27. if (match == null) {
  28. if (!object.hasOwnProperty(variable)) {
  29. return;
  30. }
  31. return object[variable];
  32. } else {
  33. while (match != null) {
  34. const tmplVar = match[0];
  35. const tmplAttrName = match[1];
  36. if (!object.hasOwnProperty(tmplAttrName)) {
  37. return;
  38. }
  39. const attrVal = object[tmplAttrName];
  40. tmpVariable = tmpVariable.replace(tmplVar, attrVal);
  41. match = templateRegex.exec(variable);
  42. }
  43. return tmpVariable;
  44. }
  45. }
  46. export function getPropertyValue(obj, key) {
  47. try {
  48. return _.reduce(key.split('.'), (acc, el) => acc[el], obj);
  49. } catch (err) {
  50. return undefined;
  51. }
  52. }
  53. export function getLdapUsername(ldapUser) {
  54. const usernameField = LDAP.settings_get('LDAP_USERNAME_FIELD');
  55. if (usernameField.indexOf('#{') > -1) {
  56. return usernameField.replace(/#{(.+?)}/g, function(match, field) {
  57. return ldapUser.getLDAPValue(field);
  58. });
  59. }
  60. return ldapUser.getLDAPValue(usernameField);
  61. }
  62. export function getLdapEmail(ldapUser) {
  63. const emailField = LDAP.settings_get('LDAP_EMAIL_FIELD');
  64. if (emailField.indexOf('#{') > -1) {
  65. return emailField.replace(/#{(.+?)}/g, function(match, field) {
  66. return ldapUser.getLDAPValue(field);
  67. });
  68. }
  69. return ldapUser.getLDAPValue(emailField);
  70. }
  71. export function getLdapFullname(ldapUser) {
  72. const fullnameField = LDAP.settings_get('LDAP_FULLNAME_FIELD');
  73. if (fullnameField.indexOf('#{') > -1) {
  74. return fullnameField.replace(/#{(.+?)}/g, function(match, field) {
  75. return ldapUser.getLDAPValue(field);
  76. });
  77. }
  78. return ldapUser.getLDAPValue(fullnameField);
  79. }
  80. export function getLdapUserUniqueID(ldapUser) {
  81. let Unique_Identifier_Field = LDAP.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD');
  82. if (Unique_Identifier_Field !== '') {
  83. Unique_Identifier_Field = Unique_Identifier_Field.replace(/\s/g, '').split(',');
  84. } else {
  85. Unique_Identifier_Field = [];
  86. }
  87. let User_Search_Field = LDAP.settings_get('LDAP_USER_SEARCH_FIELD');
  88. if (User_Search_Field !== '') {
  89. User_Search_Field = User_Search_Field.replace(/\s/g, '').split(',');
  90. } else {
  91. User_Search_Field = [];
  92. }
  93. Unique_Identifier_Field = Unique_Identifier_Field.concat(User_Search_Field);
  94. if (Unique_Identifier_Field.length > 0) {
  95. Unique_Identifier_Field = Unique_Identifier_Field.find((field) => {
  96. return !_.isEmpty(ldapUser._raw.getLDAPValue(field));
  97. });
  98. if (Unique_Identifier_Field) {
  99. log_debug(`Identifying user with: ${ Unique_Identifier_Field}`);
  100. Unique_Identifier_Field = {
  101. attribute: Unique_Identifier_Field,
  102. value: ldapUser._raw.getLDAPValue(Unique_Identifier_Field).toString('hex'),
  103. };
  104. }
  105. return Unique_Identifier_Field;
  106. }
  107. }
  108. export function getDataToSyncUserData(ldapUser, user) {
  109. const syncUserData = LDAP.settings_get('LDAP_SYNC_USER_DATA');
  110. const syncUserDataFieldMap = LDAP.settings_get('LDAP_SYNC_USER_DATA_FIELDMAP').trim();
  111. const userData = {};
  112. if (syncUserData && syncUserDataFieldMap) {
  113. const whitelistedUserFields = ['email', 'name', 'customFields'];
  114. const fieldMap = JSON.parse(syncUserDataFieldMap);
  115. const emailList = [];
  116. _.map(fieldMap, function(userField, ldapField) {
  117. log_debug(`Mapping field ${ldapField} -> ${userField}`);
  118. switch (userField) {
  119. case 'email':
  120. if (!ldapUser.hasOwnProperty(ldapField)) {
  121. log_debug(`user does not have attribute: ${ ldapField }`);
  122. return;
  123. }
  124. if (_.isObject(ldapUser[ldapField])) {
  125. _.map(ldapUser[ldapField], function(item) {
  126. emailList.push({ address: item, verified: true });
  127. });
  128. } else {
  129. emailList.push({ address: ldapUser[ldapField], verified: true });
  130. }
  131. break;
  132. default:
  133. const [outerKey, innerKeys] = userField.split(/\.(.+)/);
  134. if (!_.find(whitelistedUserFields, (el) => el === outerKey)) {
  135. log_debug(`user attribute not whitelisted: ${ userField }`);
  136. return;
  137. }
  138. if (outerKey === 'customFields') {
  139. let customFieldsMeta;
  140. try {
  141. customFieldsMeta = JSON.parse(LDAP.settings_get('Accounts_CustomFields'));
  142. } catch (e) {
  143. log_debug('Invalid JSON for Custom Fields');
  144. return;
  145. }
  146. if (!getPropertyValue(customFieldsMeta, innerKeys)) {
  147. log_debug(`user attribute does not exist: ${ userField }`);
  148. return;
  149. }
  150. }
  151. const tmpUserField = getPropertyValue(user, userField);
  152. const tmpLdapField = templateVarHandler(ldapField, ldapUser);
  153. if (tmpLdapField && tmpUserField !== tmpLdapField) {
  154. // creates the object structure instead of just assigning 'tmpLdapField' to
  155. // 'userData[userField]' in order to avoid the "cannot use the part (...)
  156. // to traverse the element" (MongoDB) error that can happen. Do not handle
  157. // arrays.
  158. // TODO: Find a better solution.
  159. const dKeys = userField.split('.');
  160. const lastKey = _.last(dKeys);
  161. _.reduce(dKeys, (obj, currKey) =>
  162. (currKey === lastKey)
  163. ? obj[currKey] = tmpLdapField
  164. : obj[currKey] = obj[currKey] || {}
  165. , userData);
  166. log_debug(`user.${ userField } changed to: ${ tmpLdapField }`);
  167. }
  168. }
  169. });
  170. if (emailList.length > 0) {
  171. if (JSON.stringify(user.emails) !== JSON.stringify(emailList)) {
  172. userData.emails = emailList;
  173. }
  174. }
  175. }
  176. const uniqueId = getLdapUserUniqueID(ldapUser);
  177. if (uniqueId && (!user.services || !user.services.ldap || user.services.ldap.id !== uniqueId.value || user.services.ldap.idAttribute !== uniqueId.attribute)) {
  178. userData['services.ldap.id'] = uniqueId.value;
  179. userData['services.ldap.idAttribute'] = uniqueId.attribute;
  180. }
  181. if (user.authenticationMethod !== 'ldap') {
  182. userData.ldap = true;
  183. }
  184. if (_.size(userData)) {
  185. return userData;
  186. }
  187. }
  188. export function syncUserData(user, ldapUser) {
  189. log_info('Syncing user data');
  190. log_debug('user', {'email': user.email, '_id': user._id});
  191. // log_debug('ldapUser', ldapUser.object);
  192. if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') {
  193. const username = slug(getLdapUsername(ldapUser));
  194. if (user && user._id && username !== user.username) {
  195. log_info('Syncing user username', user.username, '->', username);
  196. Meteor.users.findOne({ _id: user._id }, { $set: { username }});
  197. }
  198. }
  199. if (LDAP.settings_get('LDAP_FULLNAME_FIELD') !== '') {
  200. const fullname= getLdapFullname(ldapUser);
  201. log_debug('fullname=',fullname);
  202. if (user && user._id && fullname !== '') {
  203. log_info('Syncing user fullname:', fullname);
  204. Meteor.users.update({ _id: user._id }, { $set: { 'profile.fullname' : fullname, }});
  205. }
  206. }
  207. if (LDAP.settings_get('LDAP_EMAIL_FIELD') !== '') {
  208. const email = getLdapEmail(ldapUser);
  209. log_debug('email=', email);
  210. if (user && user._id && email !== '') {
  211. log_info('Syncing user email:', email);
  212. Meteor.users.update({
  213. _id: user._id
  214. }, {
  215. $set: {
  216. 'emails.0.address': email,
  217. }
  218. });
  219. }
  220. }
  221. }
  222. export function addLdapUser(ldapUser, username, password) {
  223. const uniqueId = getLdapUserUniqueID(ldapUser);
  224. const userObject = {
  225. };
  226. if (username) {
  227. userObject.username = username;
  228. }
  229. const userData = getDataToSyncUserData(ldapUser, {});
  230. if (userData && userData.emails && userData.emails[0] && userData.emails[0].address) {
  231. if (Array.isArray(userData.emails[0].address)) {
  232. userObject.email = userData.emails[0].address[0];
  233. } else {
  234. userObject.email = userData.emails[0].address;
  235. }
  236. } else if (ldapUser.mail && ldapUser.mail.indexOf('@') > -1) {
  237. userObject.email = ldapUser.mail;
  238. } else if (LDAP.settings_get('LDAP_DEFAULT_DOMAIN') !== '') {
  239. userObject.email = `${ username || uniqueId.value }@${ LDAP.settings_get('LDAP_DEFAULT_DOMAIN') }`;
  240. } else {
  241. const error = new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, there is no email to create an account. Have you tried setting your Default Domain in LDAP Settings?');
  242. log_error(error);
  243. throw error;
  244. }
  245. log_debug('New user data', userObject);
  246. if (password) {
  247. userObject.password = password;
  248. }
  249. try {
  250. // This creates the account with password service
  251. userObject.ldap = true;
  252. userObject._id = Accounts.createUser(userObject);
  253. // Add the services.ldap identifiers
  254. Meteor.users.update({ _id: userObject._id }, {
  255. $set: {
  256. 'services.ldap': { id: uniqueId.value },
  257. 'emails.0.verified': true,
  258. 'authenticationMethod': 'ldap',
  259. }});
  260. } catch (error) {
  261. log_error('Error creating user', error);
  262. return error;
  263. }
  264. syncUserData(userObject, ldapUser);
  265. return {
  266. userId: userObject._id,
  267. };
  268. }
  269. export function importNewUsers(ldap) {
  270. if (LDAP.settings_get('LDAP_ENABLE') !== true) {
  271. log_error('Can\'t run LDAP Import, LDAP is disabled');
  272. return;
  273. }
  274. if (!ldap) {
  275. ldap = new LDAP();
  276. ldap.connectSync();
  277. }
  278. let count = 0;
  279. ldap.searchUsersSync('*', Meteor.bindEnvironment((error, ldapUsers, {next, end} = {}) => {
  280. if (error) {
  281. throw error;
  282. }
  283. ldapUsers.forEach((ldapUser) => {
  284. count++;
  285. const uniqueId = getLdapUserUniqueID(ldapUser);
  286. // Look to see if user already exists
  287. const userQuery = {
  288. 'services.ldap.id': uniqueId.value,
  289. };
  290. log_debug('userQuery', userQuery);
  291. let username;
  292. if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') {
  293. username = slug(getLdapUsername(ldapUser));
  294. }
  295. // Add user if it was not added before
  296. let user = Meteor.users.findOne(userQuery);
  297. if (!user && username && LDAP.settings_get('LDAP_MERGE_EXISTING_USERS') === true) {
  298. const userQuery = {
  299. username,
  300. };
  301. log_debug('userQuery merge', userQuery);
  302. user = Meteor.users.findOne(userQuery);
  303. if (user) {
  304. syncUserData(user, ldapUser);
  305. }
  306. }
  307. if (!user) {
  308. addLdapUser(ldapUser, username);
  309. }
  310. if (count % 100 === 0) {
  311. log_info('Import running. Users imported until now:', count);
  312. }
  313. });
  314. if (end) {
  315. log_info('Import finished. Users imported:', count);
  316. }
  317. next(count);
  318. }));
  319. }
  320. function sync() {
  321. if (LDAP.settings_get('LDAP_ENABLE') !== true) {
  322. return;
  323. }
  324. const ldap = new LDAP();
  325. try {
  326. ldap.connectSync();
  327. let users;
  328. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) {
  329. users = Meteor.users.find({ 'services.ldap': { $exists: true }});
  330. }
  331. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS') === true) {
  332. importNewUsers(ldap);
  333. }
  334. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) {
  335. users.forEach(function(user) {
  336. let ldapUser;
  337. if (user.services && user.services.ldap && user.services.ldap.id) {
  338. ldapUser = ldap.getUserByIdSync(user.services.ldap.id, user.services.ldap.idAttribute);
  339. } else {
  340. ldapUser = ldap.getUserByUsernameSync(user.username);
  341. }
  342. if (ldapUser) {
  343. syncUserData(user, ldapUser);
  344. } else {
  345. log_info('Can\'t sync user', user.username);
  346. }
  347. });
  348. }
  349. } catch (error) {
  350. log_error(error);
  351. return error;
  352. }
  353. return true;
  354. }
  355. const jobName = 'LDAP_Sync';
  356. const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounced() {
  357. let sc=SyncedCron.SyncedCron; //Why ?? something must be wrong in the import
  358. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC') !== true) {
  359. log_info('Disabling LDAP Background Sync');
  360. if (sc.nextScheduledAtDate(jobName)) {
  361. sc.remove(jobName);
  362. }
  363. return;
  364. }
  365. log_info('Enabling LDAP Background Sync');
  366. sc.add({
  367. name: jobName,
  368. schedule: function(parser) {
  369. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL')) {
  370. return parser.text(LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL'));
  371. }
  372. else {
  373. return parser.recur().on(0).minute();
  374. }},
  375. job: function() {
  376. sync();
  377. },
  378. });
  379. sc.start();
  380. }), 500);
  381. Meteor.startup(() => {
  382. Meteor.defer(() => {
  383. if(LDAP.settings_get('LDAP_BACKGROUND_SYNC')){addCronJob();}
  384. });
  385. });