me.js 8.8 KB

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