me.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.disassociate = function(req, res) {
  157. const userData = req.user;
  158. const redirectWithFlash = (type, msg) => {
  159. req.flash(type, msg);
  160. return res.redirect('/me/external-accounts');
  161. }
  162. if (req.body == null) {
  163. redirectWithFlash('errorMessage', 'Invalid form.');
  164. }
  165. // make sure password set or this user has two or more ExternalAccounts
  166. new Promise((resolve, reject) => {
  167. if (userData.password != null) {
  168. resolve(true);
  169. }
  170. else {
  171. ExternalAccount.count({user: userData})
  172. .then((count) => {
  173. resolve(count > 1)
  174. });
  175. }
  176. })
  177. .then((isDisassociatable) => {
  178. if (!isDisassociatable) {
  179. let e = new Error();
  180. e.name = 'couldntDisassociateError';
  181. throw e;
  182. }
  183. const providerType = req.body.providerType;
  184. const accountId = req.body.accountId;
  185. return ExternalAccount.findOneAndRemove({providerType, accountId, user: userData});
  186. })
  187. .then((account) => {
  188. if (account == null) {
  189. return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
  190. }
  191. else {
  192. return redirectWithFlash('successMessage', 'Successfully disassociated.');
  193. }
  194. })
  195. .catch((err) => {
  196. if (err) {
  197. if (err.name == 'couldntDisassociateError') {
  198. return redirectWithFlash('couldntDisassociateError', true);
  199. }
  200. else {
  201. return redirectWithFlash('errorMessage', err.message);
  202. }
  203. }
  204. });
  205. }
  206. actions.externalAccounts.associateLdap = function(req, res) {
  207. const passport = require('passport');
  208. const passportService = crowi.passportService;
  209. const redirectWithFlash = (type, msg) => {
  210. req.flash(type, msg);
  211. return res.redirect('/me/external-accounts');
  212. }
  213. if (!passportService.isLdapStrategySetup) {
  214. debug('LdapStrategy has not been set up');
  215. return redirectWithFlash('warning', 'LdapStrategy has not been set up');
  216. }
  217. const loginForm = req.body.loginForm;
  218. passport.authenticate('ldapauth', (err, user, info) => {
  219. if (res.headersSent) { // dirty hack -- 2017.09.25
  220. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  221. }
  222. if (err) { // DB Error
  223. console.log('LDAP Server Error: ', err);
  224. return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
  225. }
  226. if (info && info.message) {
  227. return redirectWithFlash('warningMessage', info.message);
  228. }
  229. if (user) {
  230. // create ExternalAccount
  231. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  232. const user = req.user;
  233. ExternalAccount.create({ providerType: 'ldap', accountId: ldapAccountId, user: user._id })
  234. .then(() => {
  235. return redirectWithFlash('successMessage', 'Successfully added.');
  236. })
  237. .catch((err) => {
  238. return redirectWithFlash('errorMessage', err.message);
  239. });
  240. }
  241. })(req, res, () => {});
  242. }
  243. actions.password = function(req, res) {
  244. var passwordForm = req.body.mePassword;
  245. var userData = req.user;
  246. /*
  247. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  248. *
  249. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  250. // そのうちこのコードはいらなくなるはず
  251. if (!userData.isEmailSet()) {
  252. return res.redirect('/me');
  253. }
  254. */
  255. if (req.method == 'POST' && req.form.isValid) {
  256. var newPassword = passwordForm.newPassword;
  257. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  258. var oldPassword = passwordForm.oldPassword;
  259. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  260. req.form.errors.push('Wrong current password');
  261. return res.render('me/password', {
  262. });
  263. }
  264. // check password confirm
  265. if (newPassword != newPasswordConfirm) {
  266. req.form.errors.push('Failed to verify passwords');
  267. } else {
  268. userData.updatePassword(newPassword, function(err, userData) {
  269. if (err) {
  270. for (var e in err.errors) {
  271. if (err.errors.hasOwnProperty(e)) {
  272. req.form.errors.push(err.errors[e].message);
  273. }
  274. }
  275. return res.render('me/password', {});
  276. }
  277. req.flash('successMessage', 'Password updated');
  278. return res.redirect('/me/password');
  279. });
  280. }
  281. } else { // method GET
  282. return res.render('me/password', {
  283. });
  284. }
  285. };
  286. actions.apiToken = function(req, res) {
  287. var apiTokenForm = req.body.apiTokenForm;
  288. var userData = req.user;
  289. if (req.method == 'POST' && req.form.isValid) {
  290. userData.updateApiToken()
  291. .then(function(userData) {
  292. req.flash('successMessage', 'API Token updated');
  293. return res.redirect('/me/apiToken');
  294. })
  295. .catch(function(err) {
  296. //req.flash('successMessage',);
  297. req.form.errors.push('Failed to update API Token');
  298. return res.render('me/api_token', {
  299. });
  300. });
  301. } else {
  302. return res.render('me/api_token', {
  303. });
  304. }
  305. };
  306. actions.updates = function(req, res) {
  307. res.render('me/update', {
  308. });
  309. };
  310. actions.deletePicture = function(req, res) {
  311. // TODO: S3 からの削除
  312. req.user.deleteImage(function(err, data) {
  313. req.flash('successMessage', 'Deleted profile picture');
  314. res.redirect('/me');
  315. });
  316. };
  317. actions.authGoogle = function(req, res) {
  318. var googleAuth = require('../util/googleAuth')(config);
  319. var userData = req.user;
  320. var toDisconnect = req.body.disconnectGoogle ? true : false;
  321. var toConnect = req.body.connectGoogle ? true : false;
  322. if (toDisconnect) {
  323. userData.deleteGoogleId(function(err, userData) {
  324. req.flash('successMessage', 'Disconnected from Google account');
  325. return res.redirect('/me');
  326. });
  327. } else if (toConnect) {
  328. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  329. if (err) {
  330. // TODO
  331. }
  332. req.session.googleCallbackAction = '/me/auth/google/callback';
  333. return res.redirect(redirectUrl);
  334. });
  335. } else {
  336. return res.redirect('/me');
  337. }
  338. };
  339. actions.authGoogleCallback = function(req, res) {
  340. var googleAuth = require('../util/googleAuth')(config);
  341. var userData = req.user;
  342. googleAuth.handleCallback(req, function(err, tokenInfo) {
  343. if (err) {
  344. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  345. return res.redirect('/me'); // TODO Handling
  346. }
  347. var googleId = tokenInfo.user_id;
  348. var googleEmail = tokenInfo.email;
  349. if (!User.isEmailValid(googleEmail)) {
  350. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  351. return res.redirect('/me');
  352. }
  353. User.findUserByGoogleId(googleId, function(err, googleUser) {
  354. if (!err && googleUser) {
  355. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  356. return res.redirect('/me');
  357. } else {
  358. userData.updateGoogleId(googleId, function(err, userData) {
  359. if (err) {
  360. debug('Failed to updateGoogleId', err);
  361. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  362. return res.redirect('/me');
  363. }
  364. // TODO if err
  365. req.flash('successMessage', 'Connected with Google');
  366. return res.redirect('/me');
  367. });
  368. }
  369. });
  370. });
  371. };
  372. return actions;
  373. };