Skip to content

Instantly share code, notes, and snippets.

@RaheemJnr
Last active March 30, 2024 14:45
Show Gist options
  • Save RaheemJnr/f130a91ed5449070c77e28cb0526c746 to your computer and use it in GitHub Desktop.
Save RaheemJnr/f130a91ed5449070c77e28cb0526c746 to your computer and use it in GitHub Desktop.
Jwt generate and refresh function
/**
*JwtController Class
* class JwtController(val tokenConfiguration: TokenConfig) { ... }: Defines a controller class for JWT operations, which is initialized with a TokenConfig object containing the configuration for tokens.
*
* val audience = tokenConfiguration.audience: Extracts the audience value from tokenConfiguration and assigns it to the audience property. The audience typically defines the recipients that the JWT is intended for.
*
* val issuer = tokenConfiguration.issuer: Similar to audience, this extracts the issuer value from tokenConfiguration and assigns it to the issuer property. The issuer is the entity that issues the token.
*
* fun generateToken(userId: String, tokenType: String, expirationDate: Long): String { ... }: A method to generate a token with specified userId, tokenType, and expirationDate. It creates a JWT with the specified audience, issuer, and claims (like user ID and token type), and sets an expiration date. It then signs the token with a secret key.
*
* fun verifyToken(tokenType: String): JWTVerifier { ... }: A method to create a verifier for tokens. It specifies requirements like the algorithm, audience, issuer, and a claim (token_type). It's used to validate tokens.
*
* generateUserTokens Function
* fun generateUserTokens(userId: String, jwt: JwtController,): UserTokensResponse { ... }: A top-level function to generate both access and refresh tokens for a user.
*
* It calculates expiration dates for both tokens using getExpirationDate and the expiration timestamps from jwt.tokenConfiguration.
*
* It then generates a refresh token and an access token by calling jwt.generateToken, specifying the user ID, the type of token (access or refresh), and the expiration date in milliseconds.
*
* Finally, it returns a UserTokensResponse object containing the expiration timestamps, access token, and refresh token.
*
* getExpirationDate Function
* private fun getExpirationDate(timestamp: Long): Date { ... }: A helper function that calculates the expiration date of a token. It adds the provided timestamp (in milliseconds) to the current system time and returns the result as a Date object.
*
* **/
class JwtController(val tokenConfig: TokenConfig) {
val audience = tokenConfig.audience
val issuer = tokenConfig.issuer
// method to generate token
fun generateToken(userId: String, tokenType: String, expirationDate: Long): String {
return JWT.create()
.withAudience(audience)
.withIssuer(issuer)
.withClaim("id", userId)
.withClaim("token_type", tokenType)
.withExpiresAt(
Date(
System.currentTimeMillis() + expirationDate
)
)
.sign(Algorithm.HMAC256(System.getenv("SECRET")))
}
// method to verify token receive
fun verifyToken(tokenType: String): JWTVerifier {
return JWT.require(Algorithm.HMAC256(secret))
.withAudience(audience)
.withIssuer(issuer)
.withClaim("token_type", tokenType)
.build()
}
}
fun generateUserTokens(
userId: String, jwt: JwtController,
): TokensResponse {
val accessTokenExpirationDate = getExpirationDate(jwt.tokenConfiguration.accessTokenExpirationTimestamp)
val refreshTokenExpirationDate = getExpirationDate(jwt.tokenConfiguration.refreshTokenExpirationTimestamp)
val refreshToken = jwt.generateToken(userId, TokenType.REFRESH_TOKEN.name, expirationDate = 24L * 60L * 60L * 1000L)
val accessToken = jwt.generateToken(userId, TokenType.ACCESS_TOKEN.name, expirationDate = 3L * 60L * 1000L)
return TokensResponse(
accessTokenExpirationDate.time, refreshTokenExpirationDate.time, accessToken, refreshToken
)
}
private fun getExpirationDate(timestamp: Long): Date {
return Date(System.currentTimeMillis() + timestamp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment