me.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. var isEmailPublished = userForm.isEmailPublished;
  76. /*
  77. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  78. *
  79. if (!User.isEmailValid(email)) {
  80. req.form.errors.push('You can\'t update to that email address');
  81. return res.render('me/index', {});
  82. }
  83. */
  84. User.findOneAndUpdate(
  85. { email: userData.email }, // query
  86. { name, email, lang, isEmailPublished }, // updating data
  87. { runValidators: true, context: 'query' }, // for validation
  88. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  89. (err) => {
  90. if (err) {
  91. Object.keys(err.errors).forEach((e) => {
  92. req.form.errors.push(err.errors[e].message);
  93. });
  94. return res.render('me/index', {});
  95. }
  96. req.i18n.changeLanguage(lang);
  97. req.flash('successMessage', req.t('Updated'));
  98. return res.redirect('/me');
  99. });
  100. } else { // method GET
  101. /*
  102. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  103. *
  104. /// そのうちこのコードはいらなくなるはず
  105. if (!userData.isEmailSet()) {
  106. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  107. }
  108. */
  109. return res.render('me/index', {
  110. });
  111. }
  112. };
  113. actions.imagetype = function(req,res) {
  114. if (req.method !== 'POST') {
  115. // do nothing
  116. return;
  117. }
  118. else if (!req.form.isValid) {
  119. req.flash('errorMessage', req.form.errors.join('\n'));
  120. return;
  121. }
  122. var imagetypeForm = req.body.imagetypeForm;
  123. var userData = req.user;
  124. var isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  125. userData.updateIsGravatarEnabled(isGravatarEnabled, function(err, userData) {
  126. if (err) {
  127. for (var e in err.errors) {
  128. if (err.errors.hasOwnProperty(e)) {
  129. req.form.errors.push(err.errors[e].message);
  130. }
  131. }
  132. return res.render('me/index', {});
  133. }
  134. req.flash('successMessage', req.t('Updated'));
  135. return res.redirect('/me');
  136. });
  137. }
  138. actions.externalAccounts = {};
  139. actions.externalAccounts.list = function(req, res) {
  140. const userData = req.user;
  141. let renderVars = {};
  142. ExternalAccount.find({user: userData})
  143. .then((externalAccounts) => {
  144. renderVars.externalAccounts = externalAccounts;
  145. return;
  146. })
  147. .then(() => {
  148. if (req.method == 'POST' && req.form.isValid) {
  149. // TODO impl
  150. return res.render('me/external-accounts', renderVars);
  151. }
  152. else { // method GET
  153. return res.render('me/external-accounts', renderVars);
  154. }
  155. });
  156. }
  157. actions.externalAccounts.disassociate = function(req, res) {
  158. const userData = req.user;
  159. const redirectWithFlash = (type, msg) => {
  160. req.flash(type, msg);
  161. return res.redirect('/me/external-accounts');
  162. }
  163. if (req.body == null) {
  164. redirectWithFlash('errorMessage', 'Invalid form.');
  165. }
  166. // make sure password set or this user has two or more ExternalAccounts
  167. new Promise((resolve, reject) => {
  168. if (userData.password != null) {
  169. resolve(true);
  170. }
  171. else {
  172. ExternalAccount.count({user: userData})
  173. .then((count) => {
  174. resolve(count > 1)
  175. });
  176. }
  177. })
  178. .then((isDisassociatable) => {
  179. if (!isDisassociatable) {
  180. let e = new Error();
  181. e.name = 'couldntDisassociateError';
  182. throw e;
  183. }
  184. const providerType = req.body.providerType;
  185. const accountId = req.body.accountId;
  186. return ExternalAccount.findOneAndRemove({providerType, accountId, user: userData});
  187. })
  188. .then((account) => {
  189. if (account == null) {
  190. return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
  191. }
  192. else {
  193. return redirectWithFlash('successMessage', 'Successfully disassociated.');
  194. }
  195. })
  196. .catch((err) => {
  197. if (err) {
  198. if (err.name == 'couldntDisassociateError') {
  199. return redirectWithFlash('couldntDisassociateError', true);
  200. }
  201. else {
  202. return redirectWithFlash('errorMessage', err.message);
  203. }
  204. }
  205. });
  206. }
  207. actions.externalAccounts.associateLdap = function(req, res) {
  208. const passport = require('passport');
  209. const passportService = crowi.passportService;
  210. const redirectWithFlash = (type, msg) => {
  211. req.flash(type, msg);
  212. return res.redirect('/me/external-accounts');
  213. }
  214. if (!passportService.isLdapStrategySetup) {
  215. debug('LdapStrategy has not been set up');
  216. return redirectWithFlash('warning', 'LdapStrategy has not been set up');
  217. }
  218. const loginForm = req.body.loginForm;
  219. passport.authenticate('ldapauth', (err, user, info) => {
  220. if (res.headersSent) { // dirty hack -- 2017.09.25
  221. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  222. }
  223. if (err) { // DB Error
  224. console.log('LDAP Server Error: ', err);
  225. return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
  226. }
  227. if (info && info.message) {
  228. return redirectWithFlash('warningMessage', info.message);
  229. }
  230. if (user) {
  231. // create ExternalAccount
  232. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  233. const user = req.user;
  234. ExternalAccount.create({ providerType: 'ldap', accountId: ldapAccountId, user: user._id })
  235. .then(() => {
  236. return redirectWithFlash('successMessage', 'Successfully added.');
  237. })
  238. .catch((err) => {
  239. return redirectWithFlash('errorMessage', err.message);
  240. });
  241. }
  242. })(req, res, () => {});
  243. }
  244. actions.password = function(req, res) {
  245. var passwordForm = req.body.mePassword;
  246. var userData = req.user;
  247. /*
  248. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  249. *
  250. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  251. // そのうちこのコードはいらなくなるはず
  252. if (!userData.isEmailSet()) {
  253. return res.redirect('/me');
  254. }
  255. */
  256. if (req.method == 'POST' && req.form.isValid) {
  257. var newPassword = passwordForm.newPassword;
  258. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  259. var oldPassword = passwordForm.oldPassword;
  260. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  261. req.form.errors.push('Wrong current password');
  262. return res.render('me/password', {
  263. });
  264. }
  265. // check password confirm
  266. if (newPassword != newPasswordConfirm) {
  267. req.form.errors.push('Failed to verify passwords');
  268. } else {
  269. userData.updatePassword(newPassword, function(err, userData) {
  270. if (err) {
  271. for (var e in err.errors) {
  272. if (err.errors.hasOwnProperty(e)) {
  273. req.form.errors.push(err.errors[e].message);
  274. }
  275. }
  276. return res.render('me/password', {});
  277. }
  278. req.flash('successMessage', 'Password updated');
  279. return res.redirect('/me/password');
  280. });
  281. }
  282. } else { // method GET
  283. return res.render('me/password', {
  284. });
  285. }
  286. };
  287. actions.apiToken = function(req, res) {
  288. var apiTokenForm = req.body.apiTokenForm;
  289. var userData = req.user;
  290. if (req.method == 'POST' && req.form.isValid) {
  291. userData.updateApiToken()
  292. .then(function(userData) {
  293. req.flash('successMessage', 'API Token updated');
  294. return res.redirect('/me/apiToken');
  295. })
  296. .catch(function(err) {
  297. //req.flash('successMessage',);
  298. req.form.errors.push('Failed to update API Token');
  299. return res.render('me/api_token', {
  300. });
  301. });
  302. } else {
  303. return res.render('me/api_token', {
  304. });
  305. }
  306. };
  307. actions.updates = function(req, res) {
  308. res.render('me/update', {
  309. });
  310. };
  311. actions.deletePicture = function(req, res) {
  312. // TODO: S3 からの削除
  313. req.user.deleteImage(function(err, data) {
  314. req.flash('successMessage', 'Deleted profile picture');
  315. res.redirect('/me');
  316. });
  317. };
  318. actions.authGoogle = function(req, res) {
  319. var googleAuth = require('../util/googleAuth')(config);
  320. var userData = req.user;
  321. var toDisconnect = req.body.disconnectGoogle ? true : false;
  322. var toConnect = req.body.connectGoogle ? true : false;
  323. if (toDisconnect) {
  324. userData.deleteGoogleId(function(err, userData) {
  325. req.flash('successMessage', 'Disconnected from Google account');
  326. return res.redirect('/me');
  327. });
  328. } else if (toConnect) {
  329. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  330. if (err) {
  331. // TODO
  332. }
  333. req.session.googleCallbackAction = '/me/auth/google/callback';
  334. return res.redirect(redirectUrl);
  335. });
  336. } else {
  337. return res.redirect('/me');
  338. }
  339. };
  340. actions.authGoogleCallback = function(req, res) {
  341. var googleAuth = require('../util/googleAuth')(config);
  342. var userData = req.user;
  343. googleAuth.handleCallback(req, function(err, tokenInfo) {
  344. if (err) {
  345. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  346. return res.redirect('/me'); // TODO Handling
  347. }
  348. var googleId = tokenInfo.user_id;
  349. var googleEmail = tokenInfo.email;
  350. if (!User.isEmailValid(googleEmail)) {
  351. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  352. return res.redirect('/me');
  353. }
  354. User.findUserByGoogleId(googleId, function(err, googleUser) {
  355. if (!err && googleUser) {
  356. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  357. return res.redirect('/me');
  358. } else {
  359. userData.updateGoogleId(googleId, function(err, userData) {
  360. if (err) {
  361. debug('Failed to updateGoogleId', err);
  362. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  363. return res.redirect('/me');
  364. }
  365. // TODO if err
  366. req.flash('successMessage', 'Connected with Google');
  367. return res.redirect('/me');
  368. });
  369. }
  370. });
  371. });
  372. };
  373. return actions;
  374. };