Skip to content

Instantly share code, notes, and snippets.

@leosabbir
Created June 26, 2019 23:54
Show Gist options
  • Save leosabbir/a5dc7dbd7f45ce1138729e54162c23d4 to your computer and use it in GitHub Desktop.
Save leosabbir/a5dc7dbd7f45ce1138729e54162c23d4 to your computer and use it in GitHub Desktop.
package authorization
import (
"encoding/json"
"io/ioutil"
"log"
"path/filepath"
)
//---------------------------------------------------------------------------------------
const (
rolePermissionFile = "data/role_permission.json"
)
//---------------------------------------------------------------------------------------
var (
fileReader = ioutil.ReadFile
)
//---------------------------------------------------------------------------------------
var rolePermissionMap map[string]map[Permission]bool
//---------------------------------------------------------------------------------------
func init() {
log.Println("init(): initializing role permission map")
absPath, _ := filepath.Abs(rolePermissionFile)
// read file bytes
bytes, err := fileReader(absPath)
if err != nil {
log.Fatalf("init(): Error reading role permission JSON content: %v", err)
}
// unmarshal bytes into map
var result map[string][]int
err = json.Unmarshal(bytes, &result)
if err != nil {
log.Fatalf("init(): Error unmarshalling role permission JSON content: %v", err)
}
// construct role permission map
rolePermissionMap = make(map[string]map[Permission]bool)
for k, v := range result {
permissions := make(map[Permission]bool)
for _, perm := range v {
permissions[Permission(perm)] = true
}
rolePermissionMap[k] = permissions
}
} // init
//---------------------------------------------------------------------------------------
// Authorize checks if given role has the permission
func Authorize(roleID string, perm Permission) bool {
permissions, ok := rolePermissionMap[roleID]
if !ok {
return false
}
return permissions[perm]
} // Authorize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment