user.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. , config = app.set('config')
  7. , ObjectId = mongoose.Schema.Types.ObjectId
  8. , STATUS_REGISTERED = 1
  9. , STATUS_ACTIVE = 2
  10. , STATUS_SUSPENDED = 3
  11. , STATUS_DELETED = 4
  12. , PAGE_ITEMS = 20
  13. , userSchema;
  14. userSchema = new mongoose.Schema({
  15. userId: String,
  16. fbId: String, // userId
  17. image: String,
  18. googleId: String,
  19. name: { type: String, required: true },
  20. username: { type: String, required: true },
  21. email: { type: String, required: true },
  22. password: String,
  23. status: { type: Number, required: true, default: STATUS_ACTIVE },
  24. createdAt: { type: Date, default: Date.now },
  25. admin: { type: Boolean, default: 0 }
  26. });
  27. userSchema.plugin(mongoosePaginate);
  28. function decideUserStatusOnRegistration () {
  29. var Config = models.Config;
  30. // status decided depends on registrationMode
  31. switch (config.crowi['security:registrationMode']) {
  32. case Config.SECURITY_REGISTRATION_MODE_OPEN:
  33. return STATUS_ACTIVE;
  34. case Config.SECURITY_REGISTRATION_MODE_RESTRICTED:
  35. case Config.SECURITY_REGISTRATION_MODE_CLOSED: // 一応
  36. return STATUS_REGISTERED;
  37. default:
  38. return STATUS_ACTIVE; // どっちにすんのがいいんだろうな
  39. }
  40. }
  41. function generatePassword (password) {
  42. var hasher = crypto.createHash('sha256');
  43. hasher.update(process.env.PASSWORD_SEED + password);
  44. return hasher.digest('hex');
  45. }
  46. userSchema.methods.isPasswordSet = function() {
  47. if (this.password) {
  48. return true;
  49. }
  50. return false;
  51. };
  52. userSchema.methods.isPasswordValid = function(password) {
  53. return this.password == generatePassword(password);
  54. };
  55. userSchema.methods.setPassword = function(password) {
  56. return this.password == generatePassword(password);
  57. };
  58. userSchema.methods.setPassword = function(password) {
  59. this.password = generatePassword(password);
  60. return this;
  61. };
  62. userSchema.methods.isEmailSet = function() {
  63. if (this.email) {
  64. return true;
  65. }
  66. return false;
  67. };
  68. userSchema.methods.update = function(name, email, callback) {
  69. this.name = name;
  70. this.email = email;
  71. this.save(function(err, userData) {
  72. return callback(err, userData);
  73. });
  74. };
  75. userSchema.methods.updatePassword = function(password, callback) {
  76. this.setPassword(password);
  77. this.save(function(err, userData) {
  78. return callback(err, userData);
  79. });
  80. };
  81. userSchema.methods.updateImage = function(image, callback) {
  82. this.image = image;
  83. this.save(function(err, userData) {
  84. return callback(err, userData);
  85. });
  86. };
  87. userSchema.methods.deleteImage = function(callback) {
  88. return this.updateImage(null, callback);
  89. };
  90. userSchema.methods.updateFacebookId = function(fbId, callback) {
  91. this.fbId = this.userId = fbId;
  92. this.save(function(err, userData) {
  93. return callback(err, userData);
  94. });
  95. };
  96. userSchema.methods.deleteFacebookId = function(callback) {
  97. return this.updateFacebookId(null, callback);
  98. };
  99. userSchema.methods.updateGoogleId = function(googleId, callback) {
  100. this.googleId = googleId;
  101. this.save(function(err, userData) {
  102. return callback(err, userData);
  103. });
  104. };
  105. userSchema.methods.deleteGoogleId = function(callback) {
  106. return this.updateGoogleId(null, callback);
  107. };
  108. userSchema.methods.removeFromAdmin = function(callback) {
  109. debug('Remove from admin', this);
  110. this.admin = 0;
  111. this.save(function(err, userData) {
  112. return callback(err, userData);
  113. });
  114. };
  115. userSchema.methods.makeAdmin = function(callback) {
  116. debug('Admin', this);
  117. this.admin = 1;
  118. this.save(function(err, userData) {
  119. return callback(err, userData);
  120. });
  121. };
  122. userSchema.methods.statusActivate = function(callback) {
  123. debug('Activate User', this);
  124. this.status = STATUS_ACTIVE;
  125. this.save(function(err, userData) {
  126. return callback(err, userData);
  127. });
  128. };
  129. userSchema.methods.statusSuspend = function(callback) {
  130. debug('Suspend User', this);
  131. this.status = STATUS_SUSPENDED;
  132. if (this.email === undefined || this.email === null) { // migrate old data
  133. this.email = '-';
  134. }
  135. if (this.name === undefined || this.name === null) { // migrate old data
  136. this.name = '-' + Date.now();
  137. }
  138. if (this.username === undefined || this.usename === null) { // migrate old data
  139. this.username = '-';
  140. }
  141. this.save(function(err, userData) {
  142. return callback(err, userData);
  143. });
  144. };
  145. userSchema.methods.statusDelete = function(callback) {
  146. debug('Delete User', this);
  147. this.status = STATUS_DELETED;
  148. this.password = '';
  149. this.email = 'deleted@deleted';
  150. this.googleId = null;
  151. this.fbId = null;
  152. this.image = null;
  153. this.save(function(err, userData) {
  154. return callback(err, userData);
  155. });
  156. };
  157. userSchema.methods.updateGoogleIdAndFacebookId = function(googleId, facebookId, callback) {
  158. this.googleId = googleId;
  159. this.fbId = this.userId = facebookId;
  160. this.save(function(err, userData) {
  161. return callback(err, userData);
  162. });
  163. };
  164. userSchema.statics.getUserStatusLabels = function() {
  165. var userStatus = {};
  166. userStatus[STATUS_REGISTERED] = '承認待ち';
  167. userStatus[STATUS_ACTIVE] = 'Active';
  168. userStatus[STATUS_SUSPENDED] = 'Suspended';
  169. userStatus[STATUS_DELETED] = 'Deleted';
  170. return userStatus;
  171. };
  172. userSchema.statics.isEmailValid = function(email, callback) {
  173. if (Array.isArray(config.crowi['security:registrationWhiteList'])) {
  174. return config.crowi['security:registrationWhiteList'].some(function(allowedEmail) {
  175. var re = new RegExp(allowedEmail + '$');
  176. return re.test(email);
  177. });
  178. }
  179. return true;
  180. };
  181. userSchema.statics.findUsers = function(options, callback) {
  182. var sort = options.sort || {status: 1, createdAt: 1};
  183. this.find()
  184. .sort(sort)
  185. .skip(options.skip || 0)
  186. .limit(options.limit || 21)
  187. .exec(function (err, userData) {
  188. callback(err, userData);
  189. });
  190. };
  191. userSchema.statics.findUsersWithPagination = function(options, callback) {
  192. var sort = options.sort || {status: 1, username: 1, createdAt: 1};
  193. this.paginate({}, options.page || 1, PAGE_ITEMS, function(err, pageCount, paginatedResults, itemCount) {
  194. if (err) {
  195. debug('Error on pagination:', err);
  196. return callback(err, null);
  197. }
  198. return callback(err, paginatedResults, pageCount, itemCount);
  199. }, { sortBy : sort });
  200. };
  201. userSchema.statics.findUserByUsername = function(username, callback) {
  202. this.findOne({username: username}, function (err, userData) {
  203. callback(err, userData);
  204. });
  205. };
  206. userSchema.statics.findUserByFacebookId = function(fbId, callback) {
  207. this.findOne({userId: fbId}, function (err, userData) {
  208. callback(err, userData);
  209. });
  210. };
  211. userSchema.statics.findUserByGoogleId = function(googleId, callback) {
  212. this.findOne({googleId: googleId}, function (err, userData) {
  213. callback(err, userData);
  214. });
  215. };
  216. userSchema.statics.findUserByEmailAndPassword = function(email, password, callback) {
  217. var hashedPassword = generatePassword(password);
  218. this.findOne({email: email, password: hashedPassword}, function (err, userData) {
  219. callback(err, userData);
  220. });
  221. };
  222. userSchema.statics.isRegisterable = function(email, username, callback) {
  223. var User = this;
  224. var emailUsable = true;
  225. var usernameUsable = true;
  226. // username check
  227. this.findOne({username: username}, function (err, userData) {
  228. if (userData) {
  229. usernameUsable = false;
  230. }
  231. // email check
  232. User.findOne({email: email}, function (err, userData) {
  233. if (userData) {
  234. emailUsable = false;
  235. }
  236. if (!emailUsable || !usernameUsable) {
  237. return callback(false, {email: emailUsable, username: usernameUsable});
  238. }
  239. return callback(true, {});
  240. });
  241. });
  242. };
  243. userSchema.statics.createUserByEmailAndPassword = function(name, username, email, password, callback) {
  244. var User = this
  245. , newUser = new User();
  246. newUser.name = name;
  247. newUser.username = username;
  248. newUser.email = email;
  249. newUser.setPassword(password);
  250. newUser.createdAt = Date.now();
  251. newUser.status = decideUserStatusOnRegistration();
  252. newUser.save(function(err, userData) {
  253. return callback(err, userData);
  254. });
  255. };
  256. userSchema.statics.createUserByFacebook = function(fbUserInfo, callback) {
  257. var User = this
  258. , newUser = new User();
  259. newUser.userId = fbUserInfo.id;
  260. newUser.image = '//graph.facebook.com/' + fbUserInfo.id + '/picture?size=square';
  261. newUser.name = fbUserInfo.name || '';
  262. newUser.username = fbUserInfo.username || '';
  263. newUser.email = fbUserInfo.email || '';
  264. newUser.createdAt = Date.now();
  265. newUser.status = decideUserStatusOnRegistration();
  266. newUser.save(function(err, userData) {
  267. return callback(err, userData);
  268. });
  269. };
  270. userSchema.statics.createUserPictureFilePath = function(user, name) {
  271. var ext = '.' + name.match(/(.*)(?:\.([^.]+$))/)[2];
  272. return 'user/' + user._id + ext;
  273. };
  274. userSchema.statics.STATUS_REGISTERED = STATUS_REGISTERED;
  275. userSchema.statics.STATUS_ACTIVE = STATUS_ACTIVE;
  276. userSchema.statics.STATUS_SUSPENDED = STATUS_SUSPENDED;
  277. userSchema.statics.STATUS_DELETED = STATUS_DELETED;
  278. models.User = mongoose.model('User', userSchema);
  279. return models.User;
  280. };