passport.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. const debug = require('debug')('growi:service:PassportService');
  2. const urljoin = require('url-join');
  3. const luceneQueryParser = require('lucene-query-parser');
  4. const passport = require('passport');
  5. const LocalStrategy = require('passport-local').Strategy;
  6. const LdapStrategy = require('passport-ldapauth');
  7. const GoogleStrategy = require('passport-google-oauth20').Strategy;
  8. const GitHubStrategy = require('passport-github').Strategy;
  9. const TwitterStrategy = require('passport-twitter').Strategy;
  10. const OidcStrategy = require('openid-client').Strategy;
  11. const SamlStrategy = require('passport-saml').Strategy;
  12. const OIDCIssuer = require('openid-client').Issuer;
  13. const BasicStrategy = require('passport-http').BasicStrategy;
  14. /**
  15. * the service class of Passport
  16. */
  17. class PassportService {
  18. // see '/lib/form/login.js'
  19. static get USERNAME_FIELD() { return 'loginForm[username]' }
  20. static get PASSWORD_FIELD() { return 'loginForm[password]' }
  21. constructor(crowi) {
  22. this.crowi = crowi;
  23. /**
  24. * the flag whether LocalStrategy is set up successfully
  25. */
  26. this.isLocalStrategySetup = false;
  27. /**
  28. * the flag whether LdapStrategy is set up successfully
  29. */
  30. this.isLdapStrategySetup = false;
  31. /**
  32. * the flag whether GoogleStrategy is set up successfully
  33. */
  34. this.isGoogleStrategySetup = false;
  35. /**
  36. * the flag whether GitHubStrategy is set up successfully
  37. */
  38. this.isGitHubStrategySetup = false;
  39. /**
  40. * the flag whether TwitterStrategy is set up successfully
  41. */
  42. this.isTwitterStrategySetup = false;
  43. /**
  44. * the flag whether OidcStrategy is set up successfully
  45. */
  46. this.isOidcStrategySetup = false;
  47. /**
  48. * the flag whether SamlStrategy is set up successfully
  49. */
  50. this.isSamlStrategySetup = false;
  51. /**
  52. * the flag whether BasicStrategy is set up successfully
  53. */
  54. this.isBasicStrategySetup = false;
  55. /**
  56. * the flag whether serializer/deserializer are set up successfully
  57. */
  58. this.isSerializerSetup = false;
  59. /**
  60. * the keys of mandatory configs for SAML
  61. */
  62. this.mandatoryConfigKeysForSaml = [
  63. 'security:passport-saml:entryPoint',
  64. 'security:passport-saml:issuer',
  65. 'security:passport-saml:cert',
  66. 'security:passport-saml:attrMapId',
  67. 'security:passport-saml:attrMapUsername',
  68. 'security:passport-saml:attrMapMail',
  69. ];
  70. this.setupFunction = {
  71. local: {
  72. setup: 'setupLocalStrategy',
  73. reset: 'resetLocalStrategy',
  74. },
  75. ldap: {
  76. setup: 'setupLdapStrategy',
  77. reset: 'resetLdapStrategy',
  78. },
  79. saml: {
  80. setup: 'setupSamlStrategy',
  81. reset: 'resetSamlStrategy',
  82. },
  83. oidc: {
  84. setup: 'setupOidcStrategy',
  85. reset: 'resetOidcStrategy',
  86. },
  87. basic: {
  88. setup: 'setupBasicStrategy',
  89. reset: 'resetBasicStrategy',
  90. },
  91. google: {
  92. setup: 'setupGoogleStrategy',
  93. reset: 'resetGoogleStrategy',
  94. },
  95. github: {
  96. setup: 'setupGitHubStrategy',
  97. reset: 'resetGitHubStrategy',
  98. },
  99. twitter: {
  100. setup: 'setupTwitterStrategy',
  101. reset: 'resetTwitterStrategy',
  102. },
  103. };
  104. }
  105. /**
  106. * get SetupStrategies
  107. *
  108. * @return {Array}
  109. * @memberof PassportService
  110. */
  111. getSetupStrategies() {
  112. const setupStrategies = [];
  113. if (this.isLocalStrategySetup) { setupStrategies.push('local') }
  114. if (this.isLdapStrategySetup) { setupStrategies.push('ldap') }
  115. if (this.isSamlStrategySetup) { setupStrategies.push('saml') }
  116. if (this.isOidcStrategySetup) { setupStrategies.push('oidc') }
  117. if (this.isBasicStrategySetup) { setupStrategies.push('basic') }
  118. if (this.isGoogleStrategySetup) { setupStrategies.push('google') }
  119. if (this.isGitHubStrategySetup) { setupStrategies.push('github') }
  120. if (this.isTwitterStrategySetup) { setupStrategies.push('twitter') }
  121. return setupStrategies;
  122. }
  123. /**
  124. * get SetupFunction
  125. *
  126. * @return {Object}
  127. * @param {string} authId
  128. */
  129. getSetupFunction(authId) {
  130. return this.setupFunction[authId];
  131. }
  132. /**
  133. * setup strategy by target name
  134. */
  135. setupStrategyById(authId) {
  136. const func = this.getSetupFunction(authId);
  137. try {
  138. this[func.setup]();
  139. }
  140. catch (err) {
  141. debug(err);
  142. this[func.reset]();
  143. }
  144. }
  145. /**
  146. * reset LocalStrategy
  147. *
  148. * @memberof PassportService
  149. */
  150. resetLocalStrategy() {
  151. debug('LocalStrategy: reset');
  152. passport.unuse('local');
  153. this.isLocalStrategySetup = false;
  154. }
  155. /**
  156. * setup LocalStrategy
  157. *
  158. * @memberof PassportService
  159. */
  160. setupLocalStrategy() {
  161. this.resetLocalStrategy();
  162. const { configManager } = this.crowi;
  163. const isEnabled = configManager.getConfig('crowi', 'security:passport-local:isEnabled');
  164. // when disabled
  165. if (!isEnabled) {
  166. return;
  167. }
  168. debug('LocalStrategy: setting up..');
  169. const User = this.crowi.model('User');
  170. passport.use(new LocalStrategy(
  171. {
  172. usernameField: PassportService.USERNAME_FIELD,
  173. passwordField: PassportService.PASSWORD_FIELD,
  174. },
  175. (username, password, done) => {
  176. // find user
  177. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  178. if (err) { return done(err) }
  179. // check existence and password
  180. if (!user || !user.isPasswordValid(password)) {
  181. return done(null, false, { message: 'Incorrect credentials.' });
  182. }
  183. return done(null, user);
  184. });
  185. },
  186. ));
  187. this.isLocalStrategySetup = true;
  188. debug('LocalStrategy: setup is done');
  189. }
  190. /**
  191. * reset LdapStrategy
  192. *
  193. * @memberof PassportService
  194. */
  195. resetLdapStrategy() {
  196. debug('LdapStrategy: reset');
  197. passport.unuse('ldapauth');
  198. this.isLdapStrategySetup = false;
  199. }
  200. /**
  201. * Asynchronous configuration retrieval
  202. *
  203. * @memberof PassportService
  204. */
  205. setupLdapStrategy() {
  206. this.resetLdapStrategy();
  207. const config = this.crowi.config;
  208. const { configManager } = this.crowi;
  209. const isLdapEnabled = configManager.getConfig('crowi', 'security:passport-ldap:isEnabled');
  210. // when disabled
  211. if (!isLdapEnabled) {
  212. return;
  213. }
  214. debug('LdapStrategy: setting up..');
  215. passport.use(new LdapStrategy(this.getLdapConfigurationFunc(config, { passReqToCallback: true }),
  216. (req, ldapAccountInfo, done) => {
  217. debug('LDAP authentication has succeeded', ldapAccountInfo);
  218. // store ldapAccountInfo to req
  219. req.ldapAccountInfo = ldapAccountInfo;
  220. done(null, ldapAccountInfo);
  221. }));
  222. this.isLdapStrategySetup = true;
  223. debug('LdapStrategy: setup is done');
  224. }
  225. /**
  226. * return attribute name for mapping to username of Crowi DB
  227. *
  228. * @returns
  229. * @memberof PassportService
  230. */
  231. getLdapAttrNameMappedToUsername() {
  232. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapUsername') || 'uid';
  233. }
  234. /**
  235. * return attribute name for mapping to name of Crowi DB
  236. *
  237. * @returns
  238. * @memberof PassportService
  239. */
  240. getLdapAttrNameMappedToName() {
  241. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapName') || '';
  242. }
  243. /**
  244. * return attribute name for mapping to name of Crowi DB
  245. *
  246. * @returns
  247. * @memberof PassportService
  248. */
  249. getLdapAttrNameMappedToMail() {
  250. return this.crowi.configManager.getConfig('crowi', 'security:passport-ldap:attrMapMail') || 'mail';
  251. }
  252. /**
  253. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  254. *
  255. * @param {any} req
  256. * @returns
  257. * @memberof PassportService
  258. */
  259. getLdapAccountIdFromReq(req) {
  260. return req.body.loginForm.username;
  261. }
  262. /**
  263. * Asynchronous configuration retrieval
  264. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  265. *
  266. * @param {object} config
  267. * @param {object} opts
  268. * @returns
  269. * @memberof PassportService
  270. */
  271. getLdapConfigurationFunc(config, opts) {
  272. /* eslint-disable no-multi-spaces */
  273. const { configManager } = this.crowi;
  274. // get configurations
  275. const isUserBind = configManager.getConfig('crowi', 'security:passport-ldap:isUserBind');
  276. const serverUrl = configManager.getConfig('crowi', 'security:passport-ldap:serverUrl');
  277. const bindDN = configManager.getConfig('crowi', 'security:passport-ldap:bindDN');
  278. const bindCredentials = configManager.getConfig('crowi', 'security:passport-ldap:bindDNPassword');
  279. const searchFilter = configManager.getConfig('crowi', 'security:passport-ldap:searchFilter') || '(uid={{username}})';
  280. const groupSearchBase = configManager.getConfig('crowi', 'security:passport-ldap:groupSearchBase');
  281. const groupSearchFilter = configManager.getConfig('crowi', 'security:passport-ldap:groupSearchFilter');
  282. const groupDnProperty = configManager.getConfig('crowi', 'security:passport-ldap:groupDnProperty') || 'uid';
  283. /* eslint-enable no-multi-spaces */
  284. // parse serverUrl
  285. // see: https://regex101.com/r/0tuYBB/1
  286. const match = serverUrl.match(/(ldaps?:\/\/[^/]+)\/(.*)?/);
  287. if (match == null || match.length < 1) {
  288. debug('LdapStrategy: serverUrl is invalid');
  289. return (req, callback) => { callback({ message: 'serverUrl is invalid' }) };
  290. }
  291. const url = match[1];
  292. const searchBase = match[2] || '';
  293. debug(`LdapStrategy: url=${url}`);
  294. debug(`LdapStrategy: searchBase=${searchBase}`);
  295. debug(`LdapStrategy: isUserBind=${isUserBind}`);
  296. if (!isUserBind) {
  297. debug(`LdapStrategy: bindDN=${bindDN}`);
  298. debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  299. }
  300. debug(`LdapStrategy: searchFilter=${searchFilter}`);
  301. debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  302. debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  303. debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  304. return (req, callback) => {
  305. // get credentials from form data
  306. const loginForm = req.body.loginForm;
  307. if (!req.form.isValid) {
  308. return callback({ message: 'Incorrect credentials.' });
  309. }
  310. // user bind
  311. const fixedBindDN = (isUserBind)
  312. ? bindDN.replace(/{{username}}/, loginForm.username)
  313. : bindDN;
  314. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  315. let serverOpt = {
  316. url,
  317. bindDN: fixedBindDN,
  318. bindCredentials: fixedBindCredentials,
  319. searchBase,
  320. searchFilter,
  321. attrMapUsername: this.getLdapAttrNameMappedToUsername(),
  322. attrMapName: this.getLdapAttrNameMappedToName(),
  323. };
  324. if (groupSearchBase && groupSearchFilter) {
  325. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  326. }
  327. process.nextTick(() => {
  328. const mergedOpts = Object.assign({
  329. usernameField: PassportService.USERNAME_FIELD,
  330. passwordField: PassportService.PASSWORD_FIELD,
  331. server: serverOpt,
  332. }, opts);
  333. debug('ldap configuration: ', mergedOpts);
  334. // store configuration to req
  335. req.ldapConfiguration = mergedOpts;
  336. callback(null, mergedOpts);
  337. });
  338. };
  339. }
  340. /**
  341. * Asynchronous configuration retrieval
  342. *
  343. * @memberof PassportService
  344. */
  345. setupGoogleStrategy() {
  346. this.resetGoogleStrategy();
  347. const { configManager } = this.crowi;
  348. const isGoogleEnabled = configManager.getConfig('crowi', 'security:passport-google:isEnabled');
  349. // when disabled
  350. if (!isGoogleEnabled) {
  351. return;
  352. }
  353. debug('GoogleStrategy: setting up..');
  354. passport.use(
  355. new GoogleStrategy(
  356. {
  357. clientID: configManager.getConfig('crowi', 'security:passport-google:clientId'),
  358. clientSecret: configManager.getConfig('crowi', 'security:passport-google:clientSecret'),
  359. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  360. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/google/callback') // auto-generated with v3.2.4 and above
  361. : configManager.getConfig('crowi', 'security:passport-google:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  362. skipUserProfile: false,
  363. },
  364. (accessToken, refreshToken, profile, done) => {
  365. if (profile) {
  366. return done(null, profile);
  367. }
  368. return done(null, false);
  369. },
  370. ),
  371. );
  372. this.isGoogleStrategySetup = true;
  373. debug('GoogleStrategy: setup is done');
  374. }
  375. /**
  376. * reset GoogleStrategy
  377. *
  378. * @memberof PassportService
  379. */
  380. resetGoogleStrategy() {
  381. debug('GoogleStrategy: reset');
  382. passport.unuse('google');
  383. this.isGoogleStrategySetup = false;
  384. }
  385. setupGitHubStrategy() {
  386. this.resetGitHubStrategy();
  387. const { configManager } = this.crowi;
  388. const isGitHubEnabled = configManager.getConfig('crowi', 'security:passport-github:isEnabled');
  389. // when disabled
  390. if (!isGitHubEnabled) {
  391. return;
  392. }
  393. debug('GitHubStrategy: setting up..');
  394. passport.use(
  395. new GitHubStrategy(
  396. {
  397. clientID: configManager.getConfig('crowi', 'security:passport-github:clientId'),
  398. clientSecret: configManager.getConfig('crowi', 'security:passport-github:clientSecret'),
  399. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  400. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/github/callback') // auto-generated with v3.2.4 and above
  401. : configManager.getConfig('crowi', 'security:passport-github:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  402. skipUserProfile: false,
  403. },
  404. (accessToken, refreshToken, profile, done) => {
  405. if (profile) {
  406. return done(null, profile);
  407. }
  408. return done(null, false);
  409. },
  410. ),
  411. );
  412. this.isGitHubStrategySetup = true;
  413. debug('GitHubStrategy: setup is done');
  414. }
  415. /**
  416. * reset GitHubStrategy
  417. *
  418. * @memberof PassportService
  419. */
  420. resetGitHubStrategy() {
  421. debug('GitHubStrategy: reset');
  422. passport.unuse('github');
  423. this.isGitHubStrategySetup = false;
  424. }
  425. setupTwitterStrategy() {
  426. this.resetTwitterStrategy();
  427. const { configManager } = this.crowi;
  428. const isTwitterEnabled = configManager.getConfig('crowi', 'security:passport-twitter:isEnabled');
  429. // when disabled
  430. if (!isTwitterEnabled) {
  431. return;
  432. }
  433. debug('TwitterStrategy: setting up..');
  434. passport.use(
  435. new TwitterStrategy(
  436. {
  437. consumerKey: configManager.getConfig('crowi', 'security:passport-twitter:consumerKey'),
  438. consumerSecret: configManager.getConfig('crowi', 'security:passport-twitter:consumerSecret'),
  439. callbackURL: (this.crowi.appService.getSiteUrl() != null)
  440. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/twitter/callback') // auto-generated with v3.2.4 and above
  441. : configManager.getConfig('crowi', 'security:passport-twitter:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  442. skipUserProfile: false,
  443. },
  444. (accessToken, refreshToken, profile, done) => {
  445. if (profile) {
  446. return done(null, profile);
  447. }
  448. return done(null, false);
  449. },
  450. ),
  451. );
  452. this.isTwitterStrategySetup = true;
  453. debug('TwitterStrategy: setup is done');
  454. }
  455. /**
  456. * reset TwitterStrategy
  457. *
  458. * @memberof PassportService
  459. */
  460. resetTwitterStrategy() {
  461. debug('TwitterStrategy: reset');
  462. passport.unuse('twitter');
  463. this.isTwitterStrategySetup = false;
  464. }
  465. async setupOidcStrategy() {
  466. this.resetOidcStrategy();
  467. const { configManager } = this.crowi;
  468. const isOidcEnabled = configManager.getConfig('crowi', 'security:passport-oidc:isEnabled');
  469. // when disabled
  470. if (!isOidcEnabled) {
  471. return;
  472. }
  473. debug('OidcStrategy: setting up..');
  474. // setup client
  475. // extend oidc request timeouts
  476. OIDCIssuer.defaultHttpOptions = { timeout: 5000 };
  477. const issuerHost = configManager.getConfig('crowi', 'security:passport-oidc:issuerHost');
  478. const clientId = configManager.getConfig('crowi', 'security:passport-oidc:clientId');
  479. const clientSecret = configManager.getConfig('crowi', 'security:passport-oidc:clientSecret');
  480. const redirectUri = (configManager.getConfig('crowi', 'app:siteUrl') != null)
  481. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/oidc/callback')
  482. : configManager.getConfig('crowi', 'security:passport-oidc:callbackUrl'); // DEPRECATED: backward compatible with v3.2.3 and below
  483. const oidcIssuer = await OIDCIssuer.discover(issuerHost);
  484. debug('Discovered issuer %s %O', oidcIssuer.issuer, oidcIssuer.metadata);
  485. const client = new oidcIssuer.Client({
  486. client_id: clientId,
  487. client_secret: clientSecret,
  488. redirect_uris: [redirectUri],
  489. response_types: ['code'],
  490. });
  491. passport.use('oidc', new OidcStrategy({
  492. client,
  493. params: { scope: 'openid email profile' },
  494. },
  495. ((tokenset, userinfo, done) => {
  496. if (userinfo) {
  497. return done(null, userinfo);
  498. }
  499. return done(null, false);
  500. })));
  501. this.isOidcStrategySetup = true;
  502. debug('OidcStrategy: setup is done');
  503. }
  504. /**
  505. * reset OidcStrategy
  506. *
  507. * @memberof PassportService
  508. */
  509. resetOidcStrategy() {
  510. debug('OidcStrategy: reset');
  511. passport.unuse('oidc');
  512. this.isOidcStrategySetup = false;
  513. }
  514. setupSamlStrategy() {
  515. this.resetSamlStrategy();
  516. const { configManager } = this.crowi;
  517. const isSamlEnabled = configManager.getConfig('crowi', 'security:passport-saml:isEnabled');
  518. // when disabled
  519. if (!isSamlEnabled) {
  520. return;
  521. }
  522. debug('SamlStrategy: setting up..');
  523. passport.use(
  524. new SamlStrategy(
  525. {
  526. entryPoint: configManager.getConfig('crowi', 'security:passport-saml:entryPoint'),
  527. callbackUrl: (this.crowi.appService.getSiteUrl() != null)
  528. ? urljoin(this.crowi.appService.getSiteUrl(), '/passport/saml/callback') // auto-generated with v3.2.4 and above
  529. : configManager.getConfig('crowi', 'security:passport-saml:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  530. issuer: configManager.getConfig('crowi', 'security:passport-saml:issuer'),
  531. cert: configManager.getConfig('crowi', 'security:passport-saml:cert'),
  532. },
  533. (profile, done) => {
  534. if (profile) {
  535. return done(null, profile);
  536. }
  537. return done(null, false);
  538. },
  539. ),
  540. );
  541. this.isSamlStrategySetup = true;
  542. debug('SamlStrategy: setup is done');
  543. }
  544. /**
  545. * reset SamlStrategy
  546. *
  547. * @memberof PassportService
  548. */
  549. resetSamlStrategy() {
  550. debug('SamlStrategy: reset');
  551. passport.unuse('saml');
  552. this.isSamlStrategySetup = false;
  553. }
  554. /**
  555. * return the keys of the configs mandatory for SAML whose value are empty.
  556. */
  557. getSamlMissingMandatoryConfigKeys() {
  558. const missingRequireds = [];
  559. for (const key of this.mandatoryConfigKeysForSaml) {
  560. if (this.crowi.configManager.getConfig('crowi', key) === null) {
  561. missingRequireds.push(key);
  562. }
  563. }
  564. return missingRequireds;
  565. }
  566. /**
  567. * Parse Attribute-Based Login Control Rule as Lucene Query
  568. * @param {string} rule Lucene syntax string
  569. * @returns {object} Expression Tree Structure generated by lucene-query-parser
  570. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  571. */
  572. parseABLCRule(rule) {
  573. // parse with lucene-query-parser
  574. // see https://github.com/thoward/lucene-query-parser.js/wiki
  575. return luceneQueryParser.parse(rule);
  576. }
  577. /**
  578. * Verify that a SAML response meets the attribute-base login control rule
  579. */
  580. verifySAMLResponseByABLCRule(response) {
  581. const rule = this.crowi.configManager.getConfig('crowi', 'security:passport-saml:ABLCRule');
  582. if (rule == null) {
  583. debug('There is no ABLCRule.');
  584. return true;
  585. }
  586. const luceneRule = this.parseABLCRule(rule);
  587. debug({ 'Parsed Rule': JSON.stringify(luceneRule, null, 2) });
  588. const attributes = this.extractAttributesFromSAMLResponse(response);
  589. debug({ 'Extracted Attributes': JSON.stringify(attributes, null, 2) });
  590. return this.evaluateRuleForSamlAttributes(attributes, luceneRule);
  591. }
  592. /**
  593. * Evaluate whether the specified rule is satisfied under the specified attributes
  594. *
  595. * @param {object} attributes results by extractAttributesFromSAMLResponse
  596. * @param {object} luceneRule Expression Tree Structure generated by lucene-query-parser
  597. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  598. */
  599. evaluateRuleForSamlAttributes(attributes, luceneRule) {
  600. const { left, right, operator } = luceneRule;
  601. // when combined rules
  602. if (right != null) {
  603. return this.evaluateCombinedRulesForSamlAttributes(attributes, left, right, operator);
  604. }
  605. if (left != null) {
  606. return this.evaluateRuleForSamlAttributes(attributes, left);
  607. }
  608. const { field, term } = luceneRule;
  609. if (field === '<implicit>') {
  610. return attributes[term] != null;
  611. }
  612. if (attributes[field] == null) {
  613. return false;
  614. }
  615. return attributes[field].includes(term);
  616. }
  617. /**
  618. * Evaluate whether the specified two rules are satisfied under the specified attributes
  619. *
  620. * @param {object} attributes results by extractAttributesFromSAMLResponse
  621. * @param {object} luceneRuleLeft Expression Tree Structure generated by lucene-query-parser
  622. * @param {object} luceneRuleRight Expression Tree Structure generated by lucene-query-parser
  623. * @param {string} luceneOperator operator string expression
  624. * @see https://github.com/thoward/lucene-query-parser.js/wiki
  625. */
  626. evaluateCombinedRulesForSamlAttributes(attributes, luceneRuleLeft, luceneRuleRight, luceneOperator) {
  627. if (luceneOperator === 'OR') {
  628. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) || this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  629. }
  630. if (luceneOperator === 'AND') {
  631. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) && this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  632. }
  633. if (luceneOperator === 'NOT') {
  634. return this.evaluateRuleForSamlAttributes(attributes, luceneRuleLeft) && !this.evaluateRuleForSamlAttributes(attributes, luceneRuleRight);
  635. }
  636. throw new Error(`Unsupported operator: ${luceneOperator}`);
  637. }
  638. /**
  639. * Extract attributes from a SAML response
  640. *
  641. * The format of extracted attributes is the following.
  642. *
  643. * {
  644. * "attribute_name1": ["value1", "value2", ...],
  645. * "attribute_name2": ["value1", "value2", ...],
  646. * ...
  647. * }
  648. */
  649. extractAttributesFromSAMLResponse(response) {
  650. const attributeStatement = response.getAssertion().Assertion.AttributeStatement;
  651. if (attributeStatement == null || attributeStatement[0] == null) {
  652. return {};
  653. }
  654. const attributes = attributeStatement[0].Attribute;
  655. if (attributes == null) {
  656. return {};
  657. }
  658. const result = {};
  659. for (const attribute of attributes) {
  660. const name = attribute.$.Name;
  661. const attributeValues = attribute.AttributeValue.map(v => v._);
  662. if (result[name] == null) {
  663. result[name] = attributeValues;
  664. }
  665. else {
  666. result[name] = result[name].concat(attributeValues);
  667. }
  668. }
  669. return result;
  670. }
  671. /**
  672. * reset BasicStrategy
  673. *
  674. * @memberof PassportService
  675. */
  676. resetBasicStrategy() {
  677. debug('BasicStrategy: reset');
  678. passport.unuse('basic');
  679. this.isBasicStrategySetup = false;
  680. }
  681. /**
  682. * setup BasicStrategy
  683. *
  684. * @memberof PassportService
  685. */
  686. setupBasicStrategy() {
  687. this.resetBasicStrategy();
  688. const configManager = this.crowi.configManager;
  689. const isBasicEnabled = configManager.getConfig('crowi', 'security:passport-basic:isEnabled');
  690. // when disabled
  691. if (!isBasicEnabled) {
  692. return;
  693. }
  694. debug('BasicStrategy: setting up..');
  695. passport.use(new BasicStrategy(
  696. (userId, password, done) => {
  697. if (userId != null) {
  698. return done(null, userId);
  699. }
  700. return done(null, false, { message: 'Incorrect credentials.' });
  701. },
  702. ));
  703. this.isBasicStrategySetup = true;
  704. debug('BasicStrategy: setup is done');
  705. }
  706. /**
  707. * setup serializer and deserializer
  708. *
  709. * @memberof PassportService
  710. */
  711. setupSerializer() {
  712. // check whether the serializer/deserializer have already been set up
  713. if (this.isSerializerSetup) {
  714. throw new Error('serializer/deserializer have already been set up');
  715. }
  716. debug('setting up serializer and deserializer');
  717. const User = this.crowi.model('User');
  718. passport.serializeUser((user, done) => {
  719. done(null, user.id);
  720. });
  721. passport.deserializeUser(async(id, done) => {
  722. try {
  723. // [TODO][user-profile-cache][GW-1775] change how to get profile image data in client side.
  724. const user = await User.findById(id);
  725. if (user == null) {
  726. throw new Error('user not found');
  727. }
  728. done(null, user);
  729. }
  730. catch (err) {
  731. done(err);
  732. }
  733. });
  734. this.isSerializerSetup = true;
  735. }
  736. isSameUsernameTreatedAsIdenticalUser(providerType) {
  737. const key = `security:passport-${providerType}:isSameUsernameTreatedAsIdenticalUser`;
  738. return this.crowi.configManager.getConfig('crowi', key);
  739. }
  740. isSameEmailTreatedAsIdenticalUser(providerType) {
  741. const key = `security:passport-${providerType}:isSameEmailTreatedAsIdenticalUser`;
  742. return this.crowi.configManager.getConfig('crowi', key);
  743. }
  744. }
  745. module.exports = PassportService;