-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomerService.js
More file actions
115 lines (105 loc) · 3.88 KB
/
customerService.js
File metadata and controls
115 lines (105 loc) · 3.88 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const express = require('express');
const router = express.Router();
const Datastore = require('nedb');
const path = require('path');
const db = new Datastore({ filename: path.join(__dirname, 'users.db'), autoload: true });
db.ensureIndex({ fieldName: 'email', unique: true });
db.ensureIndex({ fieldName: 'username', unique: true });
db.ensureIndex({ fieldName: 'cpf', unique: true });
function validarCPF(cpf) {
cpf = cpf.replace(/\D/g, '');
if (cpf.length !== 11 || /^([0-9])\1+$/.test(cpf)) return false;
let soma = 0, resto;
for (let i = 1; i <= 9; i++) soma += parseInt(cpf[i-1]) * (11 - i);
resto = (soma * 10) % 11;
if (resto === 10 || resto === 11) resto = 0;
if (resto !== parseInt(cpf[9])) return false;
soma = 0;
for (let i = 1; i <= 10; i++) soma += parseInt(cpf[i-1]) * (12 - i);
resto = (soma * 10) % 11;
if (resto === 10 || resto === 11) resto = 0;
if (resto !== parseInt(cpf[10])) return false;
return true;
}
function validarTelefone(telefone) {
telefone = telefone.replace(/\D/g, '');
return telefone.length >= 10 && telefone.length <= 11;
}
function validarMaioridade(dataNasc) {
const hoje = new Date();
const nasc = new Date(dataNasc);
let idade = hoje.getFullYear() - nasc.getFullYear();
const m = hoje.getMonth() - nasc.getMonth();
if (m < 0 || (m === 0 && hoje.getDate() < nasc.getDate())) idade--;
return idade >= 18;
}
function validateCustomer(data, isRegister = true, cb) {
const errors = [];
if (!data.name || data.name.length < 3) {
errors.push('Nome deve ter pelo menos 3 caracteres.');
}
if (!data.email || !/^\S+@\S+\.\S+$/.test(data.email)) {
errors.push('Email inválido.');
}
if (!data.cpf || !validarCPF(data.cpf)) {
errors.push('CPF inválido.');
}
if (!data.phone || !validarTelefone(data.phone)) {
errors.push('Telefone inválido.');
}
if (!data.birth || !validarMaioridade(data.birth)) {
errors.push('É necessário ser maior de 18 anos.');
}
if (!data.username || data.username.length < 3) {
errors.push('Usuário deve ter pelo menos 3 caracteres.');
}
if (!data.password || data.password.length < 6) {
errors.push('Senha deve ter pelo menos 6 caracteres.');
}
if (isRegister && data.password !== data.password2) {
errors.push('As senhas não coincidem.');
}
if (isRegister) {
db.findOne({ $or: [
{ email: data.email },
{ username: data.username },
{ cpf: data.cpf }
] }, (err, user) => {
if (user) {
if (user.email === data.email) errors.push('Já existe um cadastro com este email.');
if (user.username === data.username) errors.push('Já existe um cadastro com este usuário.');
if (user.cpf === data.cpf) errors.push('Já existe um cadastro com este CPF.');
}
cb(errors);
});
} else {
cb(errors);
}
}
router.post('/register', (req, res) => {
const data = req.body;
validateCustomer(data, true, (errors) => {
if (errors.length) return res.json({ success: false, errors });
db.insert({ name: data.name, email: data.email, cpf: data.cpf, phone: data.phone, birth: data.birth, username: data.username, password: data.password }, (err, newUser) => {
if (err) {
return res.json({ success: false, errors: [err.message] });
}
res.json({ success: true });
});
});
});
router.post('/login', (req, res) => {
const { usernameOrEmail, password } = req.body;
db.findOne({ $or: [{ username: usernameOrEmail }, { email: usernameOrEmail }] }, (err, user) => {
if (!user || user.password !== password) {
return res.json({ success: false, errors: ['Usuário ou senha incorretos.'] });
}
res.json({ success: true, user: { id: user._id, name: user.name, email: user.email, username: user.username } });
});
});
router.get('/users', (req, res) => {
db.find({}, { password: 0 }).sort({ name: 1 }).exec((err, users) => {
res.json(users);
});
});
module.exports = router;