passport.js 15 KB

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