Created
June 24, 2021 11:34
-
-
Save dipeshhkc/1af5760d8e5becacb309e4de51fab388 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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