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/access-tokens/create.js

83 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-08-31 04:07:25 +05:00
const bcrypt = require('bcrypt');
2020-04-03 00:35:25 +05:00
const validator = require('validator');
2019-08-31 04:07:25 +05:00
const { getRemoteAddress } = require('../../../utils/remoteAddress');
2019-08-31 04:07:25 +05:00
const Errors = {
2020-04-03 00:35:25 +05:00
INVALID_EMAIL_OR_USERNAME: {
invalidEmailOrUsername: 'Invalid email or username',
2019-08-31 04:07:25 +05:00
},
2020-04-03 00:35:25 +05:00
INVALID_PASSWORD: {
invalidPassword: 'Invalid password',
},
2023-10-17 19:18:19 +02:00
USE_SINGLE_SIGN_ON: {
useSingleSignOn: 'Use single sign-on',
},
2019-08-31 04:07:25 +05:00
};
2022-12-26 21:10:50 +01:00
const emailOrUsernameValidator = (value) =>
value.includes('@')
? validator.isEmail(value)
: value.length >= 3 && value.length <= 16 && /^[a-zA-Z0-9]+((_|\.)?[a-zA-Z0-9])*$/.test(value);
2019-08-31 04:07:25 +05:00
module.exports = {
inputs: {
2020-04-03 00:35:25 +05:00
emailOrUsername: {
2019-08-31 04:07:25 +05:00
type: 'string',
2022-12-26 21:10:50 +01:00
custom: emailOrUsernameValidator,
2019-08-31 04:07:25 +05:00
required: true,
},
password: {
type: 'string',
required: true,
},
2019-08-31 04:07:25 +05:00
},
exits: {
2020-04-03 00:35:25 +05:00
invalidEmailOrUsername: {
responseType: 'unauthorized',
},
invalidPassword: {
responseType: 'unauthorized',
},
2023-10-17 19:18:19 +02:00
useSingleSignOn: {
responseType: 'forbidden',
},
2019-08-31 04:07:25 +05:00
},
async fn(inputs) {
const remoteAddress = getRemoteAddress(this.req);
const user = await sails.helpers.users.getOneByEmailOrUsername(inputs.emailOrUsername);
2019-08-31 04:07:25 +05:00
2023-10-17 19:18:19 +02:00
if (user.isSso) {
throw Errors.USE_SINGLE_SIGN_ON;
}
2019-08-31 04:07:25 +05:00
if (!user) {
sails.log.warn(
`Invalid email or username: "${inputs.emailOrUsername}"! (IP: ${remoteAddress})`,
);
2020-04-03 00:35:25 +05:00
throw Errors.INVALID_EMAIL_OR_USERNAME;
2019-08-31 04:07:25 +05:00
}
if (!bcrypt.compareSync(inputs.password, user.password)) {
sails.log.warn(`Invalid password! (IP: ${remoteAddress})`);
2020-04-03 00:35:25 +05:00
throw Errors.INVALID_PASSWORD;
2019-08-31 04:07:25 +05:00
}
const accessToken = sails.helpers.utils.createToken(user.id);
await Session.create({
accessToken,
remoteAddress,
userId: user.id,
userAgent: this.req.headers['user-agent'],
});
return {
item: accessToken,
};
},
2019-08-31 04:07:25 +05:00
};