Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/auth token middleware #16

Merged
merged 2 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 106 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"graphql": "^16.8.1",
"graphql-tag": "^2.12.6"
"graphql-tag": "^2.12.6",
"jsonwebtoken": "^9.0.2"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/jsonwebtoken": "^9.0.6",
"@types/node": "^20.11.21",
"@typescript-eslint/parser": "^7.1.0",
"eslint": "^8.54.0",
Expand Down
129 changes: 129 additions & 0 deletions src/util/authToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/**
* Express.js middleware for authentication token verification.
* Retrieves token from cookies, verifies it, and sends authentication context.
*/
import express from "express";
import jwt from "jsonwebtoken";

// Configuration
const secretKey = "top secret"; // Secret key for JWT signing and verification

/**
* Represents an optional value of type T.
*/
export type Optional<T> = T | null | undefined;

/**
* Represents a JWT token.
*/
export type Token = string;

/**
* Represents a decoded JWT token.
*/
export type DecodedToken = any;

/**
* Represents the response from a token creation operation.
*/
export type CreateTokenResponse = {
/** Indicates whether the token creation was successful. */
ok: boolean;
/** The body of the token if creation was successful. */
body: Optional<Token>;
/** An error object if an error occurred during token creation. */
error: Optional<Error>;
};

/**
* Represents the response from a token verification operation.
*/
export type VerifyTokenResponse = {
/** Indicates whether the token verification was successful. */
ok: boolean;
/** The decoded body of the token if verification was successful. */
body: Optional<DecodedToken>;
/** An error object if an error occurred during token verification. */
error: Optional<Error>;
};

/**
* Represents the context for authentication operations.
*/
export type Context = {
/** The authentication verification response. */
auth: VerifyTokenResponse;
};

/**
* Creates a JWT token with the provided data.
* @param data - The data to be encoded into the token.
* @param durationOfToken - Optional. Duration for which the token will be valid (default is "1h").
* @returns The response indicating the success or failure of token creation.
*/
export function createToken(data: any, durationOfToken: string = "1h"): CreateTokenResponse {
const token = jwt.sign(data, secretKey, {
expiresIn: durationOfToken,
});

return {
ok: true,
body: token,
error: undefined,
};
}

/**
* Verifies the authenticity of a JWT token.
* @param token - The token to be verified.
* @returns The response indicating the success or failure of token verification.
*/
export function verifyToken(token: Token): VerifyTokenResponse {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this check for token expiration? We probably want to check for that here or at least somewhere in the process.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it does, jwt.verify should return the decoded token only if it's valid and not expired, otherwise it throws an error.

try {
const decodedToken: DecodedToken = jwt.verify(token, secretKey);
return {
ok: true,
body: decodedToken,
error: undefined,
};
} catch (e) {
return {
ok: false,
body: undefined,
error: e,
};
}
}

/**
* Express router for token authentication
*/
export const authTokenRouter = express.Router();

/**
* Middleware function to handle token authentication.
* Retrieves token from cookies, verifies it, and sends authentication context.
* @param req - The Express request object. Assumes that there exists req.cookies.token
* @param res - The Express response object.
* @param next - The next middleware function in the request-response cycle.
*/
authTokenRouter.use((req, res, next) => {
try {
const { token } = req.cookies; // Retrieve token from cookies
const context: Context = {
auth: verifyToken(token), // Verify token and create authentication context
};
res.send(context); // Send authentication context in the response
next();
} catch (e) {
const context: Context = {
auth: {
ok: false,
body: undefined,
error: e,
} as VerifyTokenResponse,
};
res.send(context); // Send error authentication context in case of exceptions
next();
}
});