cas_server.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. "use strict";
  2. const Fiber = Npm.require('fibers');
  3. const https = Npm.require('https');
  4. const url = Npm.require('url');
  5. const xmlParser = Npm.require('xml2js');
  6. // Library
  7. class CAS {
  8. constructor(options) {
  9. options = options || {};
  10. if (!options.validate_url) {
  11. throw new Error('Required CAS option `validateUrl` missing.');
  12. }
  13. if (!options.service) {
  14. throw new Error('Required CAS option `service` missing.');
  15. }
  16. const cas_url = url.parse(options.validate_url);
  17. if (cas_url.protocol != 'https:' ) {
  18. throw new Error('Only https CAS servers are supported.');
  19. } else if (!cas_url.hostname) {
  20. throw new Error('Option `validateUrl` must be a valid url like: https://example.com/cas/serviceValidate');
  21. } else {
  22. this.hostname = cas_url.host;
  23. this.port = 443;// Should be 443 for https
  24. this.validate_path = cas_url.pathname;
  25. }
  26. this.service = options.service;
  27. }
  28. validate(ticket, callback) {
  29. const httparams = {
  30. host: this.hostname,
  31. port: this.port,
  32. path: url.format({
  33. pathname: this.validate_path,
  34. query: {ticket: ticket, service: this.service},
  35. }),
  36. };
  37. https.get(httparams, (res) => {
  38. res.on('error', (e) => {
  39. console.log('error' + e);
  40. callback(e);
  41. });
  42. // Read result
  43. res.setEncoding('utf8');
  44. let response = '';
  45. res.on('data', (chunk) => {
  46. response += chunk;
  47. });
  48. res.on('end', (error) => {
  49. if (error) {
  50. console.log('error callback');
  51. console.log(error);
  52. callback(undefined, false);
  53. } else {
  54. xmlParser.parseString(response, (err, result) => {
  55. if (err) {
  56. console.log('Bad response format.');
  57. callback({message: 'Bad response format. XML could not parse it'});
  58. } else {
  59. if (result['cas:serviceResponse'] == null) {
  60. console.log('Empty response.');
  61. callback({message: 'Empty response.'});
  62. }
  63. if (result['cas:serviceResponse']['cas:authenticationSuccess']) {
  64. const userData = {
  65. id: result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:user'][0].toLowerCase(),
  66. };
  67. const attributes = result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:attributes'][0];
  68. // Check allowed ldap groups if exist (array only)
  69. // example cas settings : "allowedLdapGroups" : ["wekan", "admin"],
  70. let findedGroup = false;
  71. const allowedLdapGroups = Meteor.settings.cas.allowedLdapGroups || false;
  72. for (const fieldName in attributes) {
  73. if (allowedLdapGroups && fieldName === 'cas:memberOf') {
  74. for (const groups in attributes[fieldName]) {
  75. const str = attributes[fieldName][groups];
  76. if (!Array.isArray(allowedLdapGroups)) {
  77. callback({message: 'Settings "allowedLdapGroups" must be an array'});
  78. }
  79. for (const allowedLdapGroup in allowedLdapGroups) {
  80. if (str.search(`cn=${allowedLdapGroups[allowedLdapGroup]}`) >= 0) {
  81. findedGroup = true;
  82. }
  83. }
  84. }
  85. }
  86. userData[fieldName] = attributes[fieldName][0];
  87. }
  88. if (allowedLdapGroups && !findedGroup) {
  89. callback({message: 'Group not finded.'}, false);
  90. } else {
  91. callback(undefined, true, userData);
  92. }
  93. } else {
  94. callback(undefined, false);
  95. }
  96. }
  97. });
  98. }
  99. });
  100. });
  101. }
  102. }
  103. ////// END OF CAS MODULE
  104. let _casCredentialTokens = {};
  105. let _userData = {};
  106. //RoutePolicy.declare('/_cas/', 'network');
  107. // Listen to incoming OAuth http requests
  108. WebApp.connectHandlers.use((req, res, next) => {
  109. // Need to create a Fiber since we're using synchronous http calls and nothing
  110. // else is wrapping this in a fiber automatically
  111. Fiber(() => {
  112. middleware(req, res, next);
  113. }).run();
  114. });
  115. const middleware = (req, res, next) => {
  116. // Make sure to catch any exceptions because otherwise we'd crash
  117. // the runner
  118. try {
  119. urlParsed = url.parse(req.url, true);
  120. // Getting the ticket (if it's defined in GET-params)
  121. // If no ticket, then request will continue down the default
  122. // middlewares.
  123. const query = urlParsed.query;
  124. if (query == null) {
  125. next();
  126. return;
  127. }
  128. const ticket = query.ticket;
  129. if (ticket == null) {
  130. next();
  131. return;
  132. }
  133. const serviceUrl = Meteor.absoluteUrl(urlParsed.href.replace(/^\//g, '')).replace(/([&?])ticket=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, '');
  134. const redirectUrl = serviceUrl;//.replace(/([&?])casToken=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, '');
  135. // get auth token
  136. const credentialToken = query.casToken;
  137. if (!credentialToken) {
  138. end(res, redirectUrl);
  139. return;
  140. }
  141. // validate ticket
  142. casValidate(req, ticket, credentialToken, serviceUrl, () => {
  143. end(res, redirectUrl);
  144. });
  145. } catch (err) {
  146. console.log("account-cas: unexpected error : " + err.message);
  147. end(res, redirectUrl);
  148. }
  149. };
  150. const casValidate = (req, ticket, token, service, callback) => {
  151. // get configuration
  152. if (!Meteor.settings.cas/* || !Meteor.settings.cas.validate*/) {
  153. throw new Error('accounts-cas: unable to get configuration.');
  154. }
  155. const cas = new CAS({
  156. validate_url: Meteor.settings.cas.validateUrl,
  157. service: service,
  158. version: Meteor.settings.cas.casVersion
  159. });
  160. cas.validate(ticket, (err, status, userData) => {
  161. if (err) {
  162. console.log("accounts-cas: error when trying to validate " + err);
  163. console.log(err);
  164. } else {
  165. if (status) {
  166. console.log(`accounts-cas: user validated ${userData.id}
  167. (${JSON.stringify(userData)})`);
  168. _casCredentialTokens[token] = { id: userData.id };
  169. _userData = userData;
  170. } else {
  171. console.log("accounts-cas: unable to validate " + ticket);
  172. }
  173. }
  174. callback();
  175. });
  176. return;
  177. };
  178. /*
  179. * Register a server-side login handle.
  180. * It is call after Accounts.callLoginMethod() is call from client.
  181. */
  182. Accounts.registerLoginHandler((options) => {
  183. if (!options.cas)
  184. return undefined;
  185. if (!_hasCredential(options.cas.credentialToken)) {
  186. throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
  187. 'no matching login attempt found');
  188. }
  189. const result = _retrieveCredential(options.cas.credentialToken);
  190. const attrs = Meteor.settings.cas.attributes || {};
  191. // CAS keys
  192. const fn = attrs.firstname || 'cas:givenName';
  193. const ln = attrs.lastname || 'cas:sn';
  194. const full = attrs.fullname;
  195. const mail = attrs.mail || 'cas:mail'; // or 'email'
  196. const uid = attrs.id || 'id';
  197. if (attrs.debug) {
  198. if (full) {
  199. console.log(`CAS fields : id:"${uid}", fullname:"${full}", mail:"${mail}"`);
  200. } else {
  201. console.log(`CAS fields : id:"${uid}", firstname:"${fn}", lastname:"${ln}", mail:"${mail}"`);
  202. }
  203. }
  204. const name = full ? _userData[full] : _userData[fn] + ' ' + _userData[ln];
  205. // https://docs.meteor.com/api/accounts.html#Meteor-users
  206. options = {
  207. // _id: Meteor.userId()
  208. username: _userData[uid], // Unique name
  209. emails: [
  210. { address: _userData[mail], verified: true }
  211. ],
  212. createdAt: new Date(),
  213. profile: {
  214. // The profile is writable by the user by default.
  215. name: name,
  216. fullname : name,
  217. email : _userData[mail]
  218. },
  219. active: true,
  220. globalRoles: ['user']
  221. };
  222. if (attrs.debug) {
  223. console.log(`CAS response : ${JSON.stringify(result)}`);
  224. }
  225. let user = Meteor.users.findOne({ 'username': options.username });
  226. if (! user) {
  227. if (attrs.debug) {
  228. console.log(`Creating user account ${JSON.stringify(options)}`);
  229. }
  230. const userId = Accounts.insertUserDoc({}, options);
  231. user = Meteor.users.findOne(userId);
  232. }
  233. if (attrs.debug) {
  234. console.log(`Using user account ${JSON.stringify(user)}`);
  235. }
  236. return { userId: user._id };
  237. });
  238. const _hasCredential = (credentialToken) => {
  239. return _.has(_casCredentialTokens, credentialToken);
  240. }
  241. /*
  242. * Retrieve token and delete it to avoid replaying it.
  243. */
  244. const _retrieveCredential = (credentialToken) => {
  245. const result = _casCredentialTokens[credentialToken];
  246. delete _casCredentialTokens[credentialToken];
  247. return result;
  248. }
  249. const closePopup = (res) => {
  250. if (Meteor.settings.cas && Meteor.settings.cas.popup == false) {
  251. return;
  252. }
  253. res.writeHead(200, {'Content-Type': 'text/html'});
  254. const content = '<html><body><div id="popupCanBeClosed"></div></body></html>';
  255. res.end(content, 'utf-8');
  256. }
  257. const redirect = (res, whereTo) => {
  258. res.writeHead(302, {'Location': whereTo});
  259. const content = '<html><head><meta http-equiv="refresh" content="0; url='+whereTo+'" /></head><body>Redirection to <a href='+whereTo+'>'+whereTo+'</a></body></html>';
  260. res.end(content, 'utf-8');
  261. return
  262. }
  263. const end = (res, whereTo) => {
  264. if (Meteor.settings.cas && Meteor.settings.cas.popup == false) {
  265. redirect(res, whereTo);
  266. } else {
  267. closePopup(res);
  268. }
  269. }