passport.js 12 KB

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