-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
197 lines (157 loc) · 4.74 KB
/
Copy pathapp.js
File metadata and controls
197 lines (157 loc) · 4.74 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bcrypt= require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
//config JSON respnose
app.use(express.json());
//Models
const User = require('./models/User');
const Transaction = require('./models/Transaction');
app.get('/', (req, res) => {
res.status(200).json({ msg: "Backend on fire!🔥"})
})
// private route
app.get('/user/:id', checkToken, async (req, res) => {
const id = req.params.id;
const user = await User.findById(id, '-password');
if(!user) {
return res.status(404).json({ msg: 'user não encontrado'})
}
return res.status(200).json({ user })
})
function checkToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split("")[1]
if(!token) {
return res.status(401).json({ msg: "acesso negado!" })
}
try {
const secret = process.env.SECRET
jwt.verify(token, secret)
next()
} catch (error) {
res.status(400).json({ msg: 'token inválido' })
}
}
// get transaction
app.get('/users/:userId/transactions', async (req, res) => {
try {
const { userId } = req.params;
const user = await User.findById(userId);
if (!user) {
return res.status(400).send({ error: 'Usuário não encontrado' });
}
const transactions = await Transaction.find({ user: userId });
console.log(transactions)
return res.json({transactions})
} catch (error) {
console.log(error)
}
})
// create transaction
app.post('/transactions/', async (req, res) => {
try {
const user = await User.findOne({ });
const { name, amount, type, created_at} = req.body;
if(!name) {
return res.status(422).json({ msg: 'Campo nome é obrigatório'})
}
if(!amount) {
return res.status(422).json({ msg: 'Campo valor é obrigatório'})
}
if(!type) {
return res.status(422).json({ msg: 'Campo tipo é obrigatório'})
}
const transaction = await new Transaction({
name,
amount,
type,
created_at,
user: user._id
})
console.log(transaction)
await transaction.save();
res.status(201).json({ msg: `transação criada com sucesso! ${transaction}`})
} catch (error) {
console.log(error)
res.status(500).json({ msg: error})
}
})
// create user
app.post('/create-user', async (req, res) => {
const { name, email, password, password_confirmation, _id } = req.body;
if(!name) {
return res.status(422).json({ msg: 'Campo nome é obrigatório'})
}
if(!email) {
return res.status(422).json({ msg: 'Campo email é obrigatório'})
}
if(!password) {
return res.status(422).json({ msg: 'Campo senha é obrigatório'})
}
if(!password_confirmation) {
return res.status(422).json({ msg: 'Campo confirmação de senha é obrigatório'})
}
if(password !== password_confirmation) {
return res.status(422).json({ msg: 'As senhas não conferem'})
}
const userExists = await User.findOne({ email: email });
if(userExists) {
return res.status(422).json({msg: 'Emai já cadastrado!'})
}
// create password
const salt = await bcrypt.genSalt(12);
const passwordHash = await bcrypt.hash(password, salt)
//create user
const user = new User({
name,
email,
password: passwordHash
})
try {
await user.save();
res.status(201).json({ msg: `usuario criado com sucesso! ${user}`})
} catch (error) {
console.log(error)
res.status(500).json({ msg: error})
}
})
app.post('/login', async (req, res) => {
const {email, password} = req.body;
if(!email) {
return res.status(422).json({ msg: 'Campo email é obrigatório'})
}
if(!password) {
return res.status(422).json({ msg: 'Campo senha é obrigatório'})
}
const user = await User.findOne({ email: email });
if(!user) {
return res.status(404).json({ msg: 'Usuário não cadastrado!'})
}
const checkPassword = await bcrypt.compare(password, user.password)
if(!checkPassword) {
return res.status(422).json({ msg: 'Senha inválida' })
}
try {
const secret = process.env.SECRET
const token = jwt.sign({
id: user._id
}, secret,
)
res.status(200).json({ msg: 'Usuário logado', token, user})
} catch (error) {
console.log(error);
res.status(500).json({ msg: error})
}
})
// credentials
const dbUser = process.env.DB_USER
const dbPassword = process.env.DB_PASSWORD
mongoose.set("strictQuery", true);
mongoose.connect(`mongodb+srv://${dbUser}:${dbPassword}@cluster0.beefml3.mongodb.net/?retryWrites=true&w=majority`,)
.then(() => {
app.listen(3000)
console.log('database connection!')
}).catch((err) => console.log(err))