me.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. api.externalAccounts = {}
  244. api.externalAccounts.testAssociateLdap = (req, res) => {
  245. const passport = require('passport');
  246. const passportService = crowi.passportService;
  247. if (!passportService.isLdapStrategySetup) {
  248. debug('LdapStrategy has not been set up');
  249. return res.json({
  250. status: 'warning',
  251. message: 'LdapStrategy has not been set up',
  252. });
  253. }
  254. const loginForm = req.body.loginForm;
  255. passport.authenticate('ldapauth', (err, user, info) => {
  256. if (res.headersSent) { // dirty hack -- 2017.09.25
  257. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  258. }
  259. if (err) { // DB Error
  260. console.log('LDAP Server Error: ', err);
  261. return res.json({
  262. status: 'warning',
  263. message: 'LDAP Server Error occured.',
  264. });
  265. }
  266. if (info && info.message) {
  267. return res.json({
  268. status: 'warning',
  269. message: info.message,
  270. });
  271. }
  272. if (user) {
  273. return res.json({
  274. status: 'success',
  275. message: 'Successfully authenticated.',
  276. });
  277. }
  278. })(req, res, () => {});
  279. }
  280. actions.password = function(req, res) {
  281. var passwordForm = req.body.mePassword;
  282. var userData = req.user;
  283. /*
  284. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  285. *
  286. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  287. // そのうちこのコードはいらなくなるはず
  288. if (!userData.isEmailSet()) {
  289. return res.redirect('/me');
  290. }
  291. */
  292. if (req.method == 'POST' && req.form.isValid) {
  293. var newPassword = passwordForm.newPassword;
  294. var newPasswordConfirm = passwordForm.newPasswordConfirm;
  295. var oldPassword = passwordForm.oldPassword;
  296. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  297. req.form.errors.push('Wrong current password');
  298. return res.render('me/password', {
  299. });
  300. }
  301. // check password confirm
  302. if (newPassword != newPasswordConfirm) {
  303. req.form.errors.push('Failed to verify passwords');
  304. } else {
  305. userData.updatePassword(newPassword, function(err, userData) {
  306. if (err) {
  307. for (var e in err.errors) {
  308. if (err.errors.hasOwnProperty(e)) {
  309. req.form.errors.push(err.errors[e].message);
  310. }
  311. }
  312. return res.render('me/password', {});
  313. }
  314. req.flash('successMessage', 'Password updated');
  315. return res.redirect('/me/password');
  316. });
  317. }
  318. } else { // method GET
  319. return res.render('me/password', {
  320. });
  321. }
  322. };
  323. actions.apiToken = function(req, res) {
  324. var apiTokenForm = req.body.apiTokenForm;
  325. var userData = req.user;
  326. if (req.method == 'POST' && req.form.isValid) {
  327. userData.updateApiToken()
  328. .then(function(userData) {
  329. req.flash('successMessage', 'API Token updated');
  330. return res.redirect('/me/apiToken');
  331. })
  332. .catch(function(err) {
  333. //req.flash('successMessage',);
  334. req.form.errors.push('Failed to update API Token');
  335. return res.render('me/api_token', {
  336. });
  337. });
  338. } else {
  339. return res.render('me/api_token', {
  340. });
  341. }
  342. };
  343. actions.updates = function(req, res) {
  344. res.render('me/update', {
  345. });
  346. };
  347. actions.deletePicture = function(req, res) {
  348. // TODO: S3 からの削除
  349. req.user.deleteImage(function(err, data) {
  350. req.flash('successMessage', 'Deleted profile picture');
  351. res.redirect('/me');
  352. });
  353. };
  354. actions.authGoogle = function(req, res) {
  355. var googleAuth = require('../util/googleAuth')(config);
  356. var userData = req.user;
  357. var toDisconnect = req.body.disconnectGoogle ? true : false;
  358. var toConnect = req.body.connectGoogle ? true : false;
  359. if (toDisconnect) {
  360. userData.deleteGoogleId(function(err, userData) {
  361. req.flash('successMessage', 'Disconnected from Google account');
  362. return res.redirect('/me');
  363. });
  364. } else if (toConnect) {
  365. googleAuth.createAuthUrl(req, function(err, redirectUrl) {
  366. if (err) {
  367. // TODO
  368. }
  369. req.session.googleCallbackAction = '/me/auth/google/callback';
  370. return res.redirect(redirectUrl);
  371. });
  372. } else {
  373. return res.redirect('/me');
  374. }
  375. };
  376. actions.authGoogleCallback = function(req, res) {
  377. var googleAuth = require('../util/googleAuth')(config);
  378. var userData = req.user;
  379. googleAuth.handleCallback(req, function(err, tokenInfo) {
  380. if (err) {
  381. req.flash('warningMessage.auth.google', err.message); // FIXME: show library error message directly
  382. return res.redirect('/me'); // TODO Handling
  383. }
  384. var googleId = tokenInfo.user_id;
  385. var googleEmail = tokenInfo.email;
  386. if (!User.isEmailValid(googleEmail)) {
  387. req.flash('warningMessage.auth.google', 'You can\'t connect with this Google\'s account');
  388. return res.redirect('/me');
  389. }
  390. User.findUserByGoogleId(googleId, function(err, googleUser) {
  391. if (!err && googleUser) {
  392. req.flash('warningMessage.auth.google', 'This Google\'s account is connected by another user');
  393. return res.redirect('/me');
  394. } else {
  395. userData.updateGoogleId(googleId, function(err, userData) {
  396. if (err) {
  397. debug('Failed to updateGoogleId', err);
  398. req.flash('warningMessage.auth.google', 'Failed to connect Google Account');
  399. return res.redirect('/me');
  400. }
  401. // TODO if err
  402. req.flash('successMessage', 'Connected with Google');
  403. return res.redirect('/me');
  404. });
  405. }
  406. });
  407. });
  408. };
  409. return actions;
  410. };