Skip to content

Instantly share code, notes, and snippets.

@robbypambudi
Created May 2, 2023 09:14
Show Gist options
  • Save robbypambudi/794c8771ae93056ed5036d412606b669 to your computer and use it in GitHub Desktop.
Save robbypambudi/794c8771ae93056ed5036d412606b669 to your computer and use it in GitHub Desktop.
func Authenticate(jwtService service.JWTService, role string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
response := utils.BuildErrorResponse("No token found", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, response)
return
}
if !strings.Contains(authHeader, "Bearer ") {
response := utils.BuildErrorResponse("No token found", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, response)
return
}
authHeader = strings.Replace(authHeader, "Bearer ", "", -1)
token, err := jwtService.ValidateToken(authHeader)
if err != nil {
response := utils.BuildErrorResponse("Invalid token", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, response)
return
}
if !token.Valid {
response := utils.BuildErrorResponse("Invalid token", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusForbidden, response)
return
}
teamRole, err := jwtService.GetRoleByToken(string(authHeader))
fmt.Println("ROLE", teamRole)
if err != nil || (teamRole != "admin" && teamRole != role) {
response := utils.BuildErrorResponse("Failed to process request", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusForbidden, response)
return
}
// get userID from token
teamID, err := jwtService.GetTeamIDByToken(authHeader)
if err != nil {
response := utils.BuildErrorResponse("Failed to process request", http.StatusUnauthorized)
c.AbortWithStatusJSON(http.StatusUnauthorized, response)
return
}
fmt.Println("ROLE", teamRole)
c.Set("teamID", teamID)
c.Next()
}
}
@robbypambudi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment