-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathauth.js
More file actions
148 lines (131 loc) · 4.37 KB
/
auth.js
File metadata and controls
148 lines (131 loc) · 4.37 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
const passport = require("passport"); // Passport.js for authentication
const validator = require("validator"); // To validate user input like email, password
const User = require("../models/User"); // Your User model for database interaction
// Render login page if user is not logged in, else redirect to profile
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect("/profile");
}
res.render("login", {
title: "Login",
});
};
// Handle login POST request with validation and passport authentication
exports.postLogin = (req, res, next) => {
const validationErrors = [];
// Validate email format
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: "Please enter a valid email address." });
// Ensure password is not blank
if (validator.isEmpty(req.body.password))
validationErrors.push({ msg: "Password cannot be blank." });
// If validation errors exist, flash errors and redirect to login page
if (validationErrors.length) {
req.flash("errors", validationErrors);
return res.redirect("/login");
}
// Normalize the email to a standard format
req.body.email = validator.normalizeEmail(req.body.email, {
gmail_remove_dots: false,
});
// Authenticate using Passport local strategy
passport.authenticate("local", (err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
// If authentication fails, flash error messages and redirect
req.flash("errors", info);
return res.redirect("/login");
}
// Log in the user if authentication is successful
req.logIn(user, (err) => {
if (err) {
return next(err);
}
// Flash success message and redirect to originally requested page or profile
req.flash("success", { msg: "Success! You are logged in." });
res.redirect(req.session.returnTo || "/profile");
});
})(req, res, next);
};
// Log out the user, destroy session and redirect to homepage
exports.logout = (req, res) => {
req.logout(() => {
console.log('User has logged out.')
});
req.session.destroy((err) => {
if (err)
console.log("Error : Failed to destroy the session during logout.", err);
req.user = null;
res.redirect("/");
});
};
// Render signup page if user is not logged in, else redirect to profile
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect("/profile");
}
res.render("signup", {
title: "Create Account",
});
};
// Handle signup POST request with validation, user creation, and login
exports.postSignup = (req, res, next) => {
const validationErrors = [];
// Validate email format
if (!validator.isEmail(req.body.email))
validationErrors.push({ msg: "Please enter a valid email address." });
// Validate password length (min 8 characters)
if (!validator.isLength(req.body.password, { min: 8 }))
validationErrors.push({
msg: "Password must be at least 8 characters long",
});
// Confirm password and confirmPassword match
if (req.body.password !== req.body.confirmPassword)
validationErrors.push({ msg: "Passwords do not match" });
// If validation errors exist, flash errors and redirect to signup page
if (validationErrors.length) {
req.flash("errors", validationErrors);
return res.redirect("../signup");
}
// Normalize email
req.body.email = validator.normalizeEmail(req.body.email, {
gmail_remove_dots: false,
});
// Create a new user instance
const user = new User({
userName: req.body.userName,
email: req.body.email,
password: req.body.password,
});
// Check if user with same email or username already exists
User.findOne(
{ $or: [{ email: req.body.email }, { userName: req.body.userName }] },
(err, existingUser) => {
if (err) {
return next(err);
}
if (existingUser) {
// If user exists, flash error and redirect to signup page
req.flash("errors", {
msg: "Account with that email address or username already exists.",
});
return res.redirect("../signup");
}
// Save the new user to database
user.save((err) => {
if (err) {
return next(err);
}
// Automatically log in the newly registered user
req.logIn(user, (err) => {
if (err) {
return next(err);
}
res.redirect("/profile");
});
});
}
);
};