sync.js 13 KB

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