generated from include-davis/Apollo-Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | ||
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(); | ||
} | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.