Skip to content

Commit 75b1271

Browse files
committed
Added "/auth" router and configured Passport, JWT.
1 parent 4e7bc6d commit 75b1271

18 files changed

+360
-12
lines changed

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
NODE_ENV=development
1212
PORT=4000 # Specifiy which PORT backend should be run on and also expose it in docker container.
1313

14+
# Token Generting Specifics
15+
JWT_SECRET=mySuperSecretsP4$$w0rD
16+
JWT_EXPIRES=3600s
17+
1418
# Below are mostly needed in CI enviroment.
1519
DOCKER_USERNAME=
1620
DOCKER_PASSWORD=

configs/mainConfigs.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ const { parsed: parsedEnvValues = {} } = dotenv.config(); // Loading & Parsing e
66
// Default values for any enviroment. (Only applicable if specifcally not provided in terminal enviroment or .env file)
77
const defaultEnvValues = {
88
NODE_ENV: "development",
9-
PORT: "4000"
9+
PORT: "4000",
10+
11+
JWT_SECRET: "superPassword!@#$",
12+
JWT_EXPIRES: "3600s"
1013
};
1114

1215
// Provide any override default value for specific enviroment here.

errorHandlers/handleCustomError.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Custom Fucntion to Generate custom errors and redirect them to "customErrorHandler" middleware.
2+
3+
module.exports = (next, config = {}) => {
4+
// Configs and default values
5+
const {
6+
err = new Error(),
7+
customErrType = "clientError",
8+
statusCode = 500,
9+
customErrMsg = "Server Error Occured.",
10+
log = false
11+
} = config;
12+
13+
const modifiedError = Object.assign({}, err, {
14+
customErrType,
15+
statusCode,
16+
customErrMsg,
17+
log
18+
});
19+
20+
// This is get catched by "customErrorHandler" middleware.
21+
next(modifiedError);
22+
};
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Custome Error Middleware to catch error directed by "handleCustomError(next, config)".
2+
3+
const config = require("../../configs/mainConfigs");
4+
5+
module.exports = (err, req, res, next) => {
6+
// Loggin error if its specified (log:true) and in development enviroment.
7+
if (err.log === true && config.NODE_ENV === "development") {
8+
console.log("Error Occured : \n", err);
9+
}
10+
11+
// Only catch error that have custom property called "customErrType". All other errors get directed to next error middleware.
12+
if (err.customErrType) {
13+
return res.status(err.statusCode || 500).json({
14+
success: false,
15+
errMsg: err.customErrMsg || "Server Error Occured."
16+
});
17+
}
18+
19+
return next(err);
20+
};
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Default Error Middleware to catch error directed by "next(err)" and any other errors that didn't get catched by other error middleware.
2+
const config = require("../../configs/mainConfigs");
3+
4+
module.exports = (err, req, res, next) => {
5+
// Loggin error in development enviroment
6+
if (config.NODE_ENV === "development") {
7+
console.log("Error Occured : \n", err);
8+
}
9+
10+
res.status(500).json({ success: false, errMsg: "Server Error Occured." });
11+
};

expressServer.integration.test.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
const request = require("supertest");
2-
32
const expressServer = require("./expressServer");
4-
const rootRouter = require("./routers/rootRouter");
53

64
describe("Express Server Starting Point", () => {
75
it("Should handle requests to Root Path sucessfully.", done => {

expressServer.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
const express = require("express");
22
const morgan = require("morgan");
33
const cors = require("cors");
4+
const passport = require("passport");
45

6+
require("./passport/passportStrategies");
57
const config = require("./configs/mainConfigs");
68

7-
const rootRouter = require("./routers/rootRouter");
9+
const customErrorHandler = require("./errorHandlers/middlewares/customErrorHandler");
10+
const defaultErrorHandler = require("./errorHandlers/middlewares/defaultErrorHandler");
11+
12+
const rootRouter = require("./routers/rootRouter/rootRouter");
13+
const authRouter = require("./routers/authRouter/authRouter");
814

915
const app = express();
1016

@@ -17,12 +23,15 @@ app.use(cors()); // Enable all CORS requests from any origin.
1723
app.use(express.json());
1824
app.use(express.urlencoded({ extended: false }));
1925

26+
// Public Endpoints
2027
app.use("/", rootRouter);
28+
app.use("/auth", authRouter);
2129

22-
app.use((err, req, res, next) => {
23-
res.status(500).json({ success: false, errMsg: "Server Error Occured." });
24-
});
30+
// Error Handlers
31+
app.use(customErrorHandler);
32+
app.use(defaultErrorHandler);
2533

34+
// Path not found is not a error. So we need custom middleware to catch them.
2635
app.use((req, res) => {
2736
res.status(404).json({ success: false, errMsg: "Requested Path Not Found." });
2837
});

package-lock.json

Lines changed: 120 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@
2626
"cors": "^2.8.5",
2727
"dotenv": "^6.2.0",
2828
"express": "^4.16.4",
29-
"morgan": "^1.9.1"
29+
"jsonwebtoken": "^8.4.0",
30+
"morgan": "^1.9.1",
31+
"passport": "^0.4.0",
32+
"passport-jwt": "^4.0.0",
33+
"passport-local": "^1.0.0"
3034
},
3135
"devDependencies": {
3236
"codecov": "^3.1.0",
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const passport = require("passport");
2+
const handleCustomError = require("../../errorHandlers/handleCustomError");
3+
4+
module.exports = (req, res, next) => {
5+
passport.authenticate(
6+
"jwt",
7+
{
8+
session: false
9+
},
10+
(err, user, info) => {
11+
if (err) {
12+
// Error Handled by "deafultErrorHandler" middleware.
13+
return next(err);
14+
}
15+
16+
// "user" not populated mean not authenticated.
17+
if (!user) {
18+
// Error Handled by "customErrorHandler" middleware.
19+
return handleCustomError(next, {
20+
customErrType: "clientError",
21+
customErrMsg: "Invalid Token.",
22+
statusCode: 401
23+
});
24+
}
25+
26+
// When custom error handlers used, its our responsibility to pass this if needed.
27+
req.user = user;
28+
29+
return next();
30+
}
31+
)(req, res, next);
32+
};

0 commit comments

Comments
 (0)