sync.js 13 KB

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