This commit is contained in:
2021-06-22 20:45:25 -05:00
parent 14f9937d93
commit 600358d640
9 changed files with 628 additions and 83 deletions

View File

@@ -2,54 +2,72 @@ const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const User = require("../models/user")
const User = require("../models/user");
//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,
});
if (process.env.REGISTER == "true") {
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
const passEncrypted = bcrypt.hashSync(password, 10);
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",
const newUser = new User({
name: name,
email: email,
password: password,
});
} catch (error) {
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}` });
}
});
}
else{
router.post("/register", (req, res) => {
return res
.status(500)
.json({ status: "fail", error: `internal error:${error}` });
}
});
.status(500)
.json({ status: "faill", error: `No tiene permitido crear usuarios nuevos` });
})
}
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" });
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" });
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(