me.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. module.exports = function(crowi, app) {
  2. const debug = require('debug')('growi:routes:me');
  3. const logger = require('@alias/logger')('growi:routes:me');
  4. const models = crowi.models;
  5. const User = models.User;
  6. const UserGroupRelation = models.UserGroupRelation;
  7. const ExternalAccount = models.ExternalAccount;
  8. const ApiResponse = require('../util/apiResponse');
  9. // , pluginService = require('../service/plugin')
  10. const actions = {};
  11. const api = {};
  12. actions.api = api;
  13. /**
  14. * retrieve user-group-relation documents
  15. * @param {object} req
  16. * @param {object} res
  17. */
  18. api.userGroupRelations = function(req, res) {
  19. UserGroupRelation.findAllRelationForUser(req.user)
  20. .then((userGroupRelations) => {
  21. return res.json(ApiResponse.success({ userGroupRelations }));
  22. });
  23. };
  24. actions.index = function(req, res) {
  25. const userForm = req.body.userForm;
  26. const userData = req.user;
  27. if (req.method === 'POST' && req.form.isValid) {
  28. const name = userForm.name;
  29. const email = userForm.email;
  30. const lang = userForm.lang;
  31. const isEmailPublished = userForm.isEmailPublished;
  32. /*
  33. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  34. *
  35. if (!User.isEmailValid(email)) {
  36. req.form.errors.push('You can\'t update to that email address');
  37. return res.render('me/index', {});
  38. }
  39. */
  40. User.findOneAndUpdate(
  41. /* eslint-disable object-curly-newline */
  42. { email: userData.email }, // query
  43. { name, email, lang, isEmailPublished }, // updating data
  44. { runValidators: true, context: 'query' }, // for validation
  45. // see https://www.npmjs.com/package/mongoose-unique-validator#find--updates -- 2017.09.24 Yuki Takei
  46. /* eslint-enable object-curly-newline */
  47. (err) => {
  48. if (err) {
  49. Object.keys(err.errors).forEach((e) => {
  50. req.form.errors.push(err.errors[e].message);
  51. });
  52. return res.render('me/index', {});
  53. }
  54. req.i18n.changeLanguage(lang);
  55. req.flash('successMessage', req.t('Updated'));
  56. return res.redirect('/me');
  57. },
  58. );
  59. }
  60. else { // method GET
  61. /*
  62. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  63. *
  64. /// そのうちこのコードはいらなくなるはず
  65. if (!userData.isEmailSet()) {
  66. req.flash('warningMessage', 'メールアドレスが設定されている必要があります');
  67. }
  68. */
  69. return res.render('me/index', {
  70. });
  71. }
  72. };
  73. actions.imagetype = function(req, res) {
  74. if (req.method !== 'POST') {
  75. // do nothing
  76. return;
  77. }
  78. if (!req.form.isValid) {
  79. req.flash('errorMessage', req.form.errors.join('\n'));
  80. return;
  81. }
  82. const imagetypeForm = req.body.imagetypeForm;
  83. const userData = req.user;
  84. const isGravatarEnabled = imagetypeForm.isGravatarEnabled;
  85. userData.updateIsGravatarEnabled(isGravatarEnabled, (err, userData) => {
  86. if (err) {
  87. /* eslint-disable no-restricted-syntax, no-prototype-builtins */
  88. for (const e in err.errors) {
  89. if (err.errors.hasOwnProperty(e)) {
  90. req.form.errors.push(err.errors[e].message);
  91. }
  92. }
  93. /* eslint-enable no-restricted-syntax, no-prototype-builtins */
  94. return res.render('me/index', {});
  95. }
  96. req.flash('successMessage', req.t('Updated'));
  97. return res.redirect('/me');
  98. });
  99. };
  100. actions.externalAccounts = {};
  101. actions.externalAccounts.list = function(req, res) {
  102. const userData = req.user;
  103. const renderVars = {};
  104. ExternalAccount.find({ user: userData })
  105. .then((externalAccounts) => {
  106. renderVars.externalAccounts = externalAccounts;
  107. return;
  108. })
  109. .then(() => {
  110. if (req.method === 'POST' && req.form.isValid) {
  111. // TODO impl
  112. return res.render('me/external-accounts', renderVars);
  113. }
  114. // method GET
  115. return res.render('me/external-accounts', renderVars);
  116. });
  117. };
  118. actions.externalAccounts.disassociate = function(req, res) {
  119. const userData = req.user;
  120. const redirectWithFlash = (type, msg) => {
  121. req.flash(type, msg);
  122. return res.redirect('/me/external-accounts');
  123. };
  124. if (req.body == null) {
  125. redirectWithFlash('errorMessage', 'Invalid form.');
  126. }
  127. // make sure password set or this user has two or more ExternalAccounts
  128. new Promise((resolve, reject) => {
  129. if (userData.password != null) {
  130. resolve(true);
  131. }
  132. else {
  133. ExternalAccount.count({ user: userData })
  134. .then((count) => {
  135. resolve(count > 1);
  136. });
  137. }
  138. })
  139. .then((isDisassociatable) => {
  140. if (!isDisassociatable) {
  141. const e = new Error();
  142. e.name = 'couldntDisassociateError';
  143. throw e;
  144. }
  145. const providerType = req.body.providerType;
  146. const accountId = req.body.accountId;
  147. return ExternalAccount.findOneAndRemove({ providerType, accountId, user: userData });
  148. })
  149. .then((account) => {
  150. if (account == null) {
  151. return redirectWithFlash('errorMessage', 'ExternalAccount not found.');
  152. }
  153. return redirectWithFlash('successMessage', 'Successfully disassociated.');
  154. })
  155. .catch((err) => {
  156. if (err) {
  157. if (err.name === 'couldntDisassociateError') {
  158. return redirectWithFlash('couldntDisassociateError', true);
  159. }
  160. return redirectWithFlash('errorMessage', err.message);
  161. }
  162. });
  163. };
  164. actions.externalAccounts.associateLdap = function(req, res) {
  165. const passport = require('passport');
  166. const passportService = crowi.passportService;
  167. const redirectWithFlash = (type, msg) => {
  168. req.flash(type, msg);
  169. return res.redirect('/me/external-accounts');
  170. };
  171. if (!passportService.isLdapStrategySetup) {
  172. debug('LdapStrategy has not been set up');
  173. return redirectWithFlash('warning', 'LdapStrategy has not been set up');
  174. }
  175. passport.authenticate('ldapauth', (err, user, info) => {
  176. if (res.headersSent) { // dirty hack -- 2017.09.25
  177. return; // cz: somehow passport.authenticate called twice when ECONNREFUSED error occurred
  178. }
  179. if (err) { // DB Error
  180. logger.error('LDAP Server Error: ', err);
  181. return redirectWithFlash('warningMessage', 'LDAP Server Error occured.');
  182. }
  183. if (info && info.message) {
  184. return redirectWithFlash('warningMessage', info.message);
  185. }
  186. if (user) {
  187. // create ExternalAccount
  188. const ldapAccountId = passportService.getLdapAccountIdFromReq(req);
  189. const user = req.user;
  190. ExternalAccount.associate('ldap', ldapAccountId, user)
  191. .then(() => {
  192. return redirectWithFlash('successMessage', 'Successfully added.');
  193. })
  194. .catch((err) => {
  195. return redirectWithFlash('errorMessage', err.message);
  196. });
  197. }
  198. })(req, res, () => {});
  199. };
  200. actions.password = function(req, res) {
  201. const passwordForm = req.body.mePassword;
  202. const userData = req.user;
  203. /*
  204. * disabled because the system no longer allows undefined email -- 2017.10.06 Yuki Takei
  205. *
  206. // パスワードを設定する前に、emailが設定されている必要がある (schemaを途中で変更したため、最初の方の人は登録されていないかもしれないため)
  207. // そのうちこのコードはいらなくなるはず
  208. if (!userData.isEmailSet()) {
  209. return res.redirect('/me');
  210. }
  211. */
  212. if (req.method === 'POST' && req.form.isValid) {
  213. const newPassword = passwordForm.newPassword;
  214. const newPasswordConfirm = passwordForm.newPasswordConfirm;
  215. const oldPassword = passwordForm.oldPassword;
  216. if (userData.isPasswordSet() && !userData.isPasswordValid(oldPassword)) {
  217. req.form.errors.push('Wrong current password');
  218. return res.render('me/password', {
  219. });
  220. }
  221. // check password confirm
  222. if (newPassword !== newPasswordConfirm) {
  223. req.form.errors.push('Failed to verify passwords');
  224. }
  225. else {
  226. userData.updatePassword(newPassword, (err, userData) => {
  227. if (err) {
  228. /* eslint-disable no-restricted-syntax, no-prototype-builtins */
  229. for (const e in err.errors) {
  230. if (err.errors.hasOwnProperty(e)) {
  231. req.form.errors.push(err.errors[e].message);
  232. }
  233. }
  234. return res.render('me/password', {});
  235. }
  236. /* eslint-enable no-restricted-syntax, no-prototype-builtins */
  237. req.flash('successMessage', 'Password updated');
  238. return res.redirect('/me/password');
  239. });
  240. }
  241. }
  242. else { // method GET
  243. return res.render('me/password', {
  244. });
  245. }
  246. };
  247. actions.apiToken = function(req, res) {
  248. const userData = req.user;
  249. if (req.method === 'POST' && req.form.isValid) {
  250. userData.updateApiToken()
  251. .then((userData) => {
  252. req.flash('successMessage', 'API Token updated');
  253. return res.redirect('/me/apiToken');
  254. })
  255. .catch((err) => {
  256. // req.flash('successMessage',);
  257. req.form.errors.push('Failed to update API Token');
  258. return res.render('me/api_token', {
  259. });
  260. });
  261. }
  262. else {
  263. return res.render('me/api_token', {
  264. });
  265. }
  266. };
  267. actions.updates = function(req, res) {
  268. res.render('me/update', {
  269. });
  270. };
  271. return actions;
  272. };