Repository: appleboy/gin-jwt
Pull request #349 (2025-07-17 05:41:31)

refactor: refactor codebase to use jwt.MapClaims directly
- Remove the MapClaims type alias and use jwt.MapClaims directly throughout the codebase
- Update all function signatures and implementations to replace MapClaims with jwt.MapClaims
- Refactor related tests to use jwt.MapClaims instead of MapClaims

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Refactor**
  * Unified the usage of JWT claims by replacing the custom type alias with the standard `jwt.MapClaims` type throughout the application and tests. No changes to logic or user-facing behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> <details>
> <summary>📥 Commits</summary>
> 
> Reviewing files that changed from the base of the PR and between 4fceb9af4672b10c2a29e4ee0c47bfcdf214d2cd and 5cf4b0ee4230e27e42663a5d78ccffcbbee7d7ba.
> 
> </details>
> 
> <details>
> <summary>📒 Files selected for processing (2)</summary>
> 
> * `auth_jwt.go` (4 hunks)
> * `auth_jwt_test.go` (9 hunks)
> 
> </details>
> 
> ```ascii
>  _________________________
> < Please feed the models. >
>  -------------------------
>   \
>    \   \
>         \ /\
>         ( )
>       .( o ).
> ```

<!-- end of auto-generated comment: review in progress by coderabbit.ai -->
<!-- usage_tips_start -->

> [!TIP]
> <details>
> <summary>CodeRabbit can generate a title for your PR based on the changes.</summary>
> 
> Add @coderabbitai placeholder anywhere in the title of your PR and CodeRabbit will replace it with a title based on the changes in the PR. You can change the placeholder by changing the `reviews.auto_title_placeholder` setting.
> 
> </details>

<!-- usage_tips_end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=appleboy/gin-jwt&utm_content=349):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Explain this complex logic.`
  - `Open a follow-up GitHub issue for this discussion.`
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai explain this code block.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and explain its main purpose.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### CodeRabbit Configuration File (`.coderabbit.yaml`)

- You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository.
- Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json`

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Patch:
diff --git a/auth_jwt.go b/auth_jwt.go
index d757198..aa9c211 100644
--- a/auth_jwt.go
+++ b/auth_jwt.go
@@ -13,8 +13,6 @@ import (
 	"github.com/youmark/pkcs8"
 )
 
-type MapClaims jwt.MapClaims
-
 // GinJWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response
 // is returned. On success, the wrapped middleware is called, and the userID is made available as
 // c.Get("userID").(string).
@@ -62,7 +60,7 @@ type GinJWTMiddleware struct {
 	// Note that the payload is not encrypted.
 	// The attributes mentioned on jwt.io can't be used as keys for the map.
 	// Optional, by default no additional data will be set.
-	PayloadFunc func(data interface{}) MapClaims
+	PayloadFunc func(data interface{}) jwt.MapClaims
 
 	// User can define own Unauthorized func.
 	Unauthorized func(c *gin.Context, code int, message string)
@@ -501,7 +499,7 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
 }
 
 // GetClaimsFromJWT get claims from JWT token
-func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error) {
+func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (jwt.MapClaims, error) {
 	token, err := mw.ParseToken(c)
 	if err != nil {
 		return nil, err
@@ -513,7 +511,7 @@ func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error)
 		}
 	}
 
-	claims := MapClaims{}
+	claims := jwt.MapClaims{}
 	for key, value := range token.Claims.(jwt.MapClaims) {
 		claims[key] = value
 	}
@@ -814,22 +812,22 @@ func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message strin
 }
 
 // ExtractClaims help to extract the JWT claims
-func ExtractClaims(c *gin.Context) MapClaims {
+func ExtractClaims(c *gin.Context) jwt.MapClaims {
 	claims, exists := c.Get("JWT_PAYLOAD")
 	if !exists {
-		return make(MapClaims)
+		return make(jwt.MapClaims)
 	}
 
-	return claims.(MapClaims)
+	return claims.(jwt.MapClaims)
 }
 
 // ExtractClaimsFromToken help to extract the JWT claims from token
-func ExtractClaimsFromToken(token *jwt.Token) MapClaims {
+func ExtractClaimsFromToken(token *jwt.Token) jwt.MapClaims {
 	if token == nil {
-		return make(MapClaims)
+		return make(jwt.MapClaims)
 	}
 
-	claims := MapClaims{}
+	claims := jwt.MapClaims{}
 	for key, value := range token.Claims.(jwt.MapClaims) {
 		claims[key] = value
 	}


Test patch:
diff --git a/auth_jwt_test.go b/auth_jwt_test.go
index ad5de92..4b5719e 100644
--- a/auth_jwt_test.go
+++ b/auth_jwt_test.go
@@ -235,9 +235,9 @@ func TestLoginHandler(t *testing.T) {
 	authMiddleware, err := New(&GinJWTMiddleware{
 		Realm: "test zone",
 		Key:   key,
-		PayloadFunc: func(data interface{}) MapClaims {
+		PayloadFunc: func(data interface{}) jwt.MapClaims {
 			// Set custom claim, to be checked in Authorizator method
-			return MapClaims{"testkey": "testval", "exp": 0}
+			return jwt.MapClaims{"testkey": "testval", "exp": 0}
 		},
 		Authenticator: func(c *gin.Context) (interface{}, error) {
 			var loginVals Login
@@ -699,13 +699,13 @@ func TestClaimsDuringAuthorization(t *testing.T) {
 		Key:        key,
 		Timeout:    time.Hour,
 		MaxRefresh: time.Hour * 24,
-		PayloadFunc: func(data interface{}) MapClaims {
-			if v, ok := data.(MapClaims); ok {
+		PayloadFunc: func(data interface{}) jwt.MapClaims {
+			if v, ok := data.(jwt.MapClaims); ok {
 				return v
 			}
 
 			if reflect.TypeOf(data).String() != "string" {
-				return MapClaims{}
+				return jwt.MapClaims{}
 			}
 
 			var testkey string
@@ -719,7 +719,7 @@ func TestClaimsDuringAuthorization(t *testing.T) {
 			}
 			// Set custom claim, to be checked in Authorizator method
 			now := time.Now()
-			return MapClaims{
+			return jwt.MapClaims{
 				"identity": data.(string),
 				"testkey":  testkey,
 				"exp":      now.Add(time.Hour).Unix(),
@@ -769,7 +769,7 @@ func TestClaimsDuringAuthorization(t *testing.T) {
 	r := gofight.New()
 	handler := ginHandler(authMiddleware)
 
-	userToken, _, _ := authMiddleware.TokenGenerator(MapClaims{
+	userToken, _, _ := authMiddleware.TokenGenerator(jwt.MapClaims{
 		"identity": "administrator",
 	})
 
@@ -820,7 +820,7 @@ func TestClaimsDuringAuthorization(t *testing.T) {
 		})
 }
 
-func ConvertClaims(claims MapClaims) map[string]interface{} {
+func ConvertClaims(claims jwt.MapClaims) map[string]interface{} {
 	return map[string]interface{}{}
 }
 
@@ -864,7 +864,7 @@ func TestEmptyClaims(t *testing.T) {
 			assert.Equal(t, http.StatusUnauthorized, r.Code)
 		})
 
-	assert.Empty(t, MapClaims{})
+	assert.Empty(t, jwt.MapClaims{})
 }
 
 func TestUnauthorized(t *testing.T) {
@@ -1305,8 +1305,8 @@ func TestCheckTokenString(t *testing.T) {
 		Unauthorized: func(c *gin.Context, code int, message string) {
 			c.String(code, message)
 		},
-		PayloadFunc: func(data interface{}) MapClaims {
-			if v, ok := data.(MapClaims); ok {
+		PayloadFunc: func(data interface{}) jwt.MapClaims {
+			if v, ok := data.(jwt.MapClaims); ok {
 				return v
 			}
 
@@ -1318,7 +1318,7 @@ func TestCheckTokenString(t *testing.T) {
 
 	r := gofight.New()
 
-	userToken, _, _ := authMiddleware.TokenGenerator(MapClaims{
+	userToken, _, _ := authMiddleware.TokenGenerator(jwt.MapClaims{
 		"identity": "admin",
 	})
 
@@ -1347,7 +1347,7 @@ func TestCheckTokenString(t *testing.T) {
 
 	_, err = authMiddleware.ParseTokenString(userToken)
 	assert.Error(t, err)
-	assert.Equal(t, MapClaims{}, ExtractClaimsFromToken(nil))
+	assert.Equal(t, jwt.MapClaims{}, ExtractClaimsFromToken(nil))
 }
 
 func TestLogout(t *testing.T) {