-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathauth.controller.js
More file actions
92 lines (78 loc) · 2.15 KB
/
auth.controller.js
File metadata and controls
92 lines (78 loc) · 2.15 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
const User = require("../models/User.model");
const mongoose = require("mongoose");
// signup
module.exports.signup = (req, res, next) => {
res.render("auth/signup"); // Correct path FINALLYYYYYY
};
// doSignup
module.exports.doSignup = (req, res, next) => {
User.create(req.body)
.then((user) => {
res.redirect("/login");
})
.catch((err) => {
if (err instanceof mongoose.Error.ValidationError) {
// Handle validation errors
res.render("auth/signup", {
user: {
email: req.body.email,
},
errors: err.errors,
});
} else if (err.code === 11000) {
// Handle duplicate key error
res.render("auth/signup", {
user: {
email: req.body.email,
},
errors:{
password:"This email is already registered. Please use a different one."
}
});
} else {
// Handle any other errors
next(err);
}
});
}
// Render login form
module.exports.login = (req, res, next) => {
res.render("auth/login"); // Correct view path
};
// Handle login submission
module.exports.doLogin = (req, res, next) => {
const { email, password } = req.body;
const renderWithErrors = () => {
res.render("auth/login", {
email,
error: "Email o contraseña incorrectos", // Incorrect email or password
});
};
// The juicy part we did in class
User.findOne({ email })
.then((user) => {
if (user) {
return user.checkPassword(password).then((match) => {
if (match) {
req.session.userId = user.id; // Save user ID in session (cookie magic!)
res.redirect("/profile");
} else {
console.log("Contraseña incorrecta");
renderWithErrors();
}
});
} else {
console.log("No existe usuario con ese email");
renderWithErrors();
}
})
.catch((err) => next(err));
};
// How you logout
module.exports.logout = (req, res, next) => {
req.session.destroy();
res.clearCookie("express-cookie");
res.redirect("/login");
};
// Add the main
// Add the private