passport.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  137. *
  138. * @param {any} req
  139. * @returns
  140. * @memberof PassportService
  141. */
  142. getLdapAccountIdFromReq(req) {
  143. return req.body.loginForm.username;
  144. }
  145. /**
  146. * Asynchronous configuration retrieval
  147. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  148. *
  149. * @param {object} config
  150. * @param {object} opts
  151. * @returns
  152. * @memberof PassportService
  153. */
  154. getLdapConfigurationFunc(config, opts) {
  155. // get configurations
  156. const isUserBind = config.crowi['security:passport-ldap:isUserBind'];
  157. const serverUrl = config.crowi['security:passport-ldap:serverUrl'];
  158. const bindDN = config.crowi['security:passport-ldap:bindDN'];
  159. const bindCredentials = config.crowi['security:passport-ldap:bindDNPassword'];
  160. const searchFilter = config.crowi['security:passport-ldap:searchFilter'] || '(uid={{username}})';
  161. const groupSearchBase = config.crowi['security:passport-ldap:groupSearchBase'];
  162. const groupSearchFilter = config.crowi['security:passport-ldap:groupSearchFilter'];
  163. const groupDnProperty = config.crowi['security:passport-ldap:groupDnProperty'] || 'uid';
  164. // parse serverUrl
  165. // see: https://regex101.com/r/0tuYBB/1
  166. const match = serverUrl.match(/(ldaps?:\/\/[^/]+)\/(.*)?/);
  167. if (match == null || match.length < 1) {
  168. debug('LdapStrategy: serverUrl is invalid');
  169. return (req, callback) => { callback({ message: 'serverUrl is invalid'}) };
  170. }
  171. const url = match[1];
  172. const searchBase = match[2] || '';
  173. debug(`LdapStrategy: url=${url}`);
  174. debug(`LdapStrategy: searchBase=${searchBase}`);
  175. debug(`LdapStrategy: isUserBind=${isUserBind}`);
  176. if (!isUserBind) {
  177. debug(`LdapStrategy: bindDN=${bindDN}`);
  178. debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  179. }
  180. debug(`LdapStrategy: searchFilter=${searchFilter}`);
  181. debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  182. debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  183. debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  184. return (req, callback) => {
  185. // get credentials from form data
  186. const loginForm = req.body.loginForm;
  187. if (!req.form.isValid) {
  188. return callback({ message: 'Incorrect credentials.' });
  189. }
  190. // user bind
  191. const fixedBindDN = (isUserBind) ?
  192. bindDN.replace(/{{username}}/, loginForm.username):
  193. bindDN;
  194. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  195. let serverOpt = {
  196. url, bindDN: fixedBindDN, bindCredentials: fixedBindCredentials,
  197. searchBase, searchFilter,
  198. attrMapUsername: this.getLdapAttrNameMappedToUsername(),
  199. attrMapName: this.getLdapAttrNameMappedToName(),
  200. };
  201. if (groupSearchBase && groupSearchFilter) {
  202. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  203. }
  204. process.nextTick(() => {
  205. const mergedOpts = Object.assign({
  206. usernameField: PassportService.USERNAME_FIELD,
  207. passwordField: PassportService.PASSWORD_FIELD,
  208. server: serverOpt,
  209. }, opts);
  210. debug('ldap configuration: ', mergedOpts);
  211. // store configuration to req
  212. req.ldapConfiguration = mergedOpts;
  213. callback(null, mergedOpts);
  214. });
  215. };
  216. }
  217. /**
  218. * Asynchronous configuration retrieval
  219. *
  220. * @memberof PassportService
  221. */
  222. setupGoogleStrategy() {
  223. // check whether the strategy has already been set up
  224. if (this.isGoogleStrategySetup) {
  225. throw new Error('GoogleStrategy has already been set up');
  226. }
  227. const config = this.crowi.config;
  228. const Config = this.crowi.model('Config');
  229. //this
  230. const isGoogleEnabled = Config.isEnabledPassportGoogle(config);
  231. // when disabled
  232. if (!isGoogleEnabled) {
  233. return;
  234. }
  235. debug('GoogleStrategy: setting up..');
  236. passport.use(new GoogleStrategy({
  237. clientId: config.crowi['security:passport-google:clientId'] || process.env.OAUTH_GOOGLE_CLIENT_ID,
  238. clientSecret: config.crowi['security:passport-google:clientSecret'] || process.env.OAUTH_GOOGLE_CLIENT_SECRET,
  239. callbackURL: config.crowi['security:passport-google:callbackUrl'] || process.env.OAUTH_GOOGLE_CALLBACK_URI,
  240. skipUserProfile: false,
  241. }, function(accessToken, refreshToken, profile, done) {
  242. if (profile) {
  243. return done(null, profile);
  244. }
  245. else {
  246. return done(null, false);
  247. }
  248. }));
  249. this.isGoogleStrategySetup = true;
  250. debug('GoogleStrategy: setup is done');
  251. }
  252. /**
  253. * reset GoogleStrategy
  254. *
  255. * @memberof PassportService
  256. */
  257. resetGoogleStrategy() {
  258. debug('GoogleStrategy: reset');
  259. passport.unuse('google');
  260. this.isGoogleStrategySetup = false;
  261. }
  262. setupGitHubStrategy() {
  263. // check whether the strategy has already been set up
  264. if (this.isGitHubStrategySetup) {
  265. throw new Error('GitHubStrategy has already been set up');
  266. }
  267. const config = this.crowi.config;
  268. const Config = this.crowi.model('Config');
  269. //this
  270. const isGitHubEnabled = Config.isEnabledPassportGitHub(config);
  271. // when disabled
  272. if (!isGitHubEnabled) {
  273. return;
  274. }
  275. debug('GitHubStrategy: setting up..');
  276. passport.use(new GitHubStrategy({
  277. clientID: config.crowi['security:passport-github:clientId'] || process.env.OAUTH_GITHUB_CLIENT_ID,
  278. clientSecret: config.crowi['security:passport-github:clientSecret'] || process.env.OAUTH_GITHUB_CLIENT_SECRET,
  279. callbackURL: config.crowi['security:passport-github:callbackUrl'] || process.env.OAUTH_GITHUB_CALLBACK_URI,
  280. skipUserProfile: false,
  281. }, function(accessToken, refreshToken, profile, done) {
  282. if (profile) {
  283. return done(null, profile);
  284. }
  285. else {
  286. return done(null, false);
  287. }
  288. }));
  289. this.isGitHubStrategySetup = true;
  290. debug('GitHubStrategy: setup is done');
  291. }
  292. /**
  293. * reset GoogleStrategy
  294. *
  295. * @memberof PassportService
  296. */
  297. resetGitHubStrategy() {
  298. debug('GitHubStrategy: reset');
  299. passport.unuse('github');
  300. this.isGitHubStrategySetup = false;
  301. }
  302. setupTwitterStrategy() {
  303. // check whether the strategy has already been set up
  304. if (this.isTwitterStrategySetup) {
  305. throw new Error('TwitterStrategy has already been set up');
  306. }
  307. const config = this.crowi.config;
  308. const Config = this.crowi.model('Config');
  309. //this
  310. const isTwitterEnabled = Config.isEnabledPassportTwitter(config);
  311. // when disabled
  312. if (!isTwitterEnabled) {
  313. return;
  314. }
  315. debug('TwitterStrategy: setting up..');
  316. passport.use(new TwitterStrategy({
  317. consumerKey: config.crowi['security:passport-twitter:consumerKey'] || process.env.OAUTH_TWITTER_CLIENT_ID,
  318. consumerSecret: config.crowi['security:passport-twitter:consumerSecret'] || process.env.OAUTH_TWITTER_CLIENT_SECRET,
  319. callbackURL: config.crowi['security:passport-twitter:callbackUrl'] || process.env.OAUTH_TWITTER_CALLBACK_URI,
  320. skipUserProfile: false,
  321. }, function(accessToken, refreshToken, profile, done) {
  322. if (profile) {
  323. return done(null, profile);
  324. }
  325. else {
  326. return done(null, false);
  327. }
  328. }));
  329. this.isTwitterStrategySetup = true;
  330. debug('TwitterStrategy: setup is done');
  331. }
  332. /**
  333. * reset GoogleStrategy
  334. *
  335. * @memberof PassportService
  336. */
  337. resetTwitterStrategy() {
  338. debug('TwitterStrategy: reset');
  339. passport.unuse('twitter');
  340. this.isTwitterStrategySetup = false;
  341. }
  342. /**
  343. * setup serializer and deserializer
  344. *
  345. * @memberof PassportService
  346. */
  347. setupSerializer() {
  348. // check whether the serializer/deserializer have already been set up
  349. if (this.isSerializerSetup) {
  350. throw new Error('serializer/deserializer have already been set up');
  351. }
  352. debug('setting up serializer and deserializer');
  353. const User = this.crowi.model('User');
  354. passport.serializeUser(function(user, done) {
  355. done(null, user.id);
  356. });
  357. passport.deserializeUser(function(id, done) {
  358. User.findById(id, function(err, user) {
  359. done(err, user);
  360. });
  361. });
  362. this.isSerializerSetup = true;
  363. }
  364. }
  365. module.exports = PassportService;