me.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('crowi:routes:me')
  4. , fs = require('fs')
  5. , models = crowi.models
  6. , config = crowi.getConfig()
  7. , Page = models.Page
  8. , User = models.User
  9. , Revision = models.Revision
  10. //, pluginService = require('../service/plugin')
  11. , actions = {}
  12. , api = {}
  13. ;
  14. actions.api = api;
  15. api.uploadPicture = function (req, res) {
  16. var fileUploader = require('../util/fileUploader')(crowi, app);
  17. //var storagePlugin = new pluginService('storage');
  18. //var storage = require('../service/storage').StorageService(config);
  19. var tmpFile = req.file || null;
  20. if (!tmpFile) {
  21. return res.json({
  22. 'status': false,
  23. 'message': 'File type error.'
  24. });
  25. }
  26. var tmpPath = tmpFile.path;
  27. var filePath = User.createUserPictureFilePath(req.user, tmpFile.filename + tmpFile.originalname);
  28. var acceptableFileType = /image\/.+/;
  29. if (!tmpFile.mimetype.match(acceptableFileType)) {
  30. return res.json({
  31. 'status': false,
  32. 'message': 'File type error. Only image files is allowed to set as user picture.',
  33. });
  34. }
  35. //debug('tmpFile Is', tmpFile, tmpFile.constructor, tmpFile.prototype);
  36. //var imageUrl = storage.writeSync(storage.tofs(tmpFile), filePath, {mime: tmpFile.mimetype});
  37. //return return res.json({
  38. // 'status': true,
  39. // 'url': imageUrl,
  40. // 'message': '',
  41. //});
  42. var tmpFileStream = fs.createReadStream(tmpPath, {flags: 'r', encoding: null, fd: null, mode: '0666', autoClose: true });
  43. fileUploader.uploadFile(filePath, tmpFile.mimetype, tmpFileStream, {})
  44. .then(function(data) {
  45. var imageUrl = fileUploader.generateUrl(filePath);
  46. req.user.updateImage(imageUrl, function(err, data) {
  47. fs.unlink(tmpPath, function (err) {
  48. // エラー自体は無視
  49. if (err) {
  50. debug('Error while deleting tmp file.', err);
  51. }
  52. return res.json({
  53. 'status': true,
  54. 'url': imageUrl,
  55. 'message': '',
  56. });
  57. });
  58. });
  59. }).catch(function (err) {
  60. debug('Uploading error', err);
  61. return res.json({
  62. 'status': false,
  63. 'message': 'Error while uploading to ',
  64. });
  65. });
  66. };
  67. actions.index = function(req, res) {
  68. var userForm = req.body.userForm;
  69. var userData = req.user;
  70. if (req.method == 'POST' && req.form.isValid) {
  71. var name = userForm.name;
  72. var email = userForm.email;
  73. var lang= userForm.lang;
  74. /*
  75. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  76. *
  77. if (!User.isEmailValid(email)) {
  78. req.form.errors.push('You can\'t update to that email address');
  79. return res.render('me/index', {});
  80. }
  81. */
  82. User.findOneAndUpdate(
  83. { email: userData.email }, // query
  84. { name, email, lang }, // updating data
  85. { runValidators: true, context: 'query' }, // for validation
  86. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  87. (err) => {
  88. if (err) {
  89. Object.keys(err.errors).forEach((e) => {
  90. req.form.errors.push(err.errors[e].message);
  91. });
  92. return res.render('me/index', {});
  93. }
  94. req.i18n.changeLanguage(lang);
  95. req.flash('successMessage', req.t('Updated'));
  96. return res.redirect('/me');
  97. });
  98. } else { // method GET
  99. /*
  100. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  101. *
  102. /// そのうちこのコードはいらなくなるはず
  103. if (!userData.isEmailSet()) {
  104. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  105. }
  106. */
  107. return res.render('me/index', {
  108. });
  109. }
  110. };
  111. actions.imagetype = function(req,res) {
  112. if (req.method !== 'POST') {
  113. // do nothing
  114. return;
  115. }
  116. else if (!req.form.isValid) {
  117. req.flash('errorMessage', req.form.errors.join('\n'));
  118. return;
  119. }
  120. var imagetypeForm = req.body.imagetypeForm;
  121. var userData = req.user;
  122. var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  123. userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
  124. if (err) {
  125. for (var e in err.errors) {
  126. if (err.errors.hasOwnProperty(e)) {
  127. req.form.errors.push(err.errors[e].message);
  128. }
  129. }
  130. return res.render('me/index', {});
  131. }
  132. req.flash('successMessage', req.t('Updated'));
  133. return res.redirect('/me');
  134. });
  135. }
  136. actions.password = function(req, res) {
  137. var passwordForm = req.body.mePassword;
  138. var userData = req.user;
  139. /*
  140. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  141. *
  142. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  143. // そのうちこのコードはいらなくなるはず
  144. if (!userData.isEmailSet()) {
  145. return res.redirect('/me');
  146. }
  147. */
  148. if (req.method == 'POST' && req.form.isValid) {
  149. var newPassword = passwordForm.newPassword;
  150. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  151. var oldPassword = passwordForm.oldPassword;
  152. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  153. req.form.errors.push('Wrong current password');
  154. return res.render('me/password', {
  155. });
  156. }
  157. // check password confirm
  158. if (newPassword != newPasswordConfirm) {
  159. req.form.errors.push('Failed to verify passwords');
  160. } else {
  161. userData.updatePassword(newPassword, function(err, userData) {
  162. if (err) {
  163. for (var e in err.errors) {
  164. if (err.errors.hasOwnProperty(e)) {
  165. req.form.errors.push(err.errors[e].message);
  166. }
  167. }
  168. return res.render('me/password', {});
  169. }
  170. req.flash('successMessage', 'Password updated');
  171. return res.redirect('/me/password');
  172. });
  173. }
  174. } else { // method GET
  175. return res.render('me/password', {
  176. });
  177. }
  178. };
  179. actions.apiToken = function(req, res) {
  180. var apiTokenForm = req.body.apiTokenForm;
  181. var userData = req.user;
  182. if (req.method == 'POST' && req.form.isValid) {
  183. userData.updateApiToken()
  184. .then(function(userData) {
  185. req.flash('successMessage', 'API Token updated');
  186. return res.redirect('/me/apiToken');
  187. })
  188. .catch(function(err) {
  189. //req.flash('successMessage',);
  190. req.form.errors.push('Failed to update API Token');
  191. return res.render('me/api_token', {
  192. });
  193. });
  194. } else {
  195. return res.render('me/api_token', {
  196. });
  197. }
  198. };
  199. actions.updates = function(req, res) {
  200. res.render('me/update', {
  201. });
  202. };
  203. actions.deletePicture = function(req, res) {
  204. // TODO: S3 からの削除
  205. req.user.deleteImage(function(err, data) {
  206. req.flash('successMessage', 'Deleted profile picture');
  207. res.redirect('/me');
  208. });
  209. };
  210. actions.authGoogle = function(req, res) {
  211. var googleAuth = require('../util/googleAuth')(config);
  212. var userData = req.user;
  213. var toDisconnect = req.body.disconnectGoogle ? true : false;
  214. var toConnect = req.body.connectGoogle ? true : false;
  215. if (toDisconnect) {
  216. userData.deleteGoogleId(function(err, userData) {
  217. req.flash('successMessage', 'Disconnected from Google account');
  218. return res.redirect('/me');
  219. });
  220. } else if (toConnect) {
  221. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  222. if (err) {
  223. // TODO
  224. }
  225. req.session.googleCallbackAction = '/me/auth/google/callback';
  226. return res.redirect(redirectUrl);
  227. });
  228. } else {
  229. return res.redirect('/me');
  230. }
  231. };
  232. actions.authGoogleCallback = function(req, res) {
  233. var googleAuth = require('../util/googleAuth')(config);
  234. var userData = req.user;
  235. googleAuth.handleCallback(req, function(err, tokenInfo) {
  236. if (err) {
  237. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  238. return res.redirect('/me'); // TODO Handling
  239. }
  240. var googleId = tokenInfo.user_id;
  241. var googleEmail = tokenInfo.email;
  242. if (!User.isEmailValid(googleEmail)) {
  243. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  244. return res.redirect('/me');
  245. }
  246. User.findUserByGoogleId(googleId, function(err, googleUser) {
  247. if (!err && googleUser) {
  248. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  249. return res.redirect('/me');
  250. } else {
  251. userData.updateGoogleId(googleId, function(err, userData) {
  252. if (err) {
  253. debug('Failed to updateGoogleId', err);
  254. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  255. return res.redirect('/me');
  256. }
  257. // TODO if err
  258. req.flash('successMessage', 'Connected with Google');
  259. return res.redirect('/me');
  260. });
  261. }
  262. });
  263. });
  264. };
  265. return actions;
  266. };