passport.js 16 KB

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