Merge pull request #981 from Rushi1109/915-be-add-new-endpoint-for-refreshing-access-token

Add endpoint to refresh auth token
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-23 10:03:40 +08:00
commit a58c1a478a
5 files changed
+229 -3

No files matched your search

+60
View File
@@ -173,6 +173,65 @@ const loginUser = async (req, res, next) => {
}
};
/**
* Generates new auth token if the refresh token is valid
* @async
* @param {Express.Request} req - The Express request object.
* @property {Object} req.headers - The parameter of the request.
* @param {Express.Response} res - The Express response object.
* @param {function} next - The next middleware function.
* @returns {Object} The response object with a success status, a message indicating new auth token is generated.
* @throws {Error} If there is an error during the process such as any of the token is not received
*/
const refreshAuthToken = async (req, res, next) => {
try {
// check for refreshToken
const refreshToken = req.headers["x-refresh-token"];
if (!refreshToken) {
// No refresh token provided
const error = new Error(errorMessages.NO_REFRESH_TOKEN);
error.status = 401;
error.service = SERVICE_NAME;
error.method = "refreshAuthToken";
return next(error);
}
// Verify refresh token
const appSettings = await req.settingsService.getSettings();
const { refreshTokenSecret } = appSettings;
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
if (refreshErr) {
// Invalid or expired refresh token, trigger logout
const errorMessage =
refreshErr.name === "TokenExpiredError"
? errorMessages.EXPIRED_REFRESH_TOKEN
: errorMessages.INVALID_REFRESH_TOKEN;
const error = new Error(errorMessage);
error.status = 401;
error.service = SERVICE_NAME;
return next(error);
}
});
// Refresh token is valid and unexpired, generate new access token
const oldAuthToken = getTokenFromHeaders(req.headers);
const { jwtSecret } = await req.settingsService.getSettings();
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
// delete old token related data
delete payloadData.iat;
delete payloadData.exp;
const newAuthToken = issueToken(payloadData, tokenType.ACCESS_TOKEN, appSettings);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "refreshAuthToken"));
}
};
/**
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
* @async
@@ -455,6 +514,7 @@ export {
issueToken,
registerUser,
loginUser,
refreshAuthToken,
editUser,
checkSuperadminExists,
requestRecovery,
+72 -1
View File
@@ -261,6 +261,77 @@
}
}
},
"/auth/refresh": {
"post": {
"tags": [
"auth"
],
"description": "Generates a new auth token if the refresh token is valid.",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {}
}
}
},
"required": false
},
"parameters": [
{
"name": "x-refresh-token",
"in": "header",
"description": "Refresh token required to generate a new auth token.",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "authorization",
"in": "header",
"description": "Old access token, used to extract payload).",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "New access token generated.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SuccessResponse"
}
}
}
},
"401": {
"description": "Unauthorized or invalid refresh token.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
"500": {
"description": "Internal Server Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
}
}
}
},
"/auth/user/{userId}": {
"put": {
"tags": [
@@ -2502,4 +2573,4 @@
}
}
}
}
}
+2
View File
@@ -11,6 +11,7 @@ const upload = multer();
import {
registerUser,
loginUser,
refreshAuthToken,
editUser,
requestRecovery,
validateRecovery,
@@ -23,6 +24,7 @@ import {
//Auth routes
router.post("/register", upload.single("profileImage"), registerUser);
router.post("/login", loginUser);
router.post("/refresh", refreshAuthToken);
router.put("/user/:userId", upload.single("profileImage"), verifyJWT, editUser);
router.get("/users/superadmin", checkSuperadminExists);
router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), getAllUsers);
@@ -2,6 +2,7 @@ import {
issueToken,
registerUser,
loginUser,
refreshAuthToken,
editUser,
checkSuperadminExists,
requestRecovery,
@@ -13,8 +14,9 @@ import {
import jwt from "jsonwebtoken";
import { errorMessages, successMessages } from "../../utils/messages.js";
import sinon from "sinon";
import { tokenType } from "../../utils/utils.js";
import { getTokenFromHeaders, tokenType } from "../../utils/utils.js";
import logger from "../../utils/logger.js";
import e from "cors";
describe("Auth Controller - issueToken", () => {
let stub;
@@ -303,6 +305,97 @@ describe("Auth Controller - loginUser", () => {
});
});
describe("Auth Controller - refreshAuthToken", () => {
let req, res, next, issueTokenStub;
beforeEach(() => {
req = {
headers: {
"x-refresh-token": "valid_refresh_token",
authorization: "Bearer old_auth_token",
},
settingsService: {
getSettings: sinon.stub().resolves({
jwtSecret: "my_secret",
refreshTokenSecret: "my_refresh_secret",
}),
},
};
res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
next = sinon.stub();
sinon.stub(jwt, "verify");
issueTokenStub = sinon.stub().returns("new_auth_token");
sinon.replace({ issueToken }, "issueToken", issueTokenStub);
});
afterEach(() => {
sinon.restore();
});
it("should reject if no refresh token is provided", async () => {
delete req.headers["x-refresh-token"];
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.NO_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if the refresh token is invalid", async () => {
jwt.verify.yields(new Error("invalid token"));
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.INVALID_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if the refresh token is expired", async () => {
const error = new Error("Token expired");
error.name = "TokenExpiredError";
jwt.verify.yields(error);
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal(errorMessages.EXPIRED_REFRESH_TOKEN);
expect(next.firstCall.args[0].status).to.equal(401);
});
it("should reject if settingsService.getSettings fails", async () => {
req.settingsService.getSettings.rejects(
new Error("settingsService.getSettings error")
);
await refreshAuthToken(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("settingsService.getSettings error");
});
it("should generate a new auth token if the refresh token is valid", async () => {
const decodedPayload = { expiresIn: "60" };
jwt.verify.callsFake(() => {
return decodedPayload;
});
await refreshAuthToken(req, res, next);
expect(res.status.calledWith(200)).to.be.true;
expect(
res.json.calledWith({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: {
user: decodedPayload,
token: sinon.match.string,
refreshToken: "valid_refresh_token",
},
})
).to.be.true;
});
});
describe("Auth Controller - editUser", async () => {
let req, res, next, stub, user;
beforeEach(() => {
+1 -1
View File
@@ -62,7 +62,6 @@ const successMessages = {
ALERT_EDIT: "Alert edited successfully",
ALERT_DELETE: "Alert deleted successfully",
// Auth Controller
AUTH_CREATE_USER: "User created successfully",
AUTH_LOGIN_USER: "User logged in successfully",
AUTH_LOGOUT_USER: "User logged out successfully",
@@ -72,6 +71,7 @@ const successMessages = {
AUTH_RESET_PASSWORD: "Password reset successfully",
AUTH_ADMIN_CHECK: "Admin check completed successfully",
AUTH_DELETE_USER: "User deleted successfully",
AUTH_TOKEN_REFRESHED: "Auth token is refreshed",
// Check Controller
CHECK_CREATE: "Check created successfully",