me.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. , Page = models.Page
  8. , User = models.User
  9. , ExternalAccount = models.ExternalAccount
  10. , Revision = models.Revision
  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. actions.index = function(req, res) {
  69. var userForm = req.body.userForm;
  70. var userData = req.user;
  71. if (req.method == 'POST' && req.form.isValid) {
  72. var name = userForm.name;
  73. var email = userForm.email;
  74. var lang = userForm.lang;
  75. var isEmailPublished = userForm.isEmailPublished;
  76. /*
  77. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  78. *
  79. if (!User.isEmailValid(email)) {
  80. req.form.errors.push('You can\'t update to that email address');
  81. return res.render('me/index', {});
  82. }
  83. */
  84. User.findOneAndUpdate(
  85. { email: userData.email }, // query
  86. { name, email, lang, isEmailPublished }, // updating data
  87. { runValidators: true, context: 'query' }, // for validation
  88. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  89. (err) => {
  90. if (err) {
  91. Object.keys(err.errors).forEach((e) => {
  92. req.form.errors.push(err.errors[e].message);
  93. });
  94. return res.render('me/index', {});
  95. }
  96. req.i18n.changeLanguage(lang);
  97. req.flash('successMessage', req.t('Updated'));
  98. return res.redirect('/me');
  99. });
  100. }
  101. else { // method GET
  102. /*
  103. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  104. *
  105. /// そのうちこのコードはいらなくなるはず
  106. if (!userData.isEmailSet()) {
  107. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  108. }
  109. */
  110. return res.render('me/index', {
  111. });
  112. }
  113. };
  114. actions.imagetype = function(req, res) {
  115. if (req.method !== 'POST') {
  116. // do nothing
  117. return;
  118. }
  119. else if (!req.form.isValid) {
  120. req.flash('errorMessage', req.form.errors.join('\n'));
  121. return;
  122. }
  123. var imagetypeForm = req.body.imagetypeForm;
  124. var userData = req.user;
  125. var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  126. userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
  127. if (err) {
  128. for (var e in err.errors) {
  129. if (err.errors.hasOwnProperty(e)) {
  130. req.form.errors.push(err.errors[e].message);
  131. }
  132. }
  133. return res.render('me/index', {});
  134. }
  135. req.flash('successMessage', req.t('Updated'));
  136. return res.redirect('/me');
  137. });
  138. };
  139. actions.externalAccounts = {};
  140. actions.externalAccounts.list = function(req, res) {
  141. const userData = req.user;
  142. let renderVars = {};
  143. ExternalAccount.find({user: userData})
  144. .then((externalAccounts) => {
  145. renderVars.externalAccounts = externalAccounts;
  146. return;
  147. })
  148. .then(() => {
  149. if (req.method == 'POST' && req.form.isValid) {
  150. // TODO impl
  151. return res.render('me/external-accounts', renderVars);
  152. }
  153. else { // method GET
  154. return res.render('me/external-accounts', renderVars);
  155. }
  156. });
  157. };
  158. actions.externalAccounts.disassociate = function(req, res) {
  159. const userData = req.user;
  160. const redirectWithFlash = (type, msg) => {
  161. req.flash(type, msg);
  162. return res.redirect('/me/external-accounts');
  163. };
  164. if (req.body == null) {
  165. redirectWithFlash('errorMessage', 'Invalid form.');
  166. }
  167. // make sure password set or this user has two or more ExternalAccounts
  168. new Promise((resolve, reject) => {
  169. if (userData.password != null) {
  170. resolve(true);
  171. }
  172. else {
  173. ExternalAccount.count({user: userData})
  174. .then((count) => {
  175. resolve(count > 1);
  176. });
  177. }
  178. })
  179. .then((isDisassociatable) => {
  180. if (!isDisassociatable) {
  181. let e = new Error();
  182. e.name = 'couldntDisassociateError';
  183. throw e;
  184. }
  185. const providerType = req.body.providerType;
  186. const accountId = req.body.accountId;
  187. return ExternalAccount.findOneAndRemove({providerType, accountId, user: userData});
  188. })
  189. .then((account) => {
  190. if (account == null) {
  191. return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
  192. }
  193. else {
  194. return redirectWithFlash('successMessage', 'Successfully disassociated.');
  195. }
  196. })
  197. .catch((err) => {
  198. if (err) {
  199. if (err.name == 'couldntDisassociateError') {
  200. return redirectWithFlash('couldntDisassociateError', true);
  201. }
  202. else {
  203. return redirectWithFlash('errorMessage', err.message);
  204. }
  205. }
  206. });
  207. };
  208. actions.externalAccounts.associateLdap = function(req, res) {
  209. const passport = require('passport');
  210. const passportService = crowi.passportService;
  211. const redirectWithFlash = (type, msg) => {
  212. req.flash(type, msg);
  213. return res.redirect('/me/external-accounts');
  214. };
  215. if (!passportService.isLdapStrategySetup) {
  216. debug('LdapStrategy has not been set up');
  217. return redirectWithFlash('warning', 'LdapStrategy has not been set up');
  218. }
  219. const loginForm = req.body.loginForm;
  220. passport.authenticate('ldapauth', (err, user, info) => {
  221. if (res.headersSent) { // dirty hack -- 2017.09.25
  222. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  223. }
  224. if (err) { // DB Error
  225. console.log('LDAP Server Error: ', err);
  226. return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
  227. }
  228. if (info && info.message) {
  229. return redirectWithFlash('warningMessage', info.message);
  230. }
  231. if (user) {
  232. // create ExternalAccount
  233. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  234. const user = req.user;
  235. ExternalAccount.associate('ldap', ldapAccountId, user)
  236. .then(() => {
  237. return redirectWithFlash('successMessage', 'Successfully added.');
  238. })
  239. .catch((err) => {
  240. return redirectWithFlash('errorMessage', err.message);
  241. });
  242. }
  243. })(req, res, () => {});
  244. };
  245. actions.password = function(req, res) {
  246. var passwordForm = req.body.mePassword;
  247. var userData = req.user;
  248. /*
  249. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  250. *
  251. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  252. // そのうちこのコードはいらなくなるはず
  253. if (!userData.isEmailSet()) {
  254. return res.redirect('/me');
  255. }
  256. */
  257. if (req.method == 'POST' && req.form.isValid) {
  258. var newPassword = passwordForm.newPassword;
  259. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  260. var oldPassword = passwordForm.oldPassword;
  261. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  262. req.form.errors.push('Wrong current password');
  263. return res.render('me/password', {
  264. });
  265. }
  266. // check password confirm
  267. if (newPassword != newPasswordConfirm) {
  268. req.form.errors.push('Failed to verify passwords');
  269. }
  270. else {
  271. userData.updatePassword(newPassword, function(err, userData) {
  272. if (err) {
  273. for (var e in err.errors) {
  274. if (err.errors.hasOwnProperty(e)) {
  275. req.form.errors.push(err.errors[e].message);
  276. }
  277. }
  278. return res.render('me/password', {});
  279. }
  280. req.flash('successMessage', 'Password updated');
  281. return res.redirect('/me/password');
  282. });
  283. }
  284. }
  285. else { // method GET
  286. return res.render('me/password', {
  287. });
  288. }
  289. };
  290. actions.apiToken = function(req, res) {
  291. var apiTokenForm = req.body.apiTokenForm;
  292. var userData = req.user;
  293. if (req.method == 'POST' && req.form.isValid) {
  294. userData.updateApiToken()
  295. .then(function(userData) {
  296. req.flash('successMessage', 'API Token updated');
  297. return res.redirect('/me/apiToken');
  298. })
  299. .catch(function(err) {
  300. //req.flash('successMessage',);
  301. req.form.errors.push('Failed to update API Token');
  302. return res.render('me/api_token', {
  303. });
  304. });
  305. }
  306. else {
  307. return res.render('me/api_token', {
  308. });
  309. }
  310. };
  311. actions.updates = function(req, res) {
  312. res.render('me/update', {
  313. });
  314. };
  315. actions.deletePicture = function(req, res) {
  316. // TODO: S3 からの削除
  317. req.user.deleteImage(function(err, data) {
  318. req.flash('successMessage', 'Deleted profile picture');
  319. res.redirect('/me');
  320. });
  321. };
  322. actions.authGoogle = function(req, res) {
  323. var googleAuth = require('../util/googleAuth')(config);
  324. var userData = req.user;
  325. var toDisconnect = req.body.disconnectGoogle ? true : false;
  326. var toConnect = req.body.connectGoogle ? true : false;
  327. if (toDisconnect) {
  328. userData.deleteGoogleId(function(err, userData) {
  329. req.flash('successMessage', 'Disconnected from Google account');
  330. return res.redirect('/me');
  331. });
  332. }
  333. else if (toConnect) {
  334. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  335. if (err) {
  336. // TODO
  337. }
  338. req.session.googleCallbackAction = '/me/auth/google/callback';
  339. return res.redirect(redirectUrl);
  340. });
  341. }
  342. else {
  343. return res.redirect('/me');
  344. }
  345. };
  346. actions.authGoogleCallback = function(req, res) {
  347. var googleAuth = require('../util/googleAuth')(config);
  348. var userData = req.user;
  349. googleAuth.handleCallback(req, function(err, tokenInfo) {
  350. if (err) {
  351. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  352. return res.redirect('/me'); // TODO Handling
  353. }
  354. var googleId = tokenInfo.user_id;
  355. var googleEmail = tokenInfo.email;
  356. if (!User.isEmailValid(googleEmail)) {
  357. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  358. return res.redirect('/me');
  359. }
  360. User.findUserByGoogleId(googleId, function(err, googleUser) {
  361. if (!err && googleUser) {
  362. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  363. return res.redirect('/me');
  364. }
  365. else {
  366. userData.updateGoogleId(googleId, function(err, userData) {
  367. if (err) {
  368. debug('Failed to updateGoogleId', err);
  369. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  370. return res.redirect('/me');
  371. }
  372. // TODO if err
  373. req.flash('successMessage', 'Connected with Google');
  374. return res.redirect('/me');
  375. });
  376. }
  377. });
  378. });
  379. };
  380. return actions;
  381. };