From 8ccff1ff2ffd0331fdcc38d6f3b4473d9dbbbf67 Mon Sep 17 00:00:00 2001
From: Benjamin Bollen <ben@monax.io>
Date: Thu, 16 Feb 2017 13:27:09 +0100
Subject: [PATCH] permissions: introduce utility to convert string map of
 permissions into AccountPermission

---
 permission/types/util.go | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
 create mode 100644 permission/types/util.go

diff --git a/permission/types/util.go b/permission/types/util.go
new file mode 100644
index 00000000..15a377ef
--- /dev/null
+++ b/permission/types/util.go
@@ -0,0 +1,35 @@
+package types
+
+// ConvertMapStringIntToPermissions converts a map of string-integer pairs and a slice of
+// strings for the roles to an AccountPermissions type.  The integer needs to be greater
+// than zero to set the permission.  For all unmentioned permissions the ZeroBasePermissions
+// is defaulted to.
+// TODO: [ben] re-evaluate the use of int for setting the permission.
+func ConvertPermissionsMapAndRolesToAccountPermissions(permissions map[string]int, roles []string) (*AccountPermissions, error) {
+	var err error
+	accountPermissions := &AccountPermissions{}
+	accountPermissions.Base, err = convertPermissionsMapStringIntToBasePermissions(permissions)
+	if err != nil {
+		return nil, err
+	}
+	accountPermissions.Roles = roles
+	return accountPermissions, nil
+}
+
+// convertPermissionsMapStringIntToBasePermissions converts a map of string-integer pairs to
+// BasePermissions.
+func convertPermissionsMapStringIntToBasePermissions(permissions map[string]int) (BasePermissions, error) {
+	// initialise basePermissions as ZeroBasePermissions
+	basePermissions := ZeroBasePermissions
+
+	for permissionName, value := range permissions {
+		permissionsFlag, err := PermStringToFlag(permissionName)
+		if err != nil {
+			return basePermissions, err
+		}
+		// sets the permissions bitflag and the setbit flag for the permission.
+		basePermissions.Set(permissionsFlag, value > 0)
+	}
+
+	return basePermissions, nil
+}
-- 
GitLab