me.js 11 KB

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