me.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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.files.userPicture || 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.name);
  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. if (!User.isEmailValid(email)) {
  74. req.form.errors.push('このメールアドレスは登録できません。(ホワイトリストなどを確認してください)');
  75. return res.render('me/index', {});
  76. }
  77. userData.update(name, email, function(err, userData) {
  78. if (err) {
  79. for (var e in err.errors) {
  80. if (err.errors.hasOwnProperty(e)) {
  81. req.form.errors.push(err.errors[e].message);
  82. }
  83. }
  84. return res.render('me/index', {});
  85. }
  86. req.flash('successMessage', '更新しました');
  87. return res.redirect('/me');
  88. });
  89. } else { // method GET
  90. /// そのうちこのコードはいらなくなるはず
  91. if (!userData.isEmailSet()) {
  92. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  93. }
  94. return res.render('me/index', {
  95. });
  96. }
  97. };
  98. actions.password = function(req, res) {
  99. var passwordForm = req.body.mePassword;
  100. var userData = req.user;
  101. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  102. // そのうちこのコードはいらなくなるはず
  103. if (!userData.isEmailSet()) {
  104. return res.redirect('/me');
  105. }
  106. if (req.method == 'POST' && req.form.isValid) {
  107. var newPassword = passwordForm.newPassword;
  108. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  109. var oldPassword = passwordForm.oldPassword;
  110. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  111. req.form.errors.push('現在のパスワードが違います。');
  112. return res.render('me/password', {
  113. });
  114. }
  115. // check password confirm
  116. if (newPassword != newPasswordConfirm) {
  117. req.form.errors.push('確認用パスワードが一致しません');
  118. } else {
  119. userData.updatePassword(newPassword, function(err, userData) {
  120. if (err) {
  121. for (var e in err.errors) {
  122. if (err.errors.hasOwnProperty(e)) {
  123. req.form.errors.push(err.errors[e].message);
  124. }
  125. }
  126. return res.render('me/password', {});
  127. }
  128. req.flash('successMessage', 'パスワードを変更しました');
  129. return res.redirect('/me/password');
  130. });
  131. }
  132. } else { // method GET
  133. return res.render('me/password', {
  134. });
  135. }
  136. };
  137. actions.apiToken = function(req, res) {
  138. var apiTokenForm = req.body.apiTokenForm;
  139. var userData = req.user;
  140. if (req.method == 'POST' && req.form.isValid) {
  141. userData.updateApiToken()
  142. .then(function(userData) {
  143. req.flash('successMessage', 'API Token を更新しました');
  144. return res.redirect('/me/apiToken');
  145. })
  146. .catch(function(err) {
  147. //req.flash('successMessage',);
  148. req.form.errors.push('API Token の更新に失敗しました');
  149. return res.render('me/api_token', {
  150. });
  151. });
  152. } else {
  153. return res.render('me/api_token', {
  154. });
  155. }
  156. };
  157. actions.updates = function(req, res) {
  158. res.render('me/update', {
  159. });
  160. };
  161. actions.deletePicture = function(req, res) {
  162. // TODO: S3 からの削除
  163. req.user.deleteImage(function(err, data) {
  164. req.flash('successMessage', 'プロフィール画像を削除しました');
  165. res.redirect('/me');
  166. });
  167. };
  168. actions.authGoogle = function(req, res) {
  169. var googleAuth = require('../util/googleAuth')(config);
  170. var userData = req.user;
  171. var toDisconnect = req.body.disconnectGoogle ? true : false;
  172. var toConnect = req.body.connectGoogle ? true : false;
  173. if (toDisconnect) {
  174. userData.deleteGoogleId(function(err, userData) {
  175. req.flash('successMessage', 'Googleコネクトを解除しました。');
  176. return res.redirect('/me');
  177. });
  178. } else if (toConnect) {
  179. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  180. if (err) {
  181. // TODO
  182. }
  183. req.session.googleCallbackAction = '/me/auth/google/callback';
  184. return res.redirect(redirectUrl);
  185. });
  186. } else {
  187. return res.redirect('/me');
  188. }
  189. };
  190. actions.authGoogleCallback = function(req, res) {
  191. var googleAuth = require('../util/googleAuth')(config);
  192. var userData = req.user;
  193. googleAuth.handleCallback(req, function(err, tokenInfo) {
  194. if (err) {
  195. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  196. return res.redirect('/me'); // TODO Handling
  197. }
  198. var googleId = tokenInfo.user_id;
  199. var googleEmail = tokenInfo.email;
  200. if (!User.isEmailValid(googleEmail)) {
  201. req.flash('warningMessage.auth.google', 'このメールアドレスのGoogleアカウントはコネクトできません。');
  202. return res.redirect('/me');
  203. }
  204. userData.updateGoogleId(googleId, function(err, userData) {
  205. if (err) {
  206. debug('Failed to updateGoogleId', err);
  207. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  208. return res.redirect('/me');
  209. }
  210. // TODO if err
  211. req.flash('successMessage', 'Googleコネクトを設定しました。');
  212. return res.redirect('/me');
  213. });
  214. });
  215. };
  216. return actions;
  217. };