1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-19 05:09:43 +02:00
planka/server/api/controllers/users/update-password.js

124 lines
2.8 KiB
JavaScript
Raw Normal View History

/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const bcrypt = require('bcrypt');
const { isPassword } = require('../../../utils/validators');
const { idInput } = require('../../../utils/inputs');
const { getRemoteAddress } = require('../../../utils/remote-address');
const Errors = {
2023-10-17 19:18:19 +02:00
NOT_ENOUGH_RIGHTS: {
notEnoughRights: 'Not enough rights',
},
2020-04-03 00:35:25 +05:00
INVALID_CURRENT_PASSWORD: {
invalidCurrentPassword: 'Invalid current password',
},
USER_NOT_FOUND: {
userNotFound: 'User not found',
},
};
module.exports = {
inputs: {
id: {
...idInput,
required: true,
},
password: {
type: 'string',
maxLength: 256,
custom: isPassword,
required: true,
},
currentPassword: {
type: 'string',
isNotEmptyString: true,
maxLength: 256,
},
},
exits: {
2023-10-17 19:18:19 +02:00
notEnoughRights: {
responseType: 'forbidden',
},
2020-04-03 00:35:25 +05:00
invalidCurrentPassword: {
responseType: 'forbidden',
},
userNotFound: {
responseType: 'notFound',
},
},
async fn(inputs) {
const { currentSession, currentUser } = this.req;
if (inputs.id === currentUser.id) {
if (!inputs.currentPassword) {
2020-04-03 00:35:25 +05:00
throw Errors.INVALID_CURRENT_PASSWORD;
}
} else if (currentUser.role !== User.Roles.ADMIN) {
throw Errors.USER_NOT_FOUND; // Forbidden
}
let user = await User.qm.getOneById(inputs.id);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
if (user.email === sails.config.custom.defaultAdminEmail || user.isSsoUser) {
2023-10-17 19:18:19 +02:00
throw Errors.NOT_ENOUGH_RIGHTS;
}
if (inputs.id === currentUser.id) {
const isCurrentPasswordValid = await bcrypt.compare(inputs.currentPassword, user.password);
if (!isCurrentPasswordValid) {
throw Errors.INVALID_CURRENT_PASSWORD;
}
}
const values = _.pick(inputs, ['password']);
2022-12-26 21:10:50 +01:00
user = await sails.helpers.users.updateOne.with({
values,
record: user,
actorUser: currentUser,
2022-12-26 21:10:50 +01:00
request: this.req,
});
if (!user) {
throw Errors.USER_NOT_FOUND;
}
if (user.id === currentUser.id) {
const { token: accessToken } = sails.helpers.utils.createJwtToken(
user.id,
user.passwordChangedAt,
);
await Session.qm.createOne({
accessToken,
httpOnlyToken: currentSession.httpOnlyToken,
userId: user.id,
remoteAddress: getRemoteAddress(this.req),
userAgent: this.req.headers['user-agent'],
});
return {
item: sails.helpers.users.presentOne(user, currentUser),
2022-08-09 22:31:43 +02:00
included: {
accessTokens: [accessToken],
},
};
}
return {
item: sails.helpers.users.presentOne(user, currentUser),
};
},
};