| #// Copyright (c) 2000-2017 Ericsson Telecom AB // |
| #// All rights reserved. This program and the accompanying materials are made available under the terms // |
| #// of the Eclipse Public License v2.0 which accompanies this distribution, and is available at // |
| #// https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html // |
| #///////////////////////////////////////////////////////////////////////////////////////////////////////// |
| import json, os |
| |
| class FileUserHandler: |
| ''' |
| This class stores usergroup information in a json file and provides an interface for editing the usergroups. |
| ''' |
| |
| def __init__(self, directory): |
| self._directory = directory |
| with open(os.path.join(self._directory, 'userGroups.json'), 'r') as f: |
| self._userGroups = json.load(f) |
| |
| def _saveUserGroups(self): |
| with open(os.path.join(self._directory, 'userGroups.json'), 'w') as f: |
| json.dump(self._userGroups, f, indent = 4) |
| |
| def getUserGroups(self, username): |
| return set(self._userGroups['users'].get(username, [])) |
| |
| def addGroup(self, group, save = True): |
| if group not in self._userGroups['groups']: |
| self._userGroups['groups'].append(group) |
| if save: |
| self._saveUserGroups() |
| |
| def removeGroup(self, group, save = True): |
| if group in self._userGroups['groups']: |
| self._userGroups['groups'].remove(group) |
| for user in self._userGroups['users'].keys(): |
| self.removeUserFromGroup(user, group, False) |
| if save: |
| self._saveUserGroups() |
| |
| def addUserToGroup(self, username, group, save = True): |
| if group in self._userGroups['groups']: |
| if username not in self._userGroups['users']: |
| self._userGroups['users'][username] = [] |
| if group not in self._userGroups['users'][username]: |
| self._userGroups['users'][username].append(group) |
| if save: |
| self._saveUserGroups() |
| |
| def removeUserFromGroup(self, username, group, save = True): |
| if username in self._userGroups['users'] and group in self._userGroups['users'][username]: |
| self._userGroups['users'][username].remove(group) |
| if len(self._userGroups['users'][username]) == 0: |
| self._userGroups['users'].pop(username, []) |
| if save: |
| self._saveUserGroups() |
| |
| def listGroups(self): |
| return self._userGroups['groups'] |
| |
| def listUsersInGroup(self, group): |
| users = set() |
| for user in self._userGroups['users']: |
| if group in self._userGroups['users'][user]: |
| users.add(user) |
| return users |