Monday, 15 May 2017

How create custom methods on my models with moogose

already, i want to call a method on my model, for compare the password given with the password encrypted on my database, im used a custom method on my schema, but appear the following error, when tried to execute the controller, i supose than i want to do, only can be used with "new" object, objects than already are on my database cant access to the method, thanks in advance for any help:

issue

  1. models/User.js
'use strict';

var mongoose, Schema, UserSchema, schemaOptions, bcrypt;
mongoose  = require('mongoose');
bcrypt = require('bcrypt');
Schema = mongoose.Schema;
schemaOptions = {
    toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    },
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
    new: true,
    runValidators: true
  };

UserSchema = Schema({
    _id:{
      type:Number,
      unique: true,
      index: true
     },
  provider:String,
  id:{
          type: String
      },
  displayName:{
          type: String,
          required:  [true, 'Scribe the Full name']
      },
  name: {
          familyName:{type: String,required:  [true, 'Scribe the last name']},
          givenName:{type: String,required:  [true, 'Scribe the first name']},
          middleName:{type: String,required:  [true, 'Scribe the middle name']}
         },
  emails:[{
          value:{
                type: String,
                unique: true,
                lowercase: true,
                index: true,
                validate: {
                 validator: function(v) {
                   return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,4}$/.test(v);
                 },
                 message: '{VALUE} is not a valid email!'}
                },
        type:{
             type: String,
             lowercase: true
           }
    }],
  email:{
         type: String,
         unique: true,
         lowercase: true,
         index: true,
         validate: {
          validator: function(v) {
            return /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9-]{2,}[.][a-zA-Z]{2,4}$/.test(v);
          },
          message: '{VALUE} is not a valid email for autenticate!'
        },
         required: [true, 'Scribe a Email']
        },
  password: {
             type: String,
             required: [true, 'Scribe a password']
            },
  photos:[{
          type: String  
        }],
  alias: {
          type: String,
          required: [true, 'Scribe the alias'],
          unique: true
         },
  birthday:{
           type: Date,
           required: [true, 'Select a birthday']
           },
  idiom: {
         type: String,
         required: [true, 'Select a idiom']
         },
  country: {
           type: Number,
           required: [true, 'Select a valid country'],
           min:1,
           max:231
       },
   rolId:{
       type: Number,
       required: [true, 'Select a rol'],
       default: 1
   },
  deletedAt: { type: Date, default: null }
},schemaOptions);

// Execute before each user.save() call
UserSchema.pre('save', function(next) {
  var user = this;

  if(this.isModified('password') || this.isNew){
      bcrypt.genSalt(10, function (error, salt){
         if(error){
             console.log(error);
             return next(error);
         } 
         bcrypt.hash(user.password, salt, function (error, hash){
           if (error) {
               console.log(error);
               return next(error);
           }
           user.password = hash;
           console.log("hashing the password!");
           next();
         });
      });
  }else{
      console.log("the password dont changed!");
      return next();
  }
});

//metodo para autenticar la clave recibida
UserSchema.methods.verifyPassword = function(password, next) {
  bcrypt.compare(password, this.password, function(error, isMatch) {
    if (error) {
        //return next(error);
        next(error);
        return false;
    };
     //return next(null, isMatch);
     next(null,isMatch);
     return true;
  });
};


module.exports = mongoose.model('User',UserSchema);

  1. controllers/UserControllers.js
'use strict';
var validator = require('validator');
var User = require('../models/User');
var Rol = require('../models/Rol');
var config = require('../config/database');
var jwt = require('jwt-simple');

function login(req, res){
  var params = req.body;
    User.find({email: params.email},function (error, user) {
        if (error) {
           return res.status(500).send({message: 'Error al devolver los marcadores del servidor'});
        };

        if (!user) {
          return res.status(404).send({message: 'El usuario con el correo designado no se encontro!'});
        }else{
            user.verifyPassword(params.email, function (error, isMatch){
                if(error){
                    console.log(error);
                    return false;
                }
                if (isMatch) {
                   var token = jwt.encode(user, config.secret);
                   return res.status(200).send({token:'JWT '+token});
                }else{
                   return res.status(403).send({message: 'La clave no es correcta!'});
                }
            });
           return res.status(200).send({token:user});
        }
    }).limit(1);
}
.
.
.
module.exports = {
    login, createUser, getUser, updateUser, deleteUser
};



via Fabio Andres Pino Gutierrez

No comments:

Post a Comment