Skip to content

Instantly share code, notes, and snippets.

@dipeshhkc
Created June 24, 2021 11:34
Show Gist options
  • Save dipeshhkc/1af5760d8e5becacb309e4de51fab388 to your computer and use it in GitHub Desktop.
Save dipeshhkc/1af5760d8e5becacb309e4de51fab388 to your computer and use it in GitHub Desktop.
// Authorize determines if current user has been authorized to take an action on an object.
func Authorize(obj string, act string, enforcer *casbin.Enforcer) gin.HandlerFunc {
return func(c *gin.Context) {
// Get current user/subject
sub, existed := c.Get("userID")
if !existed {
c.AbortWithStatusJSON(401, gin.H{"msg": "User hasn't logged in yet"})
return
}
// Load policy from Database
err := enforcer.LoadPolicy()
if err != nil {
c.AbortWithStatusJSON(500, gin.H{"msg": "Failed to load policy from DB"})
return
}
// Casbin enforces policy
ok, err := enforcer.Enforce(fmt.Sprint(sub), obj, act)
if err != nil {
c.AbortWithStatusJSON(500, gin.H{"msg": "Error occurred when authorizing user"})
return
}
if !ok {
c.AbortWithStatusJSON(403, gin.H{"msg": "You are not authorized"})
return
}
c.Next()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment