me.js 10 KB

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