-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
94 lines (84 loc) · 2.68 KB
/
app.js
File metadata and controls
94 lines (84 loc) · 2.68 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
require('dotenv').config();
const express = require('express');
const app = express();
const asyncHandler = require('express-async-handler');
const mongoose = require('mongoose');
const User = require('./models/user');
const { sendEmail } = require('./utils/sendMail');
var validator = require('email-validator');
var bodyParser = require('body-parser');
const MongoDBKey = process.env.MONGODB_KEY;
const MongoDBName = process.env.MONGODB_NAME;
const dev_db_url = `mongodb+srv://admin:${MongoDBKey}@cluster0.lnrds0m.mongodb.net/${MongoDBName}?retryWrites=true&w=majority`;
const mongoDB = dev_db_url;
async function main() {
await mongoose.connect(mongoDB);
}
main().catch((err) => console.log(err));
app.use(bodyParser.json());
// Define as rotas da aplicação
app.post(
'/create_account',
asyncHandler(async (req, res) => {
const verificationCode = Math.floor(Math.random() * 1000000);
const { username, email } = req.body;
if (!validator.validate(email)) {
return res.status(400).send('Email inválido');
}
const userWithSameEmail = await User.findOne({ email: email });
if (userWithSameEmail) {
return res.status(400).send('Email já cadastrado');
}
if (typeof username !== 'string' || !username.length > 0) {
return res.status(400).send('Usuário inválido');
}
const userWithSameUsername = await User.findOne({ username: username });
if (userWithSameUsername) {
return res.status(400).send('Usuário já existe');
}
const user = new User({
username: username,
email: email,
verificationCode: verificationCode,
});
await user.save();
await sendEmail(email, verificationCode);
return res.status(201).send('Usuário criado com sucesso');
})
);
app.post(
'/validate_user',
asyncHandler(async (req, res) => {
const { username, verificationCode } = req.body;
const user = await User.findOne({
username: username,
verificationCode: verificationCode,
});
if (!user) {
return res.status(400).send('Usuário não encontrado');
}
if (user.verified === true) {
return res.status(400).send('Usuário já validado');
}
user.verified = true;
await user.save();
return res.status(200).send('Usuário validado com sucesso');
})
);
app.post(
'/login',
asyncHandler(async (req, res) => {
const { username } = req.body;
const user = await User.findOne({
username: username,
});
if (user.verified === false) {
return res.status(400).send('Usuário não validado');
}
return res.send('Olá, usuário validado!');
})
);
// Inicializa o servidor
app.listen(3000, () => {
console.log('Servidor rodando na porta 3000');
});