passport.js 11 KB

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