1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-18 20:59:44 +02:00
planka/server/api/controllers/users/update-username.js

100 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-04-03 00:35:25 +05:00
const bcrypt = require('bcrypt');
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
USER_NOT_FOUND: {
userNotFound: 'User not found',
},
INVALID_CURRENT_PASSWORD: {
invalidCurrentPassword: 'Invalid current password',
},
USERNAME_ALREADY_IN_USE: {
usernameAlreadyInUse: 'Username already in use',
},
};
module.exports = {
inputs: {
id: {
type: 'string',
regex: /^[0-9]+$/,
required: true,
},
username: {
isNotEmptyString: true,
minLength: 3,
maxLength: 16,
2021-04-13 18:59:02 +05:00
regex: /^[a-zA-Z0-9]+((_|\.)?[a-zA-Z0-9])*$/,
2020-04-03 00:35:25 +05:00
allowNull: true,
},
currentPassword: {
type: 'string',
isNotEmptyString: true,
},
},
exits: {
2023-10-17 19:18:19 +02:00
notEnoughRights: {
responseType: 'forbidden',
},
2020-04-03 00:35:25 +05:00
userNotFound: {
responseType: 'notFound',
},
invalidCurrentPassword: {
responseType: 'forbidden',
},
usernameAlreadyInUse: {
responseType: 'conflict',
},
},
async fn(inputs) {
2020-04-03 00:35:25 +05:00
const { currentUser } = this.req;
if (inputs.id !== currentUser.id && !currentUser.isAdmin) {
2020-04-03 00:35:25 +05:00
throw Errors.USER_NOT_FOUND; // Forbidden
}
let user = await sails.helpers.users.getOne(inputs.id);
2020-04-03 00:35:25 +05:00
if (!user) {
throw Errors.USER_NOT_FOUND;
}
if (user.email === sails.config.custom.defaultAdminEmail) {
2023-10-17 19:18:19 +02:00
throw Errors.NOT_ENOUGH_RIGHTS;
}
if (user.isSso) {
if (!sails.config.custom.oidcIgnoreUsername) {
throw Errors.NOT_ENOUGH_RIGHTS;
}
} else if (inputs.id === currentUser.id) {
if (!inputs.currentPassword || !bcrypt.compareSync(inputs.currentPassword, user.password)) {
throw Errors.INVALID_CURRENT_PASSWORD;
}
2020-04-03 00:35:25 +05:00
}
const values = _.pick(inputs, ['username']);
2022-12-26 21:10:50 +01:00
user = await sails.helpers.users.updateOne
.with({
values,
record: user,
user: currentUser,
request: this.req,
})
2020-04-03 00:35:25 +05:00
.intercept('usernameAlreadyInUse', () => Errors.USERNAME_ALREADY_IN_USE);
if (!user) {
throw Errors.USER_NOT_FOUND;
}
return {
2020-05-26 00:46:04 +05:00
item: user,
};
2020-04-03 00:35:25 +05:00
},
};