passport.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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['security:passport-google:callbackUrl'] || process.env.OAUTH_GOOGLE_CALLBACK_URI,
  262. skipUserProfile: false,
  263. }, function(accessToken, refreshToken, profile, done) {
  264. if (profile) {
  265. return done(null, profile);
  266. }
  267. else {
  268. return done(null, false);
  269. }
  270. }));
  271. this.isGoogleStrategySetup = true;
  272. debug('GoogleStrategy: setup is done');
  273. }
  274. /**
  275. * reset GoogleStrategy
  276. *
  277. * @memberof PassportService
  278. */
  279. resetGoogleStrategy() {
  280. debug('GoogleStrategy: reset');
  281. passport.unuse('google');
  282. this.isGoogleStrategySetup = false;
  283. }
  284. setupGitHubStrategy() {
  285. // check whether the strategy has already been set up
  286. if (this.isGitHubStrategySetup) {
  287. throw new Error('GitHubStrategy has already been set up');
  288. }
  289. const config = this.crowi.config;
  290. const Config = this.crowi.model('Config');
  291. const isGitHubEnabled = Config.isEnabledPassportGitHub(config);
  292. // when disabled
  293. if (!isGitHubEnabled) {
  294. return;
  295. }
  296. debug('GitHubStrategy: setting up..');
  297. passport.use(new GitHubStrategy({
  298. clientID: config.crowi['security:passport-github:clientId'] || process.env.OAUTH_GITHUB_CLIENT_ID,
  299. clientSecret: config.crowi['security:passport-github:clientSecret'] || process.env.OAUTH_GITHUB_CLIENT_SECRET,
  300. callbackURL: config.crowi['security:passport-github:callbackUrl'] || process.env.OAUTH_GITHUB_CALLBACK_URI,
  301. skipUserProfile: false,
  302. }, function(accessToken, refreshToken, profile, done) {
  303. if (profile) {
  304. return done(null, profile);
  305. }
  306. else {
  307. return done(null, false);
  308. }
  309. }));
  310. this.isGitHubStrategySetup = true;
  311. debug('GitHubStrategy: setup is done');
  312. }
  313. /**
  314. * reset GitHubStrategy
  315. *
  316. * @memberof PassportService
  317. */
  318. resetGitHubStrategy() {
  319. debug('GitHubStrategy: reset');
  320. passport.unuse('github');
  321. this.isGitHubStrategySetup = false;
  322. }
  323. setupTwitterStrategy() {
  324. // check whether the strategy has already been set up
  325. if (this.isTwitterStrategySetup) {
  326. throw new Error('TwitterStrategy has already been set up');
  327. }
  328. const config = this.crowi.config;
  329. const Config = this.crowi.model('Config');
  330. const isTwitterEnabled = Config.isEnabledPassportTwitter(config);
  331. // when disabled
  332. if (!isTwitterEnabled) {
  333. return;
  334. }
  335. debug('TwitterStrategy: setting up..');
  336. passport.use(new TwitterStrategy({
  337. consumerKey: config.crowi['security:passport-twitter:consumerKey'] || process.env.OAUTH_TWITTER_CONSUMER_KEY,
  338. consumerSecret: config.crowi['security:passport-twitter:consumerSecret'] || process.env.OAUTH_TWITTER_CONSUMER_SECRET,
  339. callbackURL: config.crowi['security:passport-twitter:callbackUrl'] || process.env.OAUTH_TWITTER_CALLBACK_URI,
  340. skipUserProfile: false,
  341. }, function(accessToken, refreshToken, profile, done) {
  342. if (profile) {
  343. return done(null, profile);
  344. }
  345. else {
  346. return done(null, false);
  347. }
  348. }));
  349. this.isTwitterStrategySetup = true;
  350. debug('TwitterStrategy: setup is done');
  351. }
  352. /**
  353. * reset TwitterStrategy
  354. *
  355. * @memberof PassportService
  356. */
  357. resetTwitterStrategy() {
  358. debug('TwitterStrategy: reset');
  359. passport.unuse('twitter');
  360. this.isTwitterStrategySetup = false;
  361. }
  362. setupSamlStrategy() {
  363. // check whether the strategy has already been set up
  364. if (this.isSamlStrategySetup) {
  365. throw new Error('SamlStrategy has already been set up');
  366. }
  367. const config = this.crowi.config;
  368. const Config = this.crowi.model('Config');
  369. // const isSamlEnabled = Config.isEnabledPassportSaml(config);
  370. const isSamlEnabled = true;
  371. // when disabled
  372. if (!isSamlEnabled) {
  373. return;
  374. }
  375. debug('SamlStrategy: setting up..');
  376. passport.use(new SamlStrategy({
  377. path: config.crowi['security:passport-saml:path'] || process.env.SAML_CALLBACK_URI,
  378. entryPoint: config.crowi['security:passport-saml:entryPoint'] || process.env.SAML_ENTRY_POINT,
  379. issuer: config.crowi['security:passport-saml:issuer'] || process.env.SAML_ISSUER,
  380. }, function(profile, done) {
  381. if (profile) {
  382. return done(null, profile);
  383. }
  384. else {
  385. return done(null, false);
  386. }
  387. }));
  388. this.isSamlStrategySetup = true;
  389. debug('SamlStrategy: setup is done');
  390. }
  391. /**
  392. * reset SamlStrategy
  393. *
  394. * @memberof PassportService
  395. */
  396. resetSamlStrategy() {
  397. debug('SamlStrategy: reset');
  398. passport.unuse('saml');
  399. this.isSamlStrategySetup = false;
  400. }
  401. /**
  402. * setup serializer and deserializer
  403. *
  404. * @memberof PassportService
  405. */
  406. setupSerializer() {
  407. // check whether the serializer/deserializer have already been set up
  408. if (this.isSerializerSetup) {
  409. throw new Error('serializer/deserializer have already been set up');
  410. }
  411. debug('setting up serializer and deserializer');
  412. const User = this.crowi.model('User');
  413. passport.serializeUser(function(user, done) {
  414. done(null, user.id);
  415. });
  416. passport.deserializeUser(function(id, done) {
  417. User.findById(id, function(err, user) {
  418. done(err, user);
  419. });
  420. });
  421. this.isSerializerSetup = true;
  422. }
  423. }
  424. module.exports = PassportService;