cas_server.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. var 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. for (var fieldName in attributes) {
  69. userData[fieldName] = attributes[fieldName][0];
  70. };
  71. callback(undefined, true, userData);
  72. } else {
  73. callback(undefined, false);
  74. }
  75. }
  76. });
  77. }
  78. });
  79. });
  80. }
  81. }
  82. ////// END OF CAS MODULE
  83. let _casCredentialTokens = {};
  84. let _userData = {};
  85. //RoutePolicy.declare('/_cas/', 'network');
  86. // Listen to incoming OAuth http requests
  87. WebApp.connectHandlers.use((req, res, next) => {
  88. // Need to create a Fiber since we're using synchronous http calls and nothing
  89. // else is wrapping this in a fiber automatically
  90. Fiber(() => {
  91. middleware(req, res, next);
  92. }).run();
  93. });
  94. const middleware = (req, res, next) => {
  95. // Make sure to catch any exceptions because otherwise we'd crash
  96. // the runner
  97. try {
  98. urlParsed = url.parse(req.url, true);
  99. // Getting the ticket (if it's defined in GET-params)
  100. // If no ticket, then request will continue down the default
  101. // middlewares.
  102. const query = urlParsed.query;
  103. if (query == null) {
  104. next();
  105. return;
  106. }
  107. const ticket = query.ticket;
  108. if (ticket == null) {
  109. next();
  110. return;
  111. }
  112. const serviceUrl = Meteor.absoluteUrl(urlParsed.href.replace(/^\//g, '')).replace(/([&?])ticket=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, '');
  113. const redirectUrl = serviceUrl;//.replace(/([&?])casToken=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, '');
  114. // get auth token
  115. const credentialToken = query.casToken;
  116. if (!credentialToken) {
  117. end(res, redirectUrl);
  118. return;
  119. }
  120. // validate ticket
  121. casValidate(req, ticket, credentialToken, serviceUrl, () => {
  122. end(res, redirectUrl);
  123. });
  124. } catch (err) {
  125. console.log("account-cas: unexpected error : " + err.message);
  126. end(res, redirectUrl);
  127. }
  128. };
  129. const casValidate = (req, ticket, token, service, callback) => {
  130. // get configuration
  131. if (!Meteor.settings.cas/* || !Meteor.settings.cas.validate*/) {
  132. throw new Error('accounts-cas: unable to get configuration.');
  133. }
  134. const cas = new CAS({
  135. validate_url: Meteor.settings.cas.validateUrl,
  136. service: service,
  137. version: Meteor.settings.cas.casVersion
  138. });
  139. cas.validate(ticket, (err, status, userData) => {
  140. if (err) {
  141. console.log("accounts-cas: error when trying to validate " + err);
  142. console.log(err);
  143. } else {
  144. if (status) {
  145. console.log(`accounts-cas: user validated ${userData.id}
  146. (${JSON.stringify(userData)})`);
  147. _casCredentialTokens[token] = { id: userData.id };
  148. _userData = userData;
  149. } else {
  150. console.log("accounts-cas: unable to validate " + ticket);
  151. }
  152. }
  153. callback();
  154. });
  155. return;
  156. };
  157. /*
  158. * Register a server-side login handle.
  159. * It is call after Accounts.callLoginMethod() is call from client.
  160. */
  161. Accounts.registerLoginHandler((options) => {
  162. if (!options.cas)
  163. return undefined;
  164. if (!_hasCredential(options.cas.credentialToken)) {
  165. throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
  166. 'no matching login attempt found');
  167. }
  168. const result = _retrieveCredential(options.cas.credentialToken);
  169. const attrs = Meteor.settings.cas.attributes || {};
  170. // CAS keys
  171. const fn = attrs.firstname || 'cas:givenName';
  172. const ln = attrs.lastname || 'cas:sn';
  173. const full = attrs.fullname;
  174. const mail = attrs.mail || 'cas:mail'; // or 'email'
  175. const uid = attrs.id || 'id';
  176. if (attrs.debug) {
  177. if (full) {
  178. console.log(`CAS fields : id:"${uid}", fullname:"${full}", mail:"${mail}"`);
  179. } else {
  180. console.log(`CAS fields : id:"${uid}", firstname:"${fn}", lastname:"${ln}", mail:"${mail}"`);
  181. }
  182. }
  183. const name = full ? _userData[full] : _userData[fn] + ' ' + _userData[ln];
  184. // https://docs.meteor.com/api/accounts.html#Meteor-users
  185. options = {
  186. // _id: Meteor.userId()
  187. username: _userData[uid], // Unique name
  188. emails: [
  189. { address: _userData[mail], verified: true }
  190. ],
  191. createdAt: new Date(),
  192. profile: {
  193. // The profile is writable by the user by default.
  194. name: name,
  195. fullname : name,
  196. email : _userData[mail]
  197. },
  198. active: true,
  199. globalRoles: ['user']
  200. };
  201. if (attrs.debug) {
  202. console.log(`CAS response : ${JSON.stringify(result)}`);
  203. }
  204. let user = Meteor.users.findOne({ 'username': options.username });
  205. if (! user) {
  206. if (attrs.debug) {
  207. console.log(`Creating user account ${JSON.stringify(options)}`);
  208. }
  209. const userId = Accounts.insertUserDoc({}, options);
  210. user = Meteor.users.findOne(userId);
  211. }
  212. if (attrs.debug) {
  213. console.log(`Using user account ${JSON.stringify(user)}`);
  214. }
  215. return { userId: user._id };
  216. });
  217. const _hasCredential = (credentialToken) => {
  218. return _.has(_casCredentialTokens, credentialToken);
  219. }
  220. /*
  221. * Retrieve token and delete it to avoid replaying it.
  222. */
  223. const _retrieveCredential = (credentialToken) => {
  224. const result = _casCredentialTokens[credentialToken];
  225. delete _casCredentialTokens[credentialToken];
  226. return result;
  227. }
  228. const closePopup = (res) => {
  229. if (Meteor.settings.cas && Meteor.settings.cas.popup == false) {
  230. return;
  231. }
  232. res.writeHead(200, {'Content-Type': 'text/html'});
  233. const content = '<html><body><div id="popupCanBeClosed"></div></body></html>';
  234. res.end(content, 'utf-8');
  235. }
  236. const redirect = (res, whereTo) => {
  237. res.writeHead(302, {'Location': whereTo});
  238. const content = '<html><head><meta http-equiv="refresh" content="0; url='+whereTo+'" /></head><body>Redirection to <a href='+whereTo+'>'+whereTo+'</a></body></html>';
  239. res.end(content, 'utf-8');
  240. return
  241. }
  242. const end = (res, whereTo) => {
  243. if (Meteor.settings.cas && Meteor.settings.cas.popup == false) {
  244. redirect(res, whereTo);
  245. } else {
  246. closePopup(res);
  247. }
  248. }