sync.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. }
  208. export function addLdapUser(ldapUser, username, password) {
  209. const uniqueId = getLdapUserUniqueID(ldapUser);
  210. const userObject = {
  211. };
  212. if (username) {
  213. userObject.username = username;
  214. }
  215. const userData = getDataToSyncUserData(ldapUser, {});
  216. if (userData && userData.emails && userData.emails[0] && userData.emails[0].address) {
  217. if (Array.isArray(userData.emails[0].address)) {
  218. userObject.email = userData.emails[0].address[0];
  219. } else {
  220. userObject.email = userData.emails[0].address;
  221. }
  222. } else if (ldapUser.mail && ldapUser.mail.indexOf('@') > -1) {
  223. userObject.email = ldapUser.mail;
  224. } else if (LDAP.settings_get('LDAP_DEFAULT_DOMAIN') !== '') {
  225. userObject.email = `${ username || uniqueId.value }@${ LDAP.settings_get('LDAP_DEFAULT_DOMAIN') }`;
  226. } else {
  227. 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?');
  228. log_error(error);
  229. throw error;
  230. }
  231. log_debug('New user data', userObject);
  232. if (password) {
  233. userObject.password = password;
  234. }
  235. try {
  236. // This creates the account with password service
  237. userObject.ldap = true;
  238. userObject._id = Accounts.createUser(userObject);
  239. // Add the services.ldap identifiers
  240. Meteor.users.update({ _id: userObject._id }, {
  241. $set: {
  242. 'services.ldap': { id: uniqueId.value },
  243. 'emails.0.verified': true,
  244. 'authenticationMethod': 'ldap',
  245. }});
  246. } catch (error) {
  247. log_error('Error creating user', error);
  248. return error;
  249. }
  250. syncUserData(userObject, ldapUser);
  251. return {
  252. userId: userObject._id,
  253. };
  254. }
  255. export function importNewUsers(ldap) {
  256. if (LDAP.settings_get('LDAP_ENABLE') !== true) {
  257. log_error('Can\'t run LDAP Import, LDAP is disabled');
  258. return;
  259. }
  260. if (!ldap) {
  261. ldap = new LDAP();
  262. ldap.connectSync();
  263. }
  264. let count = 0;
  265. ldap.searchUsersSync('*', Meteor.bindEnvironment((error, ldapUsers, {next, end} = {}) => {
  266. if (error) {
  267. throw error;
  268. }
  269. ldapUsers.forEach((ldapUser) => {
  270. count++;
  271. const uniqueId = getLdapUserUniqueID(ldapUser);
  272. // Look to see if user already exists
  273. const userQuery = {
  274. 'services.ldap.id': uniqueId.value,
  275. };
  276. log_debug('userQuery', userQuery);
  277. let username;
  278. if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') {
  279. username = slug(getLdapUsername(ldapUser));
  280. }
  281. // Add user if it was not added before
  282. let user = Meteor.users.findOne(userQuery);
  283. if (!user && username && LDAP.settings_get('LDAP_MERGE_EXISTING_USERS') === true) {
  284. const userQuery = {
  285. username,
  286. };
  287. log_debug('userQuery merge', userQuery);
  288. user = Meteor.users.findOne(userQuery);
  289. if (user) {
  290. syncUserData(user, ldapUser);
  291. }
  292. }
  293. if (!user) {
  294. addLdapUser(ldapUser, username);
  295. }
  296. if (count % 100 === 0) {
  297. log_info('Import running. Users imported until now:', count);
  298. }
  299. });
  300. if (end) {
  301. log_info('Import finished. Users imported:', count);
  302. }
  303. next(count);
  304. }));
  305. }
  306. function sync() {
  307. if (LDAP.settings_get('LDAP_ENABLE') !== true) {
  308. return;
  309. }
  310. const ldap = new LDAP();
  311. try {
  312. ldap.connectSync();
  313. let users;
  314. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) {
  315. users = Meteor.users.find({ 'services.ldap': { $exists: true }});
  316. }
  317. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS') === true) {
  318. importNewUsers(ldap);
  319. }
  320. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) {
  321. users.forEach(function(user) {
  322. let ldapUser;
  323. if (user.services && user.services.ldap && user.services.ldap.id) {
  324. ldapUser = ldap.getUserByIdSync(user.services.ldap.id, user.services.ldap.idAttribute);
  325. } else {
  326. ldapUser = ldap.getUserByUsernameSync(user.username);
  327. }
  328. if (ldapUser) {
  329. syncUserData(user, ldapUser);
  330. } else {
  331. log_info('Can\'t sync user', user.username);
  332. }
  333. });
  334. }
  335. } catch (error) {
  336. log_error(error);
  337. return error;
  338. }
  339. return true;
  340. }
  341. const jobName = 'LDAP_Sync';
  342. const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounced() {
  343. let sc=SyncedCron.SyncedCron; //Why ?? something must be wrong in the import
  344. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC') !== true) {
  345. log_info('Disabling LDAP Background Sync');
  346. if (sc.nextScheduledAtDate(jobName)) {
  347. sc.remove(jobName);
  348. }
  349. return;
  350. }
  351. log_info('Enabling LDAP Background Sync');
  352. sc.add({
  353. name: jobName,
  354. schedule: function(parser) {
  355. if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL')) {
  356. return parser.text(LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL'));
  357. }
  358. else {
  359. return parser.recur().on(0).minute();
  360. }},
  361. job: function() {
  362. sync();
  363. },
  364. });
  365. sc.start();
  366. }), 500);
  367. Meteor.startup(() => {
  368. Meteor.defer(() => {
  369. if(LDAP.settings_get('LDAP_BACKGROUND_SYNC')){addCronJob();}
  370. });
  371. });