passport.js 11 KB

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