Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to implement a pre function #63

Open
denghauser opened this issue Sep 18, 2020 · 3 comments
Open

How to implement a pre function #63

denghauser opened this issue Sep 18, 2020 · 3 comments

Comments

@denghauser
Copy link

Hi, I just tried to add the pre function to my Schema but figured out, that I have no idea how to do this with ts-mongoose. Can you share an example?

@denghauser
Copy link
Author

denghauser commented Sep 18, 2020

Here is an example of what I plan to do, but have no idea how to attach this to the schema generated by ts-mongoose

Schema.methods.hashPassword = (password: string) => {
    return security.pbkdf2Sync(password, this.salt, 10000, 64, 'SHA512').toString('base64');
};

Schema.methods.authenticate = (password: string) => {
    return this.password === this.hashPassword(password);
};

Schema.pre('save', (next: express.NextFunction) => {
     if (this.password) {
	    this.salt = new Buffer(security.randomBytes(16).toString('base64'), 'base64');
	    this.password = this.hashPassword(this.password);
    }
    next();
});

@Corky3892
Copy link

Corky3892 commented Oct 19, 2020

Not exactly using the pre function (not something I have messed around with using this library).

This is the pattern I use for creating methods included in the generated schema. Of course you'll need to call myModel.mySave() instead of myModel.save().

export const myModel= typedModel('schemaName', mySchema, undefined, undefined, {
  hashPassword: (password: string) => {
    return security.pbkdf2Sync(password, this.salt, 10000, 64, 'SHA512').toString('base64');
  },

  authenticate: (password: string) => {
    return myModel.password === myModel.hashPassword(password);
  },

  mySave: (next: express.NextFunction) => {
     if (myModel.password) {
	  myModel.salt = new Buffer(security.randomBytes(16).toString('base64'), 'base64');
	  myModel.password = myModel.hashPassword(myModel.password);
     }
     next();
  });
}

@honboubao
Copy link

Have you tried it just like that? I'm new to ts-mongoose as well, but it seems to at least satisfy my unit tests. This is what I have:

const UserSchema = createSchema({
  email: string({ required: true, unique: true, trim: true, lowercase: true }),
  password: string({ required: true, select: false, immutable: isImmutable }),
}, { timestamps: true });

UserSchema.pre('save', async function (next) {
  const user = this as UserDoc;
  if (user.isModified('password')) {
    user.password = await hashPassword(user.password);
  }
  next();
});

UserSchema.methods.checkPassword = async function (password: string): Promise<boolean> {
  let doc = this as UserDoc;
  return comparePasswords(password, await doc.getPassword());
};

export const User = typedModel('User', UserSchema);
export type UserDoc = ExtractDoc<typeof UserSchema>;

And

  it('should create user', async () => {
    const userData: UserProps = {
      _id: userId,
      email: 'blub@blub.blub',
      password: 'blubblub'
    };
    await User.create(userData);
    const user = await User.findById(userId);
    expect(user).not.toBeNull();
  });

  it('should hash the password on creation', async () => {
    const user = await User.findById(userId, '+password') as UserDoc;
    expect(user.password).not.toBe('blublub');
  });

  test('User.checkPassword', async () => {
    const user = await User.findById(userId, '+password') as UserDoc;
    const positiveCheck = await user.checkPassword('blubblub');
    expect(positiveCheck).toBe(true);
    const negativeCheck = await user.checkPassword('asdf');
    expect(negativeCheck).toBe(false);
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants