me.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. if (!User.isEmailValid(email)) {
  75. req.form.errors.push('You can\'t update to that email address');
  76. return res.render('me/index', {});
  77. }
  78. User.findOneAndUpdate(
  79. { email: userData.email }, // query
  80. { name, email, lang }, // updating data
  81. { runValidators: true, context: 'query' }, // for validation
  82. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  83. (err) => {
  84. if (err) {
  85. Object.keys(err.errors).forEach((e) => {
  86. req.form.errors.push(err.errors[e].message);
  87. });
  88. return res.render('me/index', {});
  89. }
  90. req.i18n.changeLanguage(lang);
  91. req.flash('successMessage', req.t('Updated'));
  92. return res.redirect('/me');
  93. });
  94. } else { // method GET
  95. /// そのうちこのコードはいらなくなるはず
  96. if (!userData.isEmailSet()) {
  97. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  98. }
  99. return res.render('me/index', {
  100. });
  101. }
  102. };
  103. actions.imagetype = function(req,res) {
  104. if (req.method !== 'POST') {
  105. // do nothing
  106. return;
  107. }
  108. else if (!req.form.isValid) {
  109. req.flash('errorMessage', req.form.errors.join('\n'));
  110. return;
  111. }
  112. var imagetypeForm = req.body.imagetypeForm;
  113. var userData = req.user;
  114. var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  115. userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
  116. if (err) {
  117. for (var e in err.errors) {
  118. if (err.errors.hasOwnProperty(e)) {
  119. req.form.errors.push(err.errors[e].message);
  120. }
  121. }
  122. return res.render('me/index', {});
  123. }
  124. req.flash('successMessage', req.t('Updated'));
  125. return res.redirect('/me');
  126. });
  127. }
  128. actions.password = function(req, res) {
  129. var passwordForm = req.body.mePassword;
  130. var userData = req.user;
  131. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  132. // そのうちこのコードはいらなくなるはず
  133. if (!userData.isEmailSet()) {
  134. return res.redirect('/me');
  135. }
  136. if (req.method == 'POST' && req.form.isValid) {
  137. var newPassword = passwordForm.newPassword;
  138. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  139. var oldPassword = passwordForm.oldPassword;
  140. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  141. req.form.errors.push('Wrong current password');
  142. return res.render('me/password', {
  143. });
  144. }
  145. // check password confirm
  146. if (newPassword != newPasswordConfirm) {
  147. req.form.errors.push('Failed to verify passwords');
  148. } else {
  149. userData.updatePassword(newPassword, function(err, userData) {
  150. if (err) {
  151. for (var e in err.errors) {
  152. if (err.errors.hasOwnProperty(e)) {
  153. req.form.errors.push(err.errors[e].message);
  154. }
  155. }
  156. return res.render('me/password', {});
  157. }
  158. req.flash('successMessage', 'Password updated');
  159. return res.redirect('/me/password');
  160. });
  161. }
  162. } else { // method GET
  163. return res.render('me/password', {
  164. });
  165. }
  166. };
  167. actions.apiToken = function(req, res) {
  168. var apiTokenForm = req.body.apiTokenForm;
  169. var userData = req.user;
  170. if (req.method == 'POST' && req.form.isValid) {
  171. userData.updateApiToken()
  172. .then(function(userData) {
  173. req.flash('successMessage', 'API Token updated');
  174. return res.redirect('/me/apiToken');
  175. })
  176. .catch(function(err) {
  177. //req.flash('successMessage',);
  178. req.form.errors.push('Failed to update API Token');
  179. return res.render('me/api_token', {
  180. });
  181. });
  182. } else {
  183. return res.render('me/api_token', {
  184. });
  185. }
  186. };
  187. actions.updates = function(req, res) {
  188. res.render('me/update', {
  189. });
  190. };
  191. actions.deletePicture = function(req, res) {
  192. // TODO: S3 からの削除
  193. req.user.deleteImage(function(err, data) {
  194. req.flash('successMessage', 'Deleted profile picture');
  195. res.redirect('/me');
  196. });
  197. };
  198. actions.authGoogle = function(req, res) {
  199. var googleAuth = require('../util/googleAuth')(config);
  200. var userData = req.user;
  201. var toDisconnect = req.body.disconnectGoogle ? true : false;
  202. var toConnect = req.body.connectGoogle ? true : false;
  203. if (toDisconnect) {
  204. userData.deleteGoogleId(function(err, userData) {
  205. req.flash('successMessage', 'Disconnected from Google account');
  206. return res.redirect('/me');
  207. });
  208. } else if (toConnect) {
  209. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  210. if (err) {
  211. // TODO
  212. }
  213. req.session.googleCallbackAction = '/me/auth/google/callback';
  214. return res.redirect(redirectUrl);
  215. });
  216. } else {
  217. return res.redirect('/me');
  218. }
  219. };
  220. actions.authGoogleCallback = function(req, res) {
  221. var googleAuth = require('../util/googleAuth')(config);
  222. var userData = req.user;
  223. googleAuth.handleCallback(req, function(err, tokenInfo) {
  224. if (err) {
  225. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  226. return res.redirect('/me'); // TODO Handling
  227. }
  228. var googleId = tokenInfo.user_id;
  229. var googleEmail = tokenInfo.email;
  230. if (!User.isEmailValid(googleEmail)) {
  231. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  232. return res.redirect('/me');
  233. }
  234. User.findUserByGoogleId(googleId, function(err, googleUser) {
  235. if (!err && googleUser) {
  236. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  237. return res.redirect('/me');
  238. } else {
  239. userData.updateGoogleId(googleId, function(err, userData) {
  240. if (err) {
  241. debug('Failed to updateGoogleId', err);
  242. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  243. return res.redirect('/me');
  244. }
  245. // TODO if err
  246. req.flash('successMessage', 'Connected with Google');
  247. return res.redirect('/me');
  248. });
  249. }
  250. });
  251. });
  252. };
  253. return actions;
  254. };