-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (88 loc) · 2.44 KB
/
index.js
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
require("dotenv").config();
const { sequelize, User } = require("./models/Model");
const express = require("express");
const routes = require("./routes");
const db = require("./db");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local");
const bcrypt = require("bcryptjs");
const APP_PORT = process.env.APP_PORT || 3000;
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.set("view engine", "ejs");
//db();
app.use(
session({
secret: "AlgúnTextoSuperSecreto",
resave: false,
saveUninitialized: false,
})
);
app.use(passport.session());
passport.use(
new LocalStrategy(async (username, password, done) => {
const user = await User.findOne({ where: { email: username } });
if (!user) {
return done(null, false, { message: "Incorrect email o password" });
}
const comparePassword = await bcrypt.compare(password, user.password);
if (!comparePassword) {
return done(null, false, { message: "Incorrect email o password" });
}
return done(null, user);
})
);
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findByPk(id)
.then((user) => {
done(null, user); // Usuario queda disponible en req.user.
})
.catch((error) => {
done(error, user);
});
});
app.get("/registro", async (req, res) => {
res.render("register");
});
app.post("/registro", async (req, res) => {
const firstname = req.body.firstname;
const lastname = req.body.lastname;
const password = req.body.password;
passport.authenticate("local", {
successRedirect: "/admin",
failureRedirect: "/login",
});
const [user, created] = await User.findOrCreate({
where: {
email: req.body.username,
firstname: firstname,
lastname: lastname,
password: password,
},
});
if (created) {
req.login(user, () => res.redirect("/admin"));
} else {
res.redirect("/login");
}
});
app.get("/login", async (req, res) => {
res.render("login");
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/admin",
failureRedirect: "/login",
})
);
app.use(routes);
app.listen(APP_PORT, () => {
console.log(`\n[Express] Servidor corriendo en el puerto ${APP_PORT}.`);
console.log(`[Express] Ingresar a http://localhost:${APP_PORT}/blog.\n`);
});