Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const async = require('async');
- const crypto = require('crypto');
- const lib = require('../lib');
- module.exports = (mongoose) => {
- let Schema = mongoose.Schema;
- let UserSchema = new Schema({
- id: {
- type: Number,
- unique: true,
- required: true
- },
- login: {
- type: String,
- unique: true,
- required: true
- },
- created: {
- type: Date,
- default: Date.now
- },
- hashedPassword: {
- type: String,
- required: true
- },
- salt: {
- type: String,
- required: true
- },
- imageId: {
- type: Number,
- default: 0
- }
- });
- UserSchema.method('encryptPassword', encryptPassword);
- UserSchema.method('checkPassword', checkPassword);
- UserSchema.static('authorize', authorize);
- UserSchema.static('create', create);
- UserSchema.static('signin', signin);
- UserSchema.static('safeFields', 'id login created');
- UserSchema.virtual('password')
- .set(function(password) {
- this._plainPassword = password;
- this.salt = Math.random() + '';
- this.hashedPassword = this.encryptPassword(password);
- });
- mongoose.model('User', UserSchema);
- }
- // statics
- function authorize(login, callback) {
- let User = this;
- async.waterfall([
- (cb) => {
- User.findOne(
- {
- login: login
- },
- User.safeFields,
- cb
- );
- },
- (user, cb) => {
- return cb(null, user);
- }
- ], callback);
- }
- function create(params, cb) {
- let User = this;
- lib.getDocumentId(User, (err, id) => {
- if (err) {
- return cb(err);
- }
- let user = new User({
- id: id,
- login: params.login,
- password: params.password
- });
- user.save(cb);
- });
- }
- function signin(params, cb) {
- let User = this;
- User.findOne({ login: params.login }, (err, user) => {
- if (err) {
- return cb(err);
- }
- // create if we dont find by login
- if (!user) {
- return User.create(params, cb);
- }
- if (user && !user.checkPassword(params.password)) {
- return cb('Passwords not match');
- }
- cb(null, user);
- });
- }
- // methods
- function encryptPassword(password) {
- return crypto
- .createHmac('sha1', this.salt)
- .update(password)
- .digest('hex');
- }
- function checkPassword(password) {
- return this.encryptPassword(password) === this.hashedPassword;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement