me.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('growi:routes:me')
  4. , fs = require('fs')
  5. , models = crowi.models
  6. , config = crowi.getConfig()
  7. , User = models.User
  8. , UserGroupRelation = models.UserGroupRelation
  9. , ExternalAccount = models.ExternalAccount
  10. , ApiResponse = require('../util/apiResponse')
  11. //, pluginService = require('../service/plugin')
  12. , actions = {}
  13. , api = {}
  14. ;
  15. actions.api = api;
  16. api.uploadPicture = function(req, res) {
  17. var fileUploader = require('../util/fileUploader')(crowi, app);
  18. //var storagePlugin = new pluginService('storage');
  19. //var storage = require('../service/storage').StorageService(config);
  20. var tmpFile = req.file || null;
  21. if (!tmpFile) {
  22. return res.json({
  23. 'status': false,
  24. 'message': 'File type error.'
  25. });
  26. }
  27. var tmpPath = tmpFile.path;
  28. var filePath = User.createUserPictureFilePath(req.user, tmpFile.filename + tmpFile.originalname);
  29. var acceptableFileType = /image\/.+/;
  30. if (!tmpFile.mimetype.match(acceptableFileType)) {
  31. return res.json({
  32. 'status': false,
  33. 'message': 'File type error. Only image files is allowed to set as user picture.',
  34. });
  35. }
  36. //debug('tmpFile Is', tmpFile, tmpFile.constructor, tmpFile.prototype);
  37. //var imageUrl = storage.writeSync(storage.tofs(tmpFile), filePath, {mime: tmpFile.mimetype});
  38. //return return res.json({
  39. // 'status': true,
  40. // 'url': imageUrl,
  41. // 'message': '',
  42. //});
  43. var tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  44. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  45. .then(function(data) {
  46. var imageUrl = fileUploader.generateUrl(filePath);
  47. req.user.updateImage(imageUrl, function(err, data) {
  48. fs.unlink(tmpPath, function(err) {
  49. // エラー自体は無視
  50. if (err) {
  51. debug('Error while deleting tmp file.', err);
  52. }
  53. return res.json({
  54. 'status': true,
  55. 'url': imageUrl,
  56. 'message': '',
  57. });
  58. });
  59. });
  60. }).catch(function(err) {
  61. debug('Uploading error', err);
  62. return res.json({
  63. 'status': false,
  64. 'message': 'Error while uploading to ',
  65. });
  66. });
  67. };
  68. /**
  69. * retrieve user-group-relation documents
  70. * @param {object} req
  71. * @param {object} res
  72. */
  73. api.userGroupRelations = function(req, res) {
  74. UserGroupRelation.findAllRelationForUser(req.user)
  75. .then(userGroupRelations => {
  76. return res.json(ApiResponse.success({userGroupRelations}));
  77. });
  78. };
  79. actions.index = function(req, res) {
  80. var userForm = req.body.userForm;
  81. var userData = req.user;
  82. if (req.method == 'POST' && req.form.isValid) {
  83. var name = userForm.name;
  84. var email = userForm.email;
  85. var lang = userForm.lang;
  86. var isEmailPublished = userForm.isEmailPublished;
  87. /*
  88. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  89. *
  90. if (!User.isEmailValid(email)) {
  91. req.form.errors.push('You can\'t update to that email address');
  92. return res.render('me/index', {});
  93. }
  94. */
  95. User.findOneAndUpdate(
  96. { email: userData.email }, // query
  97. { name, email, lang, isEmailPublished }, // updating data
  98. { runValidators: true, context: 'query' }, // for validation
  99. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  100. (err) => {
  101. if (err) {
  102. Object.keys(err.errors).forEach((e) => {
  103. req.form.errors.push(err.errors[e].message);
  104. });
  105. return res.render('me/index', {});
  106. }
  107. req.i18n.changeLanguage(lang);
  108. req.flash('successMessage', req.t('Updated'));
  109. return res.redirect('/me');
  110. });
  111. }
  112. else { // method GET
  113. /*
  114. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  115. *
  116. /// そのうちこのコードはいらなくなるはず
  117. if (!userData.isEmailSet()) {
  118. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  119. }
  120. */
  121. return res.render('me/index', {
  122. });
  123. }
  124. };
  125. actions.imagetype = function(req, res) {
  126. if (req.method !== 'POST') {
  127. // do nothing
  128. return;
  129. }
  130. else if (!req.form.isValid) {
  131. req.flash('errorMessage', req.form.errors.join('\n'));
  132. return;
  133. }
  134. var imagetypeForm = req.body.imagetypeForm;
  135. var userData = req.user;
  136. var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  137. userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
  138. if (err) {
  139. for (var e in err.errors) {
  140. if (err.errors.hasOwnProperty(e)) {
  141. req.form.errors.push(err.errors[e].message);
  142. }
  143. }
  144. return res.render('me/index', {});
  145. }
  146. req.flash('successMessage', req.t('Updated'));
  147. return res.redirect('/me');
  148. });
  149. };
  150. actions.externalAccounts = {};
  151. actions.externalAccounts.list = function(req, res) {
  152. const userData = req.user;
  153. let renderVars = {};
  154. ExternalAccount.find({user: userData})
  155. .then((externalAccounts) => {
  156. renderVars.externalAccounts = externalAccounts;
  157. return;
  158. })
  159. .then(() => {
  160. if (req.method == 'POST' && req.form.isValid) {
  161. // TODO impl
  162. return res.render('me/external-accounts', renderVars);
  163. }
  164. else { // method GET
  165. return res.render('me/external-accounts', renderVars);
  166. }
  167. });
  168. };
  169. actions.externalAccounts.disassociate = function(req, res) {
  170. const userData = req.user;
  171. const redirectWithFlash = (type, msg) => {
  172. req.flash(type, msg);
  173. return res.redirect('/me/external-accounts');
  174. };
  175. if (req.body == null) {
  176. redirectWithFlash('errorMessage', 'Invalid form.');
  177. }
  178. // make sure password set or this user has two or more ExternalAccounts
  179. new Promise((resolve, reject) => {
  180. if (userData.password != null) {
  181. resolve(true);
  182. }
  183. else {
  184. ExternalAccount.count({user: userData})
  185. .then((count) => {
  186. resolve(count > 1);
  187. });
  188. }
  189. })
  190. .then((isDisassociatable) => {
  191. if (!isDisassociatable) {
  192. let e = new Error();
  193. e.name = 'couldntDisassociateError';
  194. throw e;
  195. }
  196. const providerType = req.body.providerType;
  197. const accountId = req.body.accountId;
  198. return ExternalAccount.findOneAndRemove({providerType, accountId, user: userData});
  199. })
  200. .then((account) => {
  201. if (account == null) {
  202. return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
  203. }
  204. else {
  205. return redirectWithFlash('successMessage', 'Successfully disassociated.');
  206. }
  207. })
  208. .catch((err) => {
  209. if (err) {
  210. if (err.name == 'couldntDisassociateError') {
  211. return redirectWithFlash('couldntDisassociateError', true);
  212. }
  213. else {
  214. return redirectWithFlash('errorMessage', err.message);
  215. }
  216. }
  217. });
  218. };
  219. actions.externalAccounts.associateLdap = function(req, res) {
  220. const passport = require('passport');
  221. const passportService = crowi.passportService;
  222. const redirectWithFlash = (type, msg) => {
  223. req.flash(type, msg);
  224. return res.redirect('/me/external-accounts');
  225. };
  226. if (!passportService.isLdapStrategySetup) {
  227. debug('LdapStrategy has not been set up');
  228. return redirectWithFlash('warning', 'LdapStrategy has not been set up');
  229. }
  230. const loginForm = req.body.loginForm;
  231. passport.authenticate('ldapauth', (err, user, info) => {
  232. if (res.headersSent) { // dirty hack -- 2017.09.25
  233. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  234. }
  235. if (err) { // DB Error
  236. console.log('LDAP Server Error: ', err);
  237. return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
  238. }
  239. if (info && info.message) {
  240. return redirectWithFlash('warningMessage', info.message);
  241. }
  242. if (user) {
  243. // create ExternalAccount
  244. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  245. const user = req.user;
  246. ExternalAccount.associate('ldap', ldapAccountId, user)
  247. .then(() => {
  248. return redirectWithFlash('successMessage', 'Successfully added.');
  249. })
  250. .catch((err) => {
  251. return redirectWithFlash('errorMessage', err.message);
  252. });
  253. }
  254. })(req, res, () => {});
  255. };
  256. actions.password = function(req, res) {
  257. var passwordForm = req.body.mePassword;
  258. var userData = req.user;
  259. /*
  260. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  261. *
  262. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  263. // そのうちこのコードはいらなくなるはず
  264. if (!userData.isEmailSet()) {
  265. return res.redirect('/me');
  266. }
  267. */
  268. if (req.method == 'POST' && req.form.isValid) {
  269. var newPassword = passwordForm.newPassword;
  270. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  271. var oldPassword = passwordForm.oldPassword;
  272. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  273. req.form.errors.push('Wrong current password');
  274. return res.render('me/password', {
  275. });
  276. }
  277. // check password confirm
  278. if (newPassword != newPasswordConfirm) {
  279. req.form.errors.push('Failed to verify passwords');
  280. }
  281. else {
  282. userData.updatePassword(newPassword, function(err, userData) {
  283. if (err) {
  284. for (var e in err.errors) {
  285. if (err.errors.hasOwnProperty(e)) {
  286. req.form.errors.push(err.errors[e].message);
  287. }
  288. }
  289. return res.render('me/password', {});
  290. }
  291. req.flash('successMessage', 'Password updated');
  292. return res.redirect('/me/password');
  293. });
  294. }
  295. }
  296. else { // method GET
  297. return res.render('me/password', {
  298. });
  299. }
  300. };
  301. actions.apiToken = function(req, res) {
  302. var apiTokenForm = req.body.apiTokenForm;
  303. var userData = req.user;
  304. if (req.method == 'POST' && req.form.isValid) {
  305. userData.updateApiToken()
  306. .then(function(userData) {
  307. req.flash('successMessage', 'API Token updated');
  308. return res.redirect('/me/apiToken');
  309. })
  310. .catch(function(err) {
  311. //req.flash('successMessage',);
  312. req.form.errors.push('Failed to update API Token');
  313. return res.render('me/api_token', {
  314. });
  315. });
  316. }
  317. else {
  318. return res.render('me/api_token', {
  319. });
  320. }
  321. };
  322. actions.updates = function(req, res) {
  323. res.render('me/update', {
  324. });
  325. };
  326. actions.deletePicture = function(req, res) {
  327. // TODO: S3 からの削除
  328. req.user.deleteImage(function(err, data) {
  329. req.flash('successMessage', 'Deleted profile picture');
  330. res.redirect('/me');
  331. });
  332. };
  333. actions.authGoogle = function(req, res) {
  334. var googleAuth = require('../util/googleAuth')(config);
  335. var userData = req.user;
  336. var toDisconnect = req.body.disconnectGoogle ? true : false;
  337. var toConnect = req.body.connectGoogle ? true : false;
  338. if (toDisconnect) {
  339. userData.deleteGoogleId(function(err, userData) {
  340. req.flash('successMessage', 'Disconnected from Google account');
  341. return res.redirect('/me');
  342. });
  343. }
  344. else if (toConnect) {
  345. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  346. if (err) {
  347. // TODO
  348. }
  349. req.session.googleCallbackAction = '/me/auth/google/callback';
  350. return res.redirect(redirectUrl);
  351. });
  352. }
  353. else {
  354. return res.redirect('/me');
  355. }
  356. };
  357. actions.authGoogleCallback = function(req, res) {
  358. var googleAuth = require('../util/googleAuth')(config);
  359. var userData = req.user;
  360. googleAuth.handleCallback(req, function(err, tokenInfo) {
  361. if (err) {
  362. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  363. return res.redirect('/me'); // TODO Handling
  364. }
  365. var googleId = tokenInfo.user_id;
  366. var googleEmail = tokenInfo.email;
  367. if (!User.isEmailValid(googleEmail)) {
  368. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  369. return res.redirect('/me');
  370. }
  371. User.findUserByGoogleId(googleId, function(err, googleUser) {
  372. if (!err && googleUser) {
  373. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  374. return res.redirect('/me');
  375. }
  376. else {
  377. userData.updateGoogleId(googleId, function(err, userData) {
  378. if (err) {
  379. debug('Failed to updateGoogleId', err);
  380. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  381. return res.redirect('/me');
  382. }
  383. // TODO if err
  384. req.flash('successMessage', 'Connected with Google');
  385. return res.redirect('/me');
  386. });
  387. }
  388. });
  389. });
  390. };
  391. return actions;
  392. };