/
create.js
executable file
·63 lines (55 loc) · 1.45 KB
/
create.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const bcrypt = require('bcrypt');
const validator = require('validator');
const { getRemoteAddress } = require('../../../utils/remoteAddress');
const Errors = {
INVALID_EMAIL_OR_USERNAME: {
invalidEmailOrUsername: 'Invalid email or username',
},
INVALID_PASSWORD: {
invalidPassword: 'Invalid password',
},
};
module.exports = {
inputs: {
emailOrUsername: {
type: 'string',
custom: (value) =>
value.includes('@')
? validator.isEmail(value)
: value.length >= 3 &&
value.length <= 16 &&
/^[a-zA-Z0-9]+((_|\.)?[a-zA-Z0-9])*$/.test(value),
required: true,
},
password: {
type: 'string',
required: true,
},
},
exits: {
invalidEmailOrUsername: {
responseType: 'unauthorized',
},
invalidPassword: {
responseType: 'unauthorized',
},
},
async fn(inputs) {
const user = await sails.helpers.users.getOneByEmailOrUsername(inputs.emailOrUsername);
if (!user) {
sails.log.warn(
`Invalid email or username: "${inputs.emailOrUsername}"! (IP: ${getRemoteAddress(
this.req,
)})`,
);
throw Errors.INVALID_EMAIL_OR_USERNAME;
}
if (!bcrypt.compareSync(inputs.password, user.password)) {
sails.log.warn(`Invalid password! (IP: ${getRemoteAddress(this.req)})`);
throw Errors.INVALID_PASSWORD;
}
return {
item: sails.helpers.utils.createToken(user.id),
};
},
};