Implementing the security information storage interface

Feedback


iServer provides a Storage interface to store and manage security information such as users, roles, and permissions. When implementing custom storage methods, you need to implement Storage as follows:

public class JsonStorage implements Storage {
...
}

For the implementation of the use of json file to store security information, this example will achieve:

The corresponding methods include:

Functional category Method Description
User getUsers(int startIndex, int expectCount)
getUser(String name)
addUser(User toAdd)
removeUsers(String[] names)
alterUser(String name, User user)
authenticate(String username, char[] password)
Get, add, delete, modify the user, and input user account information.
 
Role getRole(String name)
getRoles(String username, Set<String> groups)
getRoles(int startIndex, int expectCount)
addRole(Role toAdd)
removeRoles(String[] names)
alterRole(String name, Role role)
containOne(String[] roles, String theRole)
insertRole(String roleName, String description)
getRolePermissions(String[] names)
setRolePermissions(String roleName, RolePermissions permission, ServiceBeanPermission[] permissions)
Get, add, delete, modify roles, insert role information in stored files, and get, set role authorization.
 
Role group getGroups(int startIndex, int expectCount)
getGroups(String username)
addUserGroup(UserGroup toAdd)
removeUserGroups(String[] names)
alterUserGroup(String name, UserGroup userGroup)
insertGroups(String GroupName, String description)
Get, add, delete, modify the user group, and input user group information.
 
Authority getPublicServiceNames()
getPermission(String user, Collection<? extends String> groups, Collection<? extends String> roles, Set<String> resourceIds)
getInstanceAuthorisations()
updateInstanceAuthorisation(String name, AuthorizeSetting authorizeSetting)
insert(ServiceBeanPermission[] permissions)
Obtain the service list, obtain the authorization information of the user, obtain and update the authorization status of the service instance, and input the authority information.

 

Other methods that need to be implemented are:

    //Set the use of extended json storage method. 
    @Override
    public void resetStorageSetting(SecurityInfoStorageSetting setting) {
        if (!(setting instanceof JsonStorageSetting)) {
            throw new IllegalArgumentException("only recieve JsonStorageSetting");
        }
        this.init((JsonStorageSetting) setting);
    }
    //Reads the storage location of the configuration, and initializes a json file for storing security information 
    private void init(JsonStorageSetting setting) {
        String appFilePath = Tool.getApplicationPath(setting.outputDirectory);
        this.storageFile = new File(appFilePath, SECURITY_FILE_NAME);
        if (!this.storageFile.exists()) {
            if (!this.storageFile.getParentFile().exists()) {
                try {
                    FileUtils.forceMkdirParent(this.storageFile);
                } catch (IOException e) {
                    throw new IllegalStateException("failed to make storage directory ");
                }
            }
            try {
                this.storageFile.createNewFile();
            } catch (IOException e) {
                throw new IllegalStateException("failed to make storage file ");
            }
            this.addPredefinedRoles();
            this.addPredefinedGroups();
        } else {
            this.setMapContent();
        }
    }
    @SuppressWarnings("unchecked")
    private void setMapContent() {
        try {
            String json = FileUtils.readFileToString(this.storageFile, UTF_8);
            Map<string, ?=""> statusMap = FastJSONUtils.parse(json, HashMap.class);
            if (statusMap.containsKey(TAG_USERS)) {
                this.users = (Map<string, user="">) statusMap.get(TAG_USERS);
            }
            if (statusMap.containsKey(TAG_ROLES)) {
                this.roles = (Map<string, role="">) statusMap.get(TAG_ROLES);
            }
            if (statusMap.containsKey(TAG_USERGROUPS)) {
                this.userGroups = (Map<string, usergroup="">) statusMap.get(TAG_USERGROUPS);
            }
            if (statusMap.containsKey(TAG_ROLEPERMISSIONS)) {
                this.rolePermissions = (Map<string, rolepermissions="">) statusMap.get(TAG_ROLEPERMISSIONS);
            }
            if (statusMap.containsKey(TAG_AUTHORIZESETTING)) {
                this.authorizeSetting = (Map<string, authorizesetting="">) statusMap.get(TAG_AUTHORIZESETTING);
            }
            if (statusMap.containsKey(TAG_SERVICEBEANPERMISSION)) {
                this.serviceBeanPermission = (Map<string, servicebeanpermission="">) statusMap.get(TAG_SERVICEBEANPERMISSION);
            }
        } catch (IOException e) {
            throw new IllegalStateException("JsonStorage init failed ");
        }
    }
    //Make persistence for the state of the security information, including all users, roles, user groups and permissions to the storage file 
    private void persistenceToFile() {
        Map<string, object=""> status = new HashMap<string, object="">();
        status.put(TAG_USERS, users);
        status.put(TAG_ROLES, roles);
        status.put(TAG_USERGROUPS, userGroups);
        status.put(TAG_ROLEPERMISSIONS, rolePermissions);
        status.put(TAG_AUTHORIZESETTING, authorizeSetting);
        status.put(TAG_SERVICEBEANPERMISSION, serviceBeanPermission);
        String jsonStatus = FastJSONUtils.toFastJson(status);
        jsonStatus = jsonFormat(jsonStatus);
        try {
            FileUtils.write(this.storageFile, jsonStatus, UTF_8);
        } catch (IOException e) {
            System.out.println("fail to persistence to " + this.storageFile.getAbsolutePath());
        }
    }
    //batch query. 
    private          QueryResult     batchGet(int startIndex, int expectCount, List  list) {
        int actualCount = expectCount;
        int size = list.size();
        if (expectCount > size - startIndex || expectCount == 0) {
            actualCount = size - startIndex;
        }
        List     founds = new ArrayList ();
        if (startIndex <= size)="" {="" int="" index="startIndex;" findcount="0;" while="" (findcount="" <="" actualcount)="" founds.add(list.get(index));="" index++;="" findcount++;="" }="" queryresult<t=""> queryResult = new QueryResult  ();
        queryResult.records = founds;
        queryResult.totalCount = size;
        return queryResult;
    }
    //Parse the role authorization information to convert it to a storeable string. 
    private static class ResolvingRolePermission {
        List<string> allowedCom = new LinkedList<string>();
        List<string> deniedCom = new LinkedList<string>();
        List<string> allowedService = new LinkedList<string>();
        List<string> deniedService = new LinkedList<string>();
        boolean isPublisher = false;
        public RolePermissions toRolePermission() {
            RolePermissions result = new RolePermissions();
            result.publishEnabled = isPublisher;
            result.componentManagerPermissions = new MixedPermissions();
            result.componentManagerPermissions.denied = toArray(deniedCom);
            result.componentManagerPermissions.permitted = toArray(allowedCom);
            result.instanceAccessPermissions = new MixedPermissions();
            result.instanceAccessPermissions.denied = toArray(deniedService);
            result.instanceAccessPermissions.permitted = toArray(allowedService);
            return result;
        }
        void add(int resourceType, String resourceName, int perm) {
            List<string> list = null;
            switch (resourceType) {
            case RESOURCE_TYPE_PUBLISH: {
                isPublisher = true;
                break;
            }
            case RESOURCE_TYPE_COMPONENT: {
                list = isAllowManageComponent(perm) ? allowedCom : deniedCom;
                break;
            }
            case RESOURCE_TYPE_SERVICE: {
                list = isAllowAccessService(perm) ? allowedService : deniedService;
                break;
            }
            }
            if (list != null) {
                list.add(resourceName);
            }
        }
    }
    private static String[] toArray(List<string> list) {
        return list.isEmpty() ? ArrayUtils.EMPTY_STRING_ARRAY : list.toArray(new String[list.size()]);
    }

 

The complete extended sample class is as follows:

NationalCacheStandardTileSourceInfo.java