Minimalistic RBAC package for Go applications
RBAC is a package that makes it easy to implement Role Based Access Control (RBAC) models in Go applications.
To download this package, run:
go get github.com/zpatrick/rbac
This section will go over some of the basic concepts and an example of how to use rbac
in an application.
For more advanced usage, please see the examples directory.
"Upvote"
, "ReadArticle"
, or "EditComment"
.articleID
as the target for a "ReadArticle"
action.
Not all actions require a target.role.Can
function should be used to determine whether or not a role can do an action on a target.
A role is only allowed to do something if it has at least one permission that allows it.package main
import (
"fmt"
"github.com/zpatrick/rbac"
)
func main() {
roles := []rbac.Role{
{
RoleID: "Adult",
Permissions: []rbac.Permission{
rbac.NewGlobPermission("watch", "*"),
},
},
{
RoleID: "Teenager",
Permissions: []rbac.Permission{
rbac.NewGlobPermission("watch", "pg-13"),
rbac.NewGlobPermission("watch", "g"),
},
},
{
RoleID: "Child",
Permissions: []rbac.Permission{
rbac.NewGlobPermission("watch", "g"),
},
},
}
for _, role := range roles {
fmt.Println("Role:", role.RoleID)
for _, rating := range []string{"g", "pg-13", "r"} {
canWatch, _ := role.Can("watch", rating)
fmt.Printf("Can watch %s? %t\n", rating, canWatch)
}
}
}
Output:
Role: Adult
Can watch g? true
Can watch pg-13? true
Can watch r? true
Role: Teenager
Can watch g? true
Can watch pg-13? true
Can watch r? false
Role: Child
Can watch g? true
Can watch pg-13? false
Can watch r? false
This work is published under the MIT license.
Please see the LICENSE
file for details.