Skip to content

Instantly share code, notes, and snippets.

@psi-4ward
Last active June 26, 2020 09:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save psi-4ward/1922c5a8ae30e5c29809f88349b68917 to your computer and use it in GitHub Desktop.
Save psi-4ward/1922c5a8ae30e5c29809f88349b68917 to your computer and use it in GitHub Desktop.
Feathers.js simple changePassword Service
const auth = require('@feathersjs/authentication');
const errors = require('@feathersjs/errors');
const bcrypt = require('bcryptjs');
const comparePasswords = (oldPassword, password) => new Promise((resolve, reject) => {
bcrypt.compare(oldPassword, password, (err, data1) => {
if(err || !data1) return reject();
return resolve();
});
});
module.exports = function() {
const app = this;
// Add authentication/changePassword service
const changePasswordService = app.use('authentication/changePassword', {
async create(data, params) {
// const user = await app.service('users').get(params.payload.userId);
const user = params.user;
if(!data.password) throw new errors.BadRequest(`Missing password`);
if(!data.oldPassword) throw new errors.BadRequest(`Missing oldPassword`);
try {
await comparePasswords(data.oldPassword, user.password);
}
catch(e) {
throw new errors.BadRequest('Current password wrong');
}
const newUser = await app.service('users').patch(user._id, {password: data.password});
delete newUser.password; // never send pwd to client
return newUser;
}
});
// Add jwt authentication
changePasswordService.hooks({
before: auth.hooks.authenticate('jwt')
});
};

Feathers.js simple changePassword Service

If feathers-authentication-management is too much :)

  • Adds create /authentication/changePassword endpoint
  • User needs a valid JWT
  • Checks if oldPassword matches current password

Client

feathersClient.service('authentication/changePassword').create({
  password: "new-top-secret",
  oldPassword: "secret"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment