me.js 8.4 KB

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