passport.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. const debug = require('debug')('growi:service:PassportService');
  2. const passport = require('passport');
  3. const LocalStrategy = require('passport-local').Strategy;
  4. const LdapStrategy = require('passport-ldapauth');
  5. const GoogleStrategy = require('passport-google-auth').Strategy;
  6. const GitHubStrategy = require('passport-github').Strategy;
  7. const TwitterStrategy = require('passport-twitter').Strategy;
  8. const SamlStrategy = require('passport-saml').Strategy;
  9. /**
  10. * the service class of Passport
  11. */
  12. class PassportService {
  13. // see '/lib/form/login.js'
  14. static get USERNAME_FIELD() { return 'loginForm[username]' }
  15. static get PASSWORD_FIELD() { return 'loginForm[password]' }
  16. constructor(crowi) {
  17. this.crowi = crowi;
  18. /**
  19. * the flag whether LocalStrategy is set up successfully
  20. */
  21. this.isLocalStrategySetup = false;
  22. /**
  23. * the flag whether LdapStrategy is set up successfully
  24. */
  25. this.isLdapStrategySetup = false;
  26. /**
  27. * the flag whether LdapStrategy is set up successfully
  28. */
  29. this.isGoogleStrategySetup = false;
  30. /**
  31. * the flag whether GitHubStrategy is set up successfully
  32. */
  33. this.isGitHubStrategySetup = false;
  34. /**
  35. * the flag whether TwitterStrategy is set up successfully
  36. */
  37. this.isTwitterStrategySetup = false;
  38. /**
  39. * the flag whether SamlStrategy is set up successfully
  40. */
  41. this.isSamlStrategySetup = false;
  42. /**
  43. * the flag whether serializer/deserializer are set up successfully
  44. */
  45. this.isSerializerSetup = false;
  46. /**
  47. * the keys of mandatory configs for SAML
  48. */
  49. this.mandatoryConfigKeysForSaml = [
  50. 'security:passport-saml:isEnabled',
  51. 'security:passport-saml:entryPoint',
  52. 'security:passport-saml:issuer',
  53. 'security:passport-saml:cert',
  54. 'security:passport-saml:attrMapId',
  55. 'security:passport-saml:attrMapUsername',
  56. 'security:passport-saml:attrMapMail'
  57. ];
  58. }
  59. /**
  60. * reset LocalStrategy
  61. *
  62. * @memberof PassportService
  63. */
  64. resetLocalStrategy() {
  65. debug('LocalStrategy: reset');
  66. passport.unuse('local');
  67. this.isLocalStrategySetup = false;
  68. }
  69. /**
  70. * setup LocalStrategy
  71. *
  72. * @memberof PassportService
  73. */
  74. setupLocalStrategy() {
  75. // check whether the strategy has already been set up
  76. if (this.isLocalStrategySetup) {
  77. throw new Error('LocalStrategy has already been set up');
  78. }
  79. debug('LocalStrategy: setting up..');
  80. const User = this.crowi.model('User');
  81. passport.use(new LocalStrategy(
  82. {
  83. usernameField: PassportService.USERNAME_FIELD,
  84. passwordField: PassportService.PASSWORD_FIELD,
  85. },
  86. (username, password, done) => {
  87. // find user
  88. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  89. if (err) { return done(err) }
  90. // check existence and password
  91. if (!user || !user.isPasswordValid(password)) {
  92. return done(null, false, { message: 'Incorrect credentials.' });
  93. }
  94. return done(null, user);
  95. });
  96. }
  97. ));
  98. this.isLocalStrategySetup = true;
  99. debug('LocalStrategy: setup is done');
  100. }
  101. /**
  102. * reset LdapStrategy
  103. *
  104. * @memberof PassportService
  105. */
  106. resetLdapStrategy() {
  107. debug('LdapStrategy: reset');
  108. passport.unuse('ldapauth');
  109. this.isLdapStrategySetup = false;
  110. }
  111. /**
  112. * Asynchronous configuration retrieval
  113. *
  114. * @memberof PassportService
  115. */
  116. setupLdapStrategy() {
  117. // check whether the strategy has already been set up
  118. if (this.isLdapStrategySetup) {
  119. throw new Error('LdapStrategy has already been set up');
  120. }
  121. const config = this.crowi.config;
  122. const Config = this.crowi.model('Config');
  123. const isLdapEnabled = Config.isEnabledPassportLdap(config);
  124. // when disabled
  125. if (!isLdapEnabled) {
  126. return;
  127. }
  128. debug('LdapStrategy: setting up..');
  129. passport.use(new LdapStrategy(this.getLdapConfigurationFunc(config, {passReqToCallback: true}),
  130. (req, ldapAccountInfo, done) => {
  131. debug('LDAP authentication has succeeded', ldapAccountInfo);
  132. // store ldapAccountInfo to req
  133. req.ldapAccountInfo = ldapAccountInfo;
  134. done(null, ldapAccountInfo);
  135. }
  136. ));
  137. this.isLdapStrategySetup = true;
  138. debug('LdapStrategy: setup is done');
  139. }
  140. /**
  141. * return attribute name for mapping to username of Crowi DB
  142. *
  143. * @returns
  144. * @memberof PassportService
  145. */
  146. getLdapAttrNameMappedToUsername() {
  147. const config = this.crowi.config;
  148. return config.crowi['security:passport-ldap:attrMapUsername'] || 'uid';
  149. }
  150. /**
  151. * return attribute name for mapping to name of Crowi DB
  152. *
  153. * @returns
  154. * @memberof PassportService
  155. */
  156. getLdapAttrNameMappedToName() {
  157. const config = this.crowi.config;
  158. return config.crowi['security:passport-ldap:attrMapName'] || '';
  159. }
  160. /**
  161. * return attribute name for mapping to name of Crowi DB
  162. *
  163. * @returns
  164. * @memberof PassportService
  165. */
  166. getLdapAttrNameMappedToMail() {
  167. const config = this.crowi.config;
  168. return config.crowi['security:passport-ldap:attrMapMail'] || 'mail';
  169. }
  170. /**
  171. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  172. *
  173. * @param {any} req
  174. * @returns
  175. * @memberof PassportService
  176. */
  177. getLdapAccountIdFromReq(req) {
  178. return req.body.loginForm.username;
  179. }
  180. /**
  181. * Asynchronous configuration retrieval
  182. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  183. *
  184. * @param {object} config
  185. * @param {object} opts
  186. * @returns
  187. * @memberof PassportService
  188. */
  189. getLdapConfigurationFunc(config, opts) {
  190. // get configurations
  191. const isUserBind = config.crowi['security:passport-ldap:isUserBind'];
  192. const serverUrl = config.crowi['security:passport-ldap:serverUrl'];
  193. const bindDN = config.crowi['security:passport-ldap:bindDN'];
  194. const bindCredentials = config.crowi['security:passport-ldap:bindDNPassword'];
  195. const searchFilter = config.crowi['security:passport-ldap:searchFilter'] || '(uid={{username}})';
  196. const groupSearchBase = config.crowi['security:passport-ldap:groupSearchBase'];
  197. const groupSearchFilter = config.crowi['security:passport-ldap:groupSearchFilter'];
  198. const groupDnProperty = config.crowi['security:passport-ldap:groupDnProperty'] || 'uid';
  199. // parse serverUrl
  200. // see: https://regex101.com/r/0tuYBB/1
  201. const match = serverUrl.match(/(ldaps?:\/\/[^/]+)\/(.*)?/);
  202. if (match == null || match.length < 1) {
  203. debug('LdapStrategy: serverUrl is invalid');
  204. return (req, callback) => { callback({ message: 'serverUrl is invalid'}) };
  205. }
  206. const url = match[1];
  207. const searchBase = match[2] || '';
  208. debug(`LdapStrategy: url=${url}`);
  209. debug(`LdapStrategy: searchBase=${searchBase}`);
  210. debug(`LdapStrategy: isUserBind=${isUserBind}`);
  211. if (!isUserBind) {
  212. debug(`LdapStrategy: bindDN=${bindDN}`);
  213. debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  214. }
  215. debug(`LdapStrategy: searchFilter=${searchFilter}`);
  216. debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  217. debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  218. debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  219. return (req, callback) => {
  220. // get credentials from form data
  221. const loginForm = req.body.loginForm;
  222. if (!req.form.isValid) {
  223. return callback({ message: 'Incorrect credentials.' });
  224. }
  225. // user bind
  226. const fixedBindDN = (isUserBind) ?
  227. bindDN.replace(/{{username}}/, loginForm.username):
  228. bindDN;
  229. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  230. let serverOpt = {
  231. url, bindDN: fixedBindDN, bindCredentials: fixedBindCredentials,
  232. searchBase, searchFilter,
  233. attrMapUsername: this.getLdapAttrNameMappedToUsername(),
  234. attrMapName: this.getLdapAttrNameMappedToName(),
  235. };
  236. if (groupSearchBase && groupSearchFilter) {
  237. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  238. }
  239. process.nextTick(() => {
  240. const mergedOpts = Object.assign({
  241. usernameField: PassportService.USERNAME_FIELD,
  242. passwordField: PassportService.PASSWORD_FIELD,
  243. server: serverOpt,
  244. }, opts);
  245. debug('ldap configuration: ', mergedOpts);
  246. // store configuration to req
  247. req.ldapConfiguration = mergedOpts;
  248. callback(null, mergedOpts);
  249. });
  250. };
  251. }
  252. /**
  253. * Asynchronous configuration retrieval
  254. *
  255. * @memberof PassportService
  256. */
  257. setupGoogleStrategy() {
  258. // check whether the strategy has already been set up
  259. if (this.isGoogleStrategySetup) {
  260. throw new Error('GoogleStrategy has already been set up');
  261. }
  262. const config = this.crowi.config;
  263. const Config = this.crowi.model('Config');
  264. const isGoogleEnabled = Config.isEnabledPassportGoogle(config);
  265. // when disabled
  266. if (!isGoogleEnabled) {
  267. return;
  268. }
  269. debug('GoogleStrategy: setting up..');
  270. passport.use(new GoogleStrategy({
  271. clientId: config.crowi['security:passport-google:clientId'] || process.env.OAUTH_GOOGLE_CLIENT_ID,
  272. clientSecret: config.crowi['security:passport-google:clientSecret'] || process.env.OAUTH_GOOGLE_CLIENT_SECRET,
  273. callbackURL: (this.crowi.configManager.getConfig('crowi', 'app:siteUrl') != null)
  274. ? `${this.crowi.configManager.getSiteUrl()}/passport/google/callback` // auto-generated with v3.2.4 and above
  275. : config.crowi['security:passport-google:callbackUrl'] || process.env.OAUTH_GOOGLE_CALLBACK_URI, // DEPRECATED: backward compatible with v3.2.3 and below
  276. skipUserProfile: false,
  277. }, function(accessToken, refreshToken, profile, done) {
  278. if (profile) {
  279. return done(null, profile);
  280. }
  281. else {
  282. return done(null, false);
  283. }
  284. }));
  285. this.isGoogleStrategySetup = true;
  286. debug('GoogleStrategy: setup is done');
  287. }
  288. /**
  289. * reset GoogleStrategy
  290. *
  291. * @memberof PassportService
  292. */
  293. resetGoogleStrategy() {
  294. debug('GoogleStrategy: reset');
  295. passport.unuse('google');
  296. this.isGoogleStrategySetup = false;
  297. }
  298. setupGitHubStrategy() {
  299. // check whether the strategy has already been set up
  300. if (this.isGitHubStrategySetup) {
  301. throw new Error('GitHubStrategy has already been set up');
  302. }
  303. const config = this.crowi.config;
  304. const Config = this.crowi.model('Config');
  305. const isGitHubEnabled = Config.isEnabledPassportGitHub(config);
  306. // when disabled
  307. if (!isGitHubEnabled) {
  308. return;
  309. }
  310. debug('GitHubStrategy: setting up..');
  311. passport.use(new GitHubStrategy({
  312. clientID: config.crowi['security:passport-github:clientId'] || process.env.OAUTH_GITHUB_CLIENT_ID,
  313. clientSecret: config.crowi['security:passport-github:clientSecret'] || process.env.OAUTH_GITHUB_CLIENT_SECRET,
  314. callbackURL: (this.crowi.configManager.getConfig('crowi', 'app:siteUrl') != null)
  315. ? `${this.crowi.configManager.getSiteUrl()}/passport/github/callback` // auto-generated with v3.2.4 and above
  316. : config.crowi['security:passport-github:callbackUrl'] || process.env.OAUTH_GITHUB_CALLBACK_URI, // DEPRECATED: backward compatible with v3.2.3 and below
  317. skipUserProfile: false,
  318. }, function(accessToken, refreshToken, profile, done) {
  319. if (profile) {
  320. return done(null, profile);
  321. }
  322. else {
  323. return done(null, false);
  324. }
  325. }));
  326. this.isGitHubStrategySetup = true;
  327. debug('GitHubStrategy: setup is done');
  328. }
  329. /**
  330. * reset GitHubStrategy
  331. *
  332. * @memberof PassportService
  333. */
  334. resetGitHubStrategy() {
  335. debug('GitHubStrategy: reset');
  336. passport.unuse('github');
  337. this.isGitHubStrategySetup = false;
  338. }
  339. setupTwitterStrategy() {
  340. // check whether the strategy has already been set up
  341. if (this.isTwitterStrategySetup) {
  342. throw new Error('TwitterStrategy has already been set up');
  343. }
  344. const config = this.crowi.config;
  345. const Config = this.crowi.model('Config');
  346. const isTwitterEnabled = Config.isEnabledPassportTwitter(config);
  347. // when disabled
  348. if (!isTwitterEnabled) {
  349. return;
  350. }
  351. debug('TwitterStrategy: setting up..');
  352. passport.use(new TwitterStrategy({
  353. consumerKey: config.crowi['security:passport-twitter:consumerKey'] || process.env.OAUTH_TWITTER_CONSUMER_KEY,
  354. consumerSecret: config.crowi['security:passport-twitter:consumerSecret'] || process.env.OAUTH_TWITTER_CONSUMER_SECRET,
  355. callbackURL: (this.crowi.configManager.getConfig('crowi', 'app:siteUrl') != null)
  356. ? `${this.crowi.configManager.getSiteUrl()}/passport/twitter/callback` // auto-generated with v3.2.4 and above
  357. : config.crowi['security:passport-twitter:callbackUrl'] || process.env.OAUTH_TWITTER_CALLBACK_URI, // DEPRECATED: backward compatible with v3.2.3 and below
  358. skipUserProfile: false,
  359. }, function(accessToken, refreshToken, profile, done) {
  360. if (profile) {
  361. return done(null, profile);
  362. }
  363. else {
  364. return done(null, false);
  365. }
  366. }));
  367. this.isTwitterStrategySetup = true;
  368. debug('TwitterStrategy: setup is done');
  369. }
  370. /**
  371. * reset TwitterStrategy
  372. *
  373. * @memberof PassportService
  374. */
  375. resetTwitterStrategy() {
  376. debug('TwitterStrategy: reset');
  377. passport.unuse('twitter');
  378. this.isTwitterStrategySetup = false;
  379. }
  380. setupSamlStrategy() {
  381. // check whether the strategy has already been set up
  382. if (this.isSamlStrategySetup) {
  383. throw new Error('SamlStrategy has already been set up');
  384. }
  385. const config = this.crowi.config;
  386. const configManager = this.crowi.configManager;
  387. const isSamlEnabled = configManager.getConfig('crowi', 'security:passport-saml:isEnabled');
  388. // when disabled
  389. if (!isSamlEnabled) {
  390. return;
  391. }
  392. debug('SamlStrategy: setting up..');
  393. passport.use(new SamlStrategy({
  394. entryPoint: configManager.getConfig('crowi', 'security:passport-saml:entryPoint'),
  395. callbackUrl: (this.crowi.configManager.getConfig('crowi', 'app:siteUrl') != null)
  396. ? `${this.crowi.configManager.getSiteUrl()}/passport/saml/callback` // auto-generated with v3.2.4 and above
  397. : configManager.getConfig('crowi', 'security:passport-saml:callbackUrl'), // DEPRECATED: backward compatible with v3.2.3 and below
  398. issuer: configManager.getConfig('crowi', 'security:passport-saml:issuer'),
  399. cert: configManager.getConfig('crowi', 'security:passport-saml:cert'),
  400. }, function(profile, done) {
  401. if (profile) {
  402. return done(null, profile);
  403. }
  404. else {
  405. return done(null, false);
  406. }
  407. }));
  408. this.isSamlStrategySetup = true;
  409. debug('SamlStrategy: setup is done');
  410. }
  411. /**
  412. * reset SamlStrategy
  413. *
  414. * @memberof PassportService
  415. */
  416. resetSamlStrategy() {
  417. debug('SamlStrategy: reset');
  418. passport.unuse('saml');
  419. this.isSamlStrategySetup = false;
  420. }
  421. /**
  422. * return the keys of the configs mandatory for SAML whose value are empty.
  423. */
  424. getSamlMissingMandatoryConfigKeys() {
  425. const missingRequireds = [];
  426. for (const key of this.mandatoryConfigKeysForSaml) {
  427. if (this.crowi.configManager.getConfig('crowi', key) === null) {
  428. missingRequireds.push(key);
  429. }
  430. }
  431. return missingRequireds;
  432. }
  433. /**
  434. * setup serializer and deserializer
  435. *
  436. * @memberof PassportService
  437. */
  438. setupSerializer() {
  439. // check whether the serializer/deserializer have already been set up
  440. if (this.isSerializerSetup) {
  441. throw new Error('serializer/deserializer have already been set up');
  442. }
  443. debug('setting up serializer and deserializer');
  444. const User = this.crowi.model('User');
  445. passport.serializeUser(function(user, done) {
  446. done(null, user.id);
  447. });
  448. passport.deserializeUser(async function(id, done) {
  449. try {
  450. const user = await User.findById(id).populate(User.IMAGE_POPULATION);
  451. if (user == null) {
  452. throw new Error('user not found');
  453. }
  454. done(null, user);
  455. }
  456. catch (err) {
  457. done(err);
  458. }
  459. });
  460. this.isSerializerSetup = true;
  461. }
  462. isSameUsernameTreatedAsIdenticalUser(providerType) {
  463. const key = `security:passport-${providerType}:isSameUsernameTreatedAsIdenticalUser`;
  464. return this.crowi.configManager.getConfig('crowi', key);
  465. }
  466. isSameEmailTreatedAsIdenticalUser(providerType) {
  467. const key = `security:passport-${providerType}:isSameEmailTreatedAsIdenticalUser`;
  468. return this.crowi.configManager.getConfig('crowi', key);
  469. }
  470. }
  471. module.exports = PassportService;