endpoint usuario y compras

This commit is contained in:
2021-04-18 20:24:56 -05:00
parent 4766d0ef3c
commit 4a7fb24eb2
13 changed files with 12114 additions and 1 deletions

22
routes/compras.js Normal file
View File

@@ -0,0 +1,22 @@
const router = require("express").Router();
const Compra = require("../models/compras");
const { checkAuth } = require("../middlewares/authentication");
router.get("/compras", checkAuth, async (req, res) => {
var compras;
compras = await Compra.find({ user: req.userData._id }).sort({
fecha: "desc",
});
return res.send(
{
status:"ok",
data:compras
}
)
});
module.exports = router;

72
routes/users.js Normal file
View File

@@ -0,0 +1,72 @@
const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
import User from "../models/user.js";
//AUTH
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
const passEncrypted = bcrypt.hashSync(password, 10);
const newUser = new User({
name: name,
email: email,
password: password,
});
const emailUser = await User.findOne({ email: email });
if (emailUser) {
return res
.status(500)
.json({ status: "fail", error: "email already exists" });
}
try {
newUser.password = await newUser.encryptPassword(password);
await newUser.save();
res.json({
status: "ok",
msg: "Usuario creado",
});
} catch (error) {
return res
.status(500)
.json({ status: "fail", error: `internal error:${error}` });
}
});
router.post("/login", async (req, res) => {
const { email, password } = req.body;
var user = await User.findOne({ email: email });
if (!user) {
res.status(401).json({ status: "fail", error: "Invalid credentials email" });
return;
}
if (! await user.matchPassword(password)) {
return res.status(401).json({ status: "fail", error: "Invalid credentials pass" });
}
user.set("password", undefined, { strict: false });
const token = jwt.sign(
{
userData: user,
},
"api finanzas mdchaparror @4050#",
{ expiresIn: 60 * 60 * 24 * 30 }
);
const toSend = {
status: "ok",
userData: user,
token: token,
};
res.json(toSend);
});
//CRUD USER
module.exports = router;