user.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. module.exports = function(app, models) {
  2. var mongoose = require('mongoose')
  3. , mongoosePaginate = require('mongoose-paginate')
  4. , debug = require('debug')('crowi:models:user')
  5. , crypto = require('crypto')
  6. , async = require('async')
  7. , config = app.set('config')
  8. , ObjectId = mongoose.Schema.Types.ObjectId
  9. , STATUS_REGISTERED = 1
  10. , STATUS_ACTIVE = 2
  11. , STATUS_SUSPENDED = 3
  12. , STATUS_DELETED = 4
  13. , STATUS_INVITED = 5
  14. , PAGE_ITEMS = 20
  15. , userSchema;
  16. userSchema = new mongoose.Schema({
  17. userId: String,
  18. fbId: String, // userId
  19. image: String,
  20. googleId: String,
  21. name: { type: String },
  22. username: { type: String },
  23. email: { type: String, required: true },
  24. password: String,
  25. status: { type: Number, required: true, default: STATUS_ACTIVE },
  26. createdAt: { type: Date, default: Date.now },
  27. admin: { type: Boolean, default: 0 }
  28. });
  29. userSchema.plugin(mongoosePaginate);
  30. function decideUserStatusOnRegistration () {
  31. var Config = models.Config;
  32. // status decided depends on registrationMode
  33. switch (config.crowi['security:registrationMode']) {
  34. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  35. return STATUS_ACTIVE;
  36. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  37. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  38. return STATUS_REGISTERED;
  39. default:
  40. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  41. }
  42. }
  43. function generatePassword (password) {
  44. var hasher = crypto.createHash('sha256');
  45. hasher.update(process.env.PASSWORD_SEED + password);
  46. return hasher.digest('hex');
  47. }
  48. userSchema.methods.isPasswordSet = function() {
  49. if (this.password) {
  50. return true;
  51. }
  52. return false;
  53. };
  54. userSchema.methods.isPasswordValid = function(password) {
  55. return this.password == generatePassword(password);
  56. };
  57. userSchema.methods.setPassword = function(password) {
  58. return this.password == generatePassword(password);
  59. };
  60. userSchema.methods.setPassword = function(password) {
  61. this.password = generatePassword(password);
  62. return this;
  63. };
  64. userSchema.methods.isEmailSet = function() {
  65. if (this.email) {
  66. return true;
  67. }
  68. return false;
  69. };
  70. userSchema.methods.update = function(name, email, callback) {
  71. this.name = name;
  72. this.email = email;
  73. this.save(function(err, userData) {
  74. return callback(err, userData);
  75. });
  76. };
  77. userSchema.methods.updatePassword = function(password, callback) {
  78. this.setPassword(password);
  79. this.save(function(err, userData) {
  80. return callback(err, userData);
  81. });
  82. };
  83. userSchema.methods.updateImage = function(image, callback) {
  84. this.image = image;
  85. this.save(function(err, userData) {
  86. return callback(err, userData);
  87. });
  88. };
  89. userSchema.methods.deleteImage = function(callback) {
  90. return this.updateImage(null, callback);
  91. };
  92. userSchema.methods.updateFacebookId = function(fbId, callback) {
  93. this.fbId = this.userId = fbId;
  94. this.save(function(err, userData) {
  95. return callback(err, userData);
  96. });
  97. };
  98. userSchema.methods.deleteFacebookId = function(callback) {
  99. return this.updateFacebookId(null, callback);
  100. };
  101. userSchema.methods.updateGoogleId = function(googleId, callback) {
  102. this.googleId = googleId;
  103. this.save(function(err, userData) {
  104. return callback(err, userData);
  105. });
  106. };
  107. userSchema.methods.deleteGoogleId = function(callback) {
  108. return this.updateGoogleId(null, callback);
  109. };
  110. userSchema.methods.removeFromAdmin = function(callback) {
  111. debug('Remove from admin', this);
  112. this.admin = 0;
  113. this.save(function(err, userData) {
  114. return callback(err, userData);
  115. });
  116. };
  117. userSchema.methods.makeAdmin = function(callback) {
  118. debug('Admin', this);
  119. this.admin = 1;
  120. this.save(function(err, userData) {
  121. return callback(err, userData);
  122. });
  123. };
  124. userSchema.methods.statusActivate = function(callback) {
  125. debug('Activate User', this);
  126. this.status = STATUS_ACTIVE;
  127. this.save(function(err, userData) {
  128. return callback(err, userData);
  129. });
  130. };
  131. userSchema.methods.statusSuspend = function(callback) {
  132. debug('Suspend User', this);
  133. this.status = STATUS_SUSPENDED;
  134. if (this.email === undefined || this.email === null) { // migrate old data
  135. this.email = '-';
  136. }
  137. if (this.name === undefined || this.name === null) { // migrate old data
  138. this.name = '-' + Date.now();
  139. }
  140. if (this.username === undefined || this.usename === null) { // migrate old data
  141. this.username = '-';
  142. }
  143. this.save(function(err, userData) {
  144. return callback(err, userData);
  145. });
  146. };
  147. userSchema.methods.statusDelete = function(callback) {
  148. debug('Delete User', this);
  149. this.status = STATUS_DELETED;
  150. this.password = '';
  151. this.email = 'deleted@deleted';
  152. this.googleId = null;
  153. this.fbId = null;
  154. this.image = null;
  155. this.save(function(err, userData) {
  156. return callback(err, userData);
  157. });
  158. };
  159. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  160. this.googleId = googleId;
  161. this.fbId = this.userId = facebookId;
  162. this.save(function(err, userData) {
  163. return callback(err, userData);
  164. });
  165. };
  166. userSchema.statics.getUserStatusLabels = function() {
  167. var userStatus = {};
  168. userStatus[STATUS_REGISTERED] = '承認待ち';
  169. userStatus[STATUS_ACTIVE] = 'Active';
  170. userStatus[STATUS_SUSPENDED] = 'Suspended';
  171. userStatus[STATUS_DELETED] = 'Deleted';
  172. userStatus[STATUS_INVITED] = '招待済み';
  173. return userStatus;
  174. };
  175. userSchema.statics.isEmailValid = function(email, callback) {
  176. if (Array.isArray(config.crowi['security:registrationWhiteList'])) {
  177. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  178. var re = new RegExp(allowedEmail + '$');
  179. return re.test(email);
  180. });
  181. }
  182. return true;
  183. };
  184. userSchema.statics.findUsers = function(options, callback) {
  185. var sort = options.sort || {status: 1, createdAt: 1};
  186. this.find()
  187. .sort(sort)
  188. .skip(options.skip || 0)
  189. .limit(options.limit || 21)
  190. .exec(function (err, userData) {
  191. callback(err, userData);
  192. });
  193. };
  194. userSchema.statics.findUsersWithPagination = function(options, callback) {
  195. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  196. this.paginate({}, options.page || 1, PAGE_ITEMS, function(err, pageCount, paginatedResults, itemCount) {
  197. if (err) {
  198. debug('Error on pagination:', err);
  199. return callback(err, null);
  200. }
  201. return callback(err, paginatedResults, pageCount, itemCount);
  202. }, { sortBy : sort });
  203. };
  204. userSchema.statics.findUserByUsername = function(username, callback) {
  205. this.findOne({username: username}, function (err, userData) {
  206. callback(err, userData);
  207. });
  208. };
  209. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  210. this.findOne({userId: fbId}, function (err, userData) {
  211. callback(err, userData);
  212. });
  213. };
  214. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  215. this.findOne({googleId: googleId}, function (err, userData) {
  216. callback(err, userData);
  217. });
  218. };
  219. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  220. var hashedPassword = generatePassword(password);
  221. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  222. callback(err, userData);
  223. });
  224. };
  225. userSchema.statics.isRegisterable = function(email, username, callback) {
  226. var User = this;
  227. var emailUsable = true;
  228. var usernameUsable = true;
  229. // username check
  230. this.findOne({username: username}, function (err, userData) {
  231. if (userData) {
  232. usernameUsable = false;
  233. }
  234. // email check
  235. User.findOne({email: email}, function (err, userData) {
  236. if (userData) {
  237. emailUsable = false;
  238. }
  239. if (!emailUsable || !usernameUsable) {
  240. return callback(false, {email: emailUsable, username: usernameUsable});
  241. }
  242. return callback(true, {});
  243. });
  244. });
  245. };
  246. userSchema.statics.removeCompletelyById = function(id, callback) {
  247. var User = this;
  248. User.findById(id, function (err, userData) {
  249. if (!userData) {
  250. return callback(err, null);
  251. }
  252. debug('Removing user:', userData);
  253. // 物理削除可能なのは、招待中ユーザーのみ
  254. // 利用を一度開始したユーザーは論理削除のみ可能
  255. if (userData.status !== STATUS_INVITED) {
  256. return callback(new Error('Cannot remove completely the user whoes status is not INVITED'), null);
  257. }
  258. userData.remove(function(err) {
  259. if (err) {
  260. return callback(err, null);
  261. }
  262. return callback(null, 1);
  263. });
  264. });
  265. };
  266. userSchema.statics.createUsersByInvitation = function(emailList, toSendEmail, callback) {
  267. var User = this
  268. , createdUserList = [];
  269. if (!Array.isArray(emailList)) {
  270. debug('emailList is not array');
  271. }
  272. async.each(
  273. emailList,
  274. function(email, next) {
  275. var newUser = new User()
  276. ,password;
  277. email = email.trim();
  278. // email check
  279. // TODO: 削除済みはチェック対象から外そう〜
  280. User.findOne({email: email}, function (err, userData) {
  281. if (userData) {
  282. createdUserList.push({
  283. email: email,
  284. password: null,
  285. user: null,
  286. });
  287. return next();
  288. }
  289. password = Math.random().toString(36).slice(-16);
  290. newUser.email = email;
  291. newUser.setPassword(password);
  292. newUser.createdAt = Date.now();
  293. newUser.status = STATUS_INVITED;
  294. newUser.save(function(err, userData) {
  295. if (err) {
  296. createdUserList.push({
  297. email: email,
  298. password: null,
  299. user: null,
  300. });
  301. debug('save failed!! ', email);
  302. } else {
  303. createdUserList.push({
  304. email: email,
  305. password: password,
  306. user: userData,
  307. });
  308. debug('saved!', email);
  309. }
  310. next();
  311. });
  312. });
  313. },
  314. function(err) {
  315. if (err) {
  316. debug('error occured while iterate email list');
  317. }
  318. if (toSendEmail) {
  319. debug('send Email here');
  320. }
  321. debug("createdUserList!!! ", createdUserList);
  322. return callback(null, createdUserList);
  323. }
  324. );
  325. };
  326. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  327. var User = this
  328. , newUser = new User();
  329. newUser.name = name;
  330. newUser.username = username;
  331. newUser.email = email;
  332. newUser.setPassword(password);
  333. newUser.createdAt = Date.now();
  334. newUser.status = decideUserStatusOnRegistration();
  335. newUser.save(function(err, userData) {
  336. return callback(err, userData);
  337. });
  338. };
  339. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  340. var User = this
  341. , newUser = new User();
  342. newUser.userId = fbUserInfo.id;
  343. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  344. newUser.name = fbUserInfo.name || '';
  345. newUser.username = fbUserInfo.username || '';
  346. newUser.email = fbUserInfo.email || '';
  347. newUser.createdAt = Date.now();
  348. newUser.status = decideUserStatusOnRegistration();
  349. newUser.save(function(err, userData) {
  350. return callback(err, userData);
  351. });
  352. };
  353. userSchema.statics.createUserPictureFilePath = function(user, name) {
  354. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  355. return 'user/' + user._id + ext;
  356. };
  357. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  358. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  359. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  360. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  361. userSchema.statics.STATUS_INVITED = STATUS_INVITED;
  362. models.User = mongoose.model('User', userSchema);
  363. return models.User;
  364. };