Skip to content

Commit 548402a

Browse files
committed
nexting around
1 parent 62db8dc commit 548402a

File tree

2 files changed

+58
-48
lines changed

2 files changed

+58
-48
lines changed
+48-39
Original file line numberDiff line numberDiff line change
@@ -1,117 +1,126 @@
1-
const express = require("express") // CommonJS import style!
1+
const express = require("express"); // CommonJS import style!
22

33
// mongoose models for MongoDB data manipulation
4-
const mongoose = require("mongoose")
5-
const User = require("../models/User.js")
4+
const mongoose = require("mongoose");
5+
const User = require("../models/User.js");
66

77
// a method that constains code to handle authentication-specific routes
88
const authenticationRouter = () => {
99
// create a new router that we can customize
10-
const router = express.Router()
10+
const router = express.Router();
1111

1212
// a route to handle user signup requests to /auth/signup
13-
router.post("/signup", async (req, res) => {
13+
router.post("/signup", async (req, res, next) => {
1414
// console.log(`Incoming signup data: ${JSON.stringify(req.body, null, 0)}`)
1515
// grab the username and password from the POST body
16-
const username = req.body.username
17-
const password = req.body.password
16+
const username = req.body.username;
17+
const password = req.body.password;
1818

1919
if (!username || !password) {
2020
// no username or password received in the POST body... send an error
2121
res.status(401).json({
2222
success: false,
2323
message: `No username or password supplied.`,
24-
})
24+
});
25+
next();
2526
}
2627

2728
// try to create a new user
2829
try {
29-
const user = await new User({ username, password }).save()
30+
const user = await new User({ username, password }).save();
3031
// user saved successfully... send a success response
31-
console.error(`New user: ${user}`)
32-
const token = user.generateJWT() // generate a signed token
32+
console.error(`New user: ${user}`);
33+
const token = user.generateJWT(); // generate a signed token
3334
res.json({
3435
success: true,
3536
message: "User saved successfully.",
3637
token: token,
3738
username: user.username,
38-
}) // send the token to the client to store
39+
}); // send the token to the client to store
40+
next();
3941
} catch (err) {
4042
// error saving user to database... send an error response
41-
console.error(`Failed to save user: ${err}`)
43+
console.error(`Failed to save user: ${err}`);
4244
res.status(500).json({
4345
success: false,
4446
message: "Error saving user to database.",
4547
error: err,
46-
})
48+
});
49+
next();
4750
}
48-
})
51+
});
4952

5053
// a route to handle login attempts requested to /auth/login
51-
router.post("/login", async function (req, res) {
54+
router.post("/login", async function (req, res, next) {
5255
// grab the name and password that were submitted as POST body data
53-
const username = req.body.username
54-
const password = req.body.password
56+
const username = req.body.username;
57+
const password = req.body.password;
5558
// console.log(`${username}, ${password}`)
5659

5760
if (!username || !password) {
5861
// no username or password received in the POST body... send an error
5962
res
6063
.status(401)
61-
.json({ success: false, message: `No username or password supplied.` })
64+
.json({ success: false, message: `No username or password supplied.` });
65+
next();
6266
}
6367

6468
// find this user in the database
6569
try {
66-
const user = await User.findOne({ username: username }).exec()
70+
const user = await User.findOne({ username: username }).exec();
6771
// check if user was found
6872
if (!user) {
69-
console.error(`User not found.`)
70-
return res.status(401).json({
73+
console.error(`User not found.`);
74+
res.status(401).json({
7175
success: false,
7276
message: "User not found in database.",
73-
})
77+
});
78+
next();
7479
}
7580
// if user exists, check if password is correct
7681
else if (!user.validPassword(password)) {
77-
console.error(`Incorrect password.`)
78-
return res.status(401).json({
82+
console.error(`Incorrect password.`);
83+
res.status(401).json({
7984
success: false,
8085
message: "Incorrect password.",
81-
})
86+
});
87+
next();
8288
}
8389
// user found and password is correct... send a success response
84-
console.log("User logged in successfully.")
85-
const token = user.generateJWT() // generate a signed token
90+
console.log("User logged in successfully.");
91+
const token = user.generateJWT(); // generate a signed token
8692
res.json({
8793
success: true,
8894
message: "User logged in successfully.",
8995
token: token,
9096
username: user.username,
91-
}) // send the token to the client to store
97+
}); // send the token to the client to store
98+
next();
9299
} catch (err) {
93100
// check error
94-
console.error(`Error looking up user: ${err}`)
95-
return res.status(500).json({
101+
console.error(`Error looking up user: ${err}`);
102+
res.status(500).json({
96103
success: false,
97104
message: "Error looking up user in database.",
98105
error: err,
99-
})
106+
});
107+
next();
100108
}
101-
})
109+
});
102110

103111
// a route to handle logging out requests to /auth/logout
104-
router.get("/logout", function (req, res) {
112+
router.get("/logout", function (req, res, next) {
105113
// nothing really to do here... logging out with JWT authentication is handled entirely by the front-end by deleting the token from the browser's memory
106114
res.json({
107115
success: true,
108116
message:
109117
"There is actually nothing to do on the server side... you simply need to delete your token from the browser's local storage!",
110-
})
111-
})
118+
});
119+
next();
120+
});
112121

113-
return router
114-
}
122+
return router;
123+
};
115124

116125
// export the router
117-
module.exports = authenticationRouter
126+
module.exports = authenticationRouter;
+10-9
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
const express = require("express") // CommonJS import style!
2-
const passport = require("passport")
1+
const express = require("express"); // CommonJS import style!
2+
const passport = require("passport");
33

44
// a method that constains code to handle routes related to protected content that requires login to access
55
const protectedContentRoutes = () => {
66
// create a new router that we can customize
7-
const router = express.Router()
7+
const router = express.Router();
88

99
// a route that is protected... only authenticated users can access it.
1010
router.get(
1111
"/",
1212
passport.authenticate("jwt", { session: false }),
13-
(req, res) => {
13+
(req, res, next) => {
1414
// our jwt passport config will send error responses to unauthenticated users will
1515
// so we only need to worry about sending data to properly authenticated users!
1616

@@ -22,12 +22,13 @@ const protectedContentRoutes = () => {
2222
},
2323
message:
2424
"Congratulations: you have accessed this route because you have a valid JWT token!",
25-
})
25+
});
26+
next();
2627
}
27-
)
28+
);
2829

29-
return router
30-
}
30+
return router;
31+
};
3132

3233
// export the function that contains code to handle cookie-related routes
33-
module.exports = protectedContentRoutes
34+
module.exports = protectedContentRoutes;

0 commit comments

Comments
 (0)