Advertisement
linaere

Untitled

May 21st, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. Для базы
  2. var mongoose = require('mongoose');
  3. var User = require('./models/User').User;
  4. //var config = require('./config');
  5. //mongoose.connect('mongodb://127.0.0.1:27017/test');
  6.  
  7. //var db = mongoose.connection.db;
  8. mongoose.connection.on('open', function () {
  9. var db = mongoose.connection.db;
  10. db.dropDatabase(function (err) {
  11. if (err) throw err;
  12. var vasya = new User({username:'Вася', password:'supervasya'});
  13. /*var petya = new User({username:'Петя', password:'123'});
  14. var admin = new User({username:'admin', password:'thetruehero'});
  15.  
  16. vasya.save();
  17. petya.save();
  18. admin.save();
  19. */
  20. mongoose.disconnect();
  21. });
  22. });
  23.  
  24. модель
  25. ar crypto = require('crypto');
  26. var mongoose = require('mongoose');
  27.  
  28. //var mongoose = require('./libs/mongoose');
  29. mongoose.connect('mongodb://127.0.0.1:27017/test');
  30. Schema = mongoose.Schema;
  31.  
  32. var schema = new Schema({
  33.  
  34. username: {
  35. type: String,
  36. unique: true,
  37. required: true
  38. },
  39. hashedPassword: {
  40. type: String,
  41. require: true
  42. },
  43. salt: {
  44. type: String,
  45. require: true
  46. },
  47. created: {
  48. type: Date,
  49. default: Date.now
  50. }
  51.  
  52. }
  53. );
  54.  
  55. schema.methods.encryptPassword = function (password) {
  56. return crypto.createHmac('shal', this.salt).update(password).digest('hex');
  57. };
  58.  
  59. schema.virtual('password')
  60. .set(function (password) {
  61. this._plainPassword = password;
  62. this.salt = Math.random() + ' ';
  63. this.hashedPassword = this.encryptPassword(password);
  64. })
  65. .get(function () {
  66. return this._plainPassword;
  67. });
  68.  
  69. schema.methods.checkPassword = function (password) {
  70. return this.encryptPassword(password) === this.hashedPassword;
  71. };
  72.  
  73. exports.User = mongoose.model('User', schema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement