passport.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. const debug = require('debug')('crowi:service:PassportService');
  2. const passport = require('passport');
  3. const LocalStrategy = require('passport-local').Strategy;
  4. const LdapStrategy = require('passport-ldapauth');
  5. /**
  6. * the service class of Passport
  7. */
  8. class PassportService {
  9. // see '/lib/form/login.js'
  10. static get USERNAME_FIELD() { return 'loginForm[username]' }
  11. static get PASSWORD_FIELD() { return 'loginForm[password]' }
  12. constructor(crowi) {
  13. this.crowi = crowi;
  14. /**
  15. * the flag whether LocalStrategy is set up successfully
  16. */
  17. this.isLocalStrategySetup = false;
  18. /**
  19. * the flag whether LdapStrategy is set up successfully
  20. */
  21. this.isLdapStrategySetup = false;
  22. /**
  23. * the flag whether serializer/deserializer are set up successfully
  24. */
  25. this.isSerializerSetup = false;
  26. }
  27. /**
  28. * reset LocalStrategy
  29. *
  30. * @memberof PassportService
  31. */
  32. resetLocalStrategy() {
  33. debug('LocalStrategy: reset');
  34. passport.unuse('local');
  35. this.isLocalStrategySetup = false;
  36. }
  37. /**
  38. * setup LocalStrategy
  39. *
  40. * @memberof PassportService
  41. */
  42. setupLocalStrategy() {
  43. // check whether the strategy has already been set up
  44. if (this.isLocalStrategySetup) {
  45. throw new Error('LocalStrategy has already been set up');
  46. }
  47. debug('LocalStrategy: setting up..');
  48. const User = this.crowi.model('User');
  49. passport.use(new LocalStrategy(
  50. {
  51. usernameField: PassportService.USERNAME_FIELD,
  52. passwordField: PassportService.PASSWORD_FIELD,
  53. },
  54. (username, password, done) => {
  55. // find user
  56. User.findUserByUsernameOrEmail(username, password, (err, user) => {
  57. if (err) { return done(err); }
  58. // check existence and password
  59. if (!user || !user.isPasswordValid(password)) {
  60. return done(null, false, { message: 'Incorrect credentials.' });
  61. }
  62. return done(null, user);
  63. });
  64. }
  65. ));
  66. this.isLocalStrategySetup = true;
  67. debug('LocalStrategy: setup is done');
  68. }
  69. /**
  70. * reset LdapStrategy
  71. *
  72. * @memberof PassportService
  73. */
  74. resetLdapStrategy() {
  75. debug('LdapStrategy: reset');
  76. passport.unuse('ldapauth');
  77. this.isLdapStrategySetup = false;
  78. }
  79. /**
  80. * Asynchronous configuration retrieval
  81. *
  82. * @memberof PassportService
  83. */
  84. setupLdapStrategy() {
  85. // check whether the strategy has already been set up
  86. if (this.isLdapStrategySetup) {
  87. throw new Error('LdapStrategy has already been set up');
  88. }
  89. const config = this.crowi.config;
  90. const Config = this.crowi.model('Config');
  91. const isLdapEnabled = Config.isEnabledPassportLdap(config);
  92. // when disabled
  93. if (!isLdapEnabled) {
  94. return;
  95. }
  96. debug('LdapStrategy: setting up..');
  97. passport.use(new LdapStrategy(this.getLdapConfigurationFunc(config, {passReqToCallback: true}),
  98. (req, ldapAccountInfo, done) => {
  99. debug("LDAP authentication has succeeded", ldapAccountInfo);
  100. done(null, ldapAccountInfo);
  101. }
  102. ));
  103. this.isLdapStrategySetup = true;
  104. debug('LdapStrategy: setup is done');
  105. }
  106. /**
  107. * return attribute name for mapping to username of Crowi DB
  108. *
  109. * @returns
  110. * @memberof PassportService
  111. */
  112. getLdapAttrNameMappedToUsername() {
  113. const config = this.crowi.config;
  114. return config.crowi['security:passport-ldap:attrMapUsername'] || 'uid';
  115. }
  116. /**
  117. * CAUTION: this method is capable to use only when `req.body.loginForm` is not null
  118. *
  119. * @param {any} req
  120. * @returns
  121. * @memberof PassportService
  122. */
  123. getLdapAccountIdFromReq(req) {
  124. return req.body.loginForm.username;
  125. }
  126. /**
  127. * Asynchronous configuration retrieval
  128. * @see https://github.com/vesse/passport-ldapauth#asynchronous-configuration-retrieval
  129. *
  130. * @param {object} config
  131. * @param {object} opts
  132. * @returns
  133. * @memberof PassportService
  134. */
  135. getLdapConfigurationFunc(config, opts) {
  136. // get configurations
  137. const isUserBind = config.crowi['security:passport-ldap:isUserBind'];
  138. const serverUrl = config.crowi['security:passport-ldap:serverUrl'];
  139. const bindDN = config.crowi['security:passport-ldap:bindDN'];
  140. const bindCredentials = config.crowi['security:passport-ldap:bindDNPassword'];
  141. const searchFilter = config.crowi['security:passport-ldap:searchFilter'] || '(uid={{username}})';
  142. const groupSearchBase = config.crowi['security:passport-ldap:groupSearchBase'];
  143. const groupSearchFilter = config.crowi['security:passport-ldap:groupSearchFilter'];
  144. const groupDnProperty = config.crowi['security:passport-ldap:groupDnProperty'] || 'uid';
  145. // parse serverUrl
  146. // see: https://regex101.com/r/0tuYBB/1
  147. const match = serverUrl.match(/(ldaps?:\/\/[^\/]+)\/(.*)?/);
  148. if (match == null || match.length < 1) {
  149. debug('LdapStrategy: serverUrl is invalid');
  150. return;
  151. }
  152. const url = match[1];
  153. const searchBase = match[2] || '';
  154. debug(`LdapStrategy: url=${url}`);
  155. debug(`LdapStrategy: searchBase=${searchBase}`);
  156. debug(`LdapStrategy: isUserBind=${isUserBind}`);
  157. if (!isUserBind) {
  158. debug(`LdapStrategy: bindDN=${bindDN}`);
  159. debug(`LdapStrategy: bindCredentials=${bindCredentials}`);
  160. }
  161. debug(`LdapStrategy: searchFilter=${searchFilter}`);
  162. debug(`LdapStrategy: groupSearchBase=${groupSearchBase}`);
  163. debug(`LdapStrategy: groupSearchFilter=${groupSearchFilter}`);
  164. debug(`LdapStrategy: groupDnProperty=${groupDnProperty}`);
  165. return (req, callback) => {
  166. // get credentials from form data
  167. const loginForm = req.body.loginForm;
  168. if (!req.form.isValid) {
  169. return callback({ message: 'Incorrect credentials.' });
  170. }
  171. // user bind
  172. const fixedBindDN = (isUserBind) ?
  173. bindDN.replace(/{{username}}/, loginForm.username):
  174. bindDN;
  175. const fixedBindCredentials = (isUserBind) ? loginForm.password : bindCredentials;
  176. let serverOpt = { url, bindDN: fixedBindDN, bindCredentials: fixedBindCredentials, searchBase, searchFilter };
  177. if (groupSearchBase && groupSearchFilter) {
  178. serverOpt = Object.assign(serverOpt, { groupSearchBase, groupSearchFilter, groupDnProperty });
  179. }
  180. process.nextTick(() => {
  181. const mergedOpts = Object.assign({
  182. usernameField: PassportService.USERNAME_FIELD,
  183. passwordField: PassportService.PASSWORD_FIELD,
  184. server: serverOpt,
  185. }, opts);
  186. debug('ldap configuration: ', mergedOpts);
  187. callback(null, mergedOpts);
  188. });
  189. };
  190. }
  191. /**
  192. * setup serializer and deserializer
  193. *
  194. * @memberof PassportService
  195. */
  196. setupSerializer() {
  197. // check whether the serializer/deserializer have already been set up
  198. if (this.isSerializerSetup) {
  199. throw new Error('serializer/deserializer have already been set up');
  200. }
  201. debug('setting up serializer and deserializer');
  202. const User = this.crowi.model('User');
  203. passport.serializeUser(function(user, done) {
  204. done(null, user.id);
  205. });
  206. passport.deserializeUser(function(id, done) {
  207. User.findById(id, function(err, user) {
  208. done(err, user);
  209. });
  210. });
  211. this.isSerializerSetup = true;
  212. }
  213. }
  214. module.exports = PassportService;