def organizations(self): """ Active, verified organizations related to this incident. Handles current and legacy incident/s properties. """ from organization import Organization # avoid circular import # lookup using new incidents field orgs = list(Organization.all().filter('incidents', self.key()).filter( 'org_verified', True).filter('is_active', True)) # build list of id and look for global admin org_ids = set() seen_global_admin = False for org in orgs: if org.is_global_admin: seen_global_admin = True org_id = org.key().id() if org_id not in org_ids: org_ids.add(org_id) # check legacy incident field legacy_field_orgs = Organization.all().filter('incident', self.key()) \ .filter('org_verified', True) \ .filter('is_active', True) for org in legacy_field_orgs: if org.key().id() not in org_ids: orgs.append(org) # prepend global admin if not encountered if not seen_global_admin: orgs = (list(Organization.all().filter('name', 'Admin')) + orgs) return orgs
def _generate_ovpn_conf(self): if not self.get_orgs(): raise ValueError('Ovpn conf cannot be generated without ' + \ 'any organizations') logger.debug('Generating server ovpn conf. %r' % { 'server_id': self.id, }) if not self.primary_organization or not self.primary_user: self._create_primary_user() if not os.path.isfile(self.dh_param_path): self._generate_dh_param() primary_org = Organization(self.primary_organization) primary_user = primary_org.get_user(self.primary_user) self.generate_ca_cert() self._generate_tls_verify() self._generate_user_pass_verify() if self.local_network: push = 'route %s %s' % self._parse_network(self.local_network) else: push = 'redirect-gateway' server_conf = OVPN_SERVER_CONF % ( self.port, self.protocol, self.interface, self.ca_cert_path, primary_user.cert_path, primary_user.key_path, self.tls_verify_path, self.dh_param_path, '%s %s' % self._parse_network(self.network), self.ifc_pool_path, push, self.ovpn_status_path, 4 if self.debug else 1, 8 if self.debug else 3, ) if self.otp_auth: server_conf += 'auth-user-pass-verify %s via-file\n' % ( self.user_pass_verify_path) if self.lzo_compression: server_conf += 'comp-lzo\npush "comp-lzo"\n' if self.local_network: server_conf += 'client-to-client\n' with open(self.ovpn_conf_path, 'w') as ovpn_conf: ovpn_conf.write(server_conf)
def _generate_ovpn_conf(self): if not self.get_orgs(): raise ValueError("Ovpn conf cannot be generated without " + "any organizations") logger.debug("Generating server ovpn conf. %r" % {"server_id": self.id}) if not self.primary_organization or not self.primary_user: self._create_primary_user() if not os.path.isfile(self.dh_param_path): self._generate_dh_param() primary_org = Organization(self.primary_organization) primary_user = primary_org.get_user(self.primary_user) self.generate_ca_cert() self._generate_tls_verify() self._generate_user_pass_verify() if self.local_network: push = "route %s %s" % self._parse_network(self.local_network) else: push = "redirect-gateway" server_conf = OVPN_SERVER_CONF % ( self.port, self.protocol, self.interface, self.ca_cert_path, primary_user.cert_path, primary_user.key_path, self.tls_verify_path, self.dh_param_path, "%s %s" % self._parse_network(self.network), self.ifc_pool_path, push, self.ovpn_status_path, 4 if self.debug else 1, 8 if self.debug else 3, ) if self.otp_auth: server_conf += "auth-user-pass-verify %s via-file\n" % (self.user_pass_verify_path) if self.lzo_compression: server_conf += 'comp-lzo\npush "comp-lzo"\n' if self.local_network: server_conf += "client-to-client\n" with open(self.ovpn_conf_path, "w") as ovpn_conf: ovpn_conf.write(server_conf)
def leave_organization(self, organization_id): """ remove relationship between user and organization :param organization_id: :return: """ #TODO exception handling org = Organization() org.id = organization_id user_org_relationship = self._graph_db.match_one(start_node=self.user_node, rel_type=GraphRelationship.MEMBER_OF, end_node=org.org_node) self._graph_db.delete(user_org_relationship)
def _fill_users_pool(self): end = True for org in itertools.chain(Organization.iter_orgs(), Organization.iter_orgs_pool()): if not cache_db.set_length('openssl_tasks') and \ app_server.user_pool_size - org.client_pool_count > 0: end = False org.new_user(type=CERT_CLIENT_POOL) if not cache_db.set_length('openssl_tasks') and \ app_server.server_user_pool_size - \ org.server_pool_size > 0: end = False org.new_user(type=CERT_SERVER_POOL) if not end: self._fill_users_pool()
def _upgrade_data(self): version = self._get_version() cur_version = self._get_data_version() if cur_version and cur_version < self._get_version_int('0.10.5'): logger.info('Upgrading data to v0.10.5...') from server import Server for server in Server.iter_servers(): server._upgrade_0_10_5() from organization import Organization for org in Organization.iter_orgs(): org._upgrade_0_10_5() if cur_version and cur_version < self._get_version_int('0.10.6'): logger.info('Upgrading data to v0.10.6...') if self.password: from cache import persist_db logger.info('Upgrading config to v0.10.6...') salt = base64.b64encode( '2511cebca93d028393735637bbc8029207731fcf') password = base64.b64encode(self.password.decode('hex')) persist_db.dict_set('auth', 'password', '0$%s$%s' % (salt, password)) self.password = None self.commit() from server import Server for server in Server.iter_servers(): server._upgrade_0_10_6() if cur_version and cur_version < self._get_version_int('0.10.9'): logger.info('Upgrading data to v0.10.9...') from server import Server for server in Server.iter_servers(): server._upgrade_0_10_9() from organization import Organization for org in Organization.iter_orgs(): for user in org.iter_users(): user._upgrade_0_10_9() org.sort_users_cache() if cur_version != version: from pritunl import __version__ version_path = os.path.join(self.data_path, VERSION_NAME) with open(version_path, 'w') as version_file: version_file.write('%s\n' % __version__)
def check_node_existence(self, data): """Checks if the nodes for the relationship exists, if not creates new nodes.""" # import pdb; pdb.set_trace() if data: permalink = Transform.to_str(data.get('Permalink')) label = Transform.to_str(data.get('PrimaryRole')) uuid = Transform.to_str(data.get('Uuid')) try: organization = Organization() organization.check_create_organization_node(label, permalink) event = Event() event.check_create_event_node(uuid) except Exception as e: pass
def dispatch(self, *args, **kwargs): " All requests must have valid, in-date activation codes. " self.page_blocks = page_db.get_page_block_dict() self.activation_code = self.request.get('code') if not self.activation_code: self.abort(404) # lookup org by activation code orgs_by_code = Organization.all() \ .filter('activation_code', self.activation_code) if orgs_by_code.count() != 1: self.abort(404) self.org_by_code = orgs_by_code[0] # send response if already activated if self.org_by_code.is_active: self.render( already_activated_template, org=self.org_by_code ) return # send response if too late if self.org_by_code.activate_by < datetime.datetime.utcnow(): self.render( activation_too_late_template, org=self.org_by_code ) return # continue handling request super(ActivationHandler, self).dispatch(*args, **kwargs)
def check_node_existence(self, data): """Checks if the nodes for the relationship exists, if not creates new nodes.""" if data: permalink = Transform.to_str(data.get('Permalink')) label = Transform.to_str(data.get('PrimaryRole')) people_permalink = Transform.to_str(data.get('PeoplePermalink')) try: organization = Organization() organization.check_create_organization_node(label, permalink) person = Person() person.check_create_person_node(people_permalink) except Exception as e: pass
def check_node_existence(self, data): """Checks if the nodes for the relationship exists, if not creates new nodes.""" if data: permalink = Transform.to_str(data.get('Permalink')) label = Transform.to_str(data.get('PrimaryRole')) name = Transform.to_str(data.get('Name')) try: organization = Organization() organization.check_create_organization_node(label, permalink) category = Category() category.check_create_category_node(name) except Exception as e: pass
def check_node_existence(self, data): """Checks if the nodes for the relationship exists, if not creates new nodes.""" if data: permalink = Transform.to_str(data.get('Permalink')) label = Transform.to_str(data.get('PrimaryRole')) fund_id = Transform.to_str(data.get('FundsId')) try: organization = Organization() organization.check_create_organization_node(label, permalink) fund = Fund() fund.check_create_fund_node(fund_id) except Exception as e: pass
def AuthenticatedPost(self, org, event): # get and check args ids = [int(id) for id in self.request.get('ids', '').split(',')] selected_org = ( Organization.get(self.request.get('org')) if self.request.get('org') else None ) status = self.request.get('status') action = self.request.get('action', None) if action not in self.BULK_ACTIONS: self.abort(404) # get authorised events if org.is_global_admin: event_keys = list(event_db.Event.all(keys_only=True)) elif org.is_local_admin: event_keys = org.incidents # handle bulk action fn = self.BULK_ACTIONS[action] for id in ids: site = Site.get_by_id(id) authorised = ( site.event.key() in event_keys and (selected_org is None or any( incident_key in event_keys for incident_key in [ incident.key() for incident in org.incidents ]) ) ) if authorised: fn(self, site, org=selected_org, status=status) # redirect back to work orders table self.redirect('/admin-view-work-orders')
def dispatch(self, *args, **kwargs): " All requests must have valid, in-date activation codes. " self.page_blocks = page_db.get_page_block_dict() self.activation_code = self.request.get('code') if not self.activation_code: self.abort(404) # lookup org by activation code orgs_by_code = Organization.all() \ .filter('activation_code', self.activation_code) if orgs_by_code.count() != 1: self.abort(404) self.org_by_code = orgs_by_code[0] # send response if already activated if self.org_by_code.is_active: self.render(already_activated_template, org=self.org_by_code) return # send response if too late if self.org_by_code.activate_by < datetime.datetime.utcnow(): self.render(activation_too_late_template, org=self.org_by_code) return # continue handling request super(ActivationHandler, self).dispatch(*args, **kwargs)
def main(): employer = Employer('Victa Kironde', 25, 'male', 'LFA') organization = Organization('Andela', 'www.andela.com') employer.work_for(organization) #add subordinates employee = Employee('Bruce Bigirwenkya', 22, 'male', 'Fellow') employer.hire(employee) employer.hire(Employee('Daniel', 22, 'male', 'Developer')) employer.hire(Employee('Joshua', 18, 'male', 'Fellow')) employer.hire(Employee('Martina', 19, 'female', 'fellow')) employer.hire(Employee('Joshua', 20, 'male', 'Supervisor')) print("\n_____________________") print("Organization") print("---XXX---") print("Name: " + employer.organization.name) print("Address: " + employer.organization.web_address) print("\n_____________________") print("Details of employer:") print("---XXX---") print("Name: " + employer.name) print("Age: " + str(employer.age)) print("Gender: " + employer.gender) print("Title: " + employer.title) print("Number of subordinates:" + str(len(employer.subordinates))) print("\n_____________________") print("Show polymorphism:") print("---XXX---") print("Message for employee:" + employee.message()) print("Message for employer:" + employer.message())
def get_event_admins(event): global_admins = get_global_admins() local_admins = Organization.gql( 'WHERE incidents = :1 AND is_admin = True AND name != :2', event.key(), 'Admin' ) return global_admins + list(local_admins)
def get_organizations(self, search=""): """Get a list of your :class:`organizations <tracker_client.organization.Organization>`. Note that the optional search term is supplied as part of the GraphQL query variables and affects the API response received, rather than filtering results client-side. :param str search: Search term to filter results with. For example, supplying the string "canada" would return only Organizations containing "canada" in their name. :return: A list of your organizations. :rtype: list[Organization] :raises ValueError: if your organizations can't be retrieved. """ params = {"after": "", "search": search} has_next = True org_list = [] # The maximum number of organizations that can be requested at once is 100 # This loop gets 100 orgs, checks if there are more, and if there are # it gets another 100 starting after the last org it got while has_next: result = self.execute_query(queries.GET_ALL_ORGS, params) if "error" in result: print("Server error: ", result) raise ValueError("Unable to get your organizations.") for edge in result["findMyOrganizations"]["edges"]: org_list.append(Organization(self, **edge["node"])) has_next = result["findMyOrganizations"]["pageInfo"]["hasNextPage"] params["after"] = result["findMyOrganizations"]["pageInfo"][ "endCursor"] return org_list
def test_global_efficiency(self): orga = Organization() orga.add_layer(1, size=2, efficiency_weight=1.0) orga.add_layer(2, size=3, efficiency_weight=0.6) orga.add_layer(3, size=5, efficiency_weight=0.2) orga.layers[1].employees = [emp(25, 8.0), emp(25, 9.0)] orga.layers[2].employees = [emp(25, 7.0), emp(25, 2.0), emp(25, 7.0)] orga.layers[3].employees = [emp(25, 6.0), emp(25, 5.5), emp(25, 10.0), None, emp(25, 7.0)] self.assertEquals(100 * ((8.0 + 9.0) * 1.0 + (7.0 + 2.0 + 7.0) * 0.6 + (6.0 + 5.5 + 10.0 + 7.0) * 0.2) / (orga.workforce() * orga.maximum_efficiency()), orga.global_efficiency())
def join_organization(self, organization_id): """ add user to organization :param organization_id: string uuid :return: list of tuple of interests """ #TODO exception handling org = Organization() org.id = organization_id user_org_relationship = Relationship(self.user_node, GraphRelationship.MEMBER_OF, org.org_node) try: self._graph_db.create_unique(user_org_relationship) except: print sys.exc_info()[0]
def check_node_existence(self, data): """Checks if the nodes for the relationship exists, if not creates new nodes.""" if data: permalinks = [ (data.get('OrganizationAcquireeID'), data.get('AcquireePrimaryRole')), (data.get('OrganizationAcquirerID'), data.get('AcquirerPrimaryRole')) ] for permalink, label in permalinks: permalink = Transform.to_str(permalink) label = Transform.to_str(label) try: organization = Organization() organization.check_create_organization_node(label, permalink) except Exception as e: pass
def test_maximum_efficiency(self): orga = Organization() orga.add_layer(1, size=2, efficiency_weight=1.0) orga.add_layer(2, size=3, efficiency_weight=0.6) orga.add_layer(3, size=5, efficiency_weight=0.2) self.assertEquals((2*10*1.0 + 3*10*0.6 + 5*10*0.2) / 10, orga.maximum_efficiency())
def test_workforce(self): orga = Organization() orga.add_layer(1, size=2, efficiency_weight=1.0) orga.add_layer(2, size=3, efficiency_weight=1.0) orga.add_layer(3, size=5, efficiency_weight=1.0) self.assertEquals(10, orga.workforce())
def _fill_cache(self): logger.info('Preloading cache...') from organization import Organization for org in Organization.iter_orgs(): org._cache_users() from server import Server for server in Server.iter_servers(): server.load()
def __init__ (self): """ """ self.data = {} resp = self.getResponse() for item in resp: org = Organization (item) self.data[org.acronym] = org
def get_organization(self, id): response = requests.get(self.base_url + str(id), params=self.params) response.raise_for_status() data = response.json()['data'] name = data['name'] latitude, longitude = self.address_to_coords(data['address']) return Organization(id, name, latitude, longitude)
def _generate_ovpn_conf(self): if not self.get_orgs(): raise ValueError('Ovpn conf cannot be generated without ' + \ 'any organizations') logger.debug('Generating server ovpn conf. %r' % { 'server_id': self.id, }) if not self.primary_organization or not self.primary_user: self._create_primary_user() if not os.path.isfile(self.dh_param_path): self._generate_dh_param() primary_org = Organization(self.primary_organization) primary_user = primary_org.get_user(self.primary_user) self.generate_ca_cert() self._generate_tls_verify() if self.local_network: push = 'route %s %s' % self._parse_network( self.local_network) else: push = 'redirect-gateway' with open(self.ovpn_conf_path, 'w') as ovpn_conf: ovpn_conf.write(OVPN_SERVER_CONF % ( self.port, self.protocol, self.interface, self.ca_cert_path, primary_user.cert_path, primary_user.key_path, self.tls_verify_path, self.dh_param_path, '%s %s' % self._parse_network(self.network), self.ifc_pool_path, push, self.ovpn_status_path, 4 if self.debug else 1, 8 if self.debug else 3, ))
def __init__(self): """ Constructor for SearchZendesk class """ self.main_choices = { 1: "Select 1 to search Zendesk", 2: "Select 2 to view a list of searchable fields", 3: "Exit" } # main menu choices self.sub_choices = { 1: "Select 1 to search users", 2: "Select 2 to search tickets", 3: "Select 3 to search organizations", 4: "Select 4 to go back to main menu" } # search menu choices self.user = User() # instantiates user class self.ticket = Ticket() # instantiates ticket class self.organization = Organization() # instantiates organization class
def user_orgs(self): """ :return: """ user_orgs = self._graph_db.match(start_node=self.user_node, rel_type=GraphRelationship.MEMBER_OF, end_node=None) orgs_list = [] for rel in user_orgs: org_properties = dict(rel.end_node.properties) org = Organization() org.id = org_properties['id'] interests = org.org_interests interests_list = [] for interest in interests: interests_list.append(interest['name']) org_properties['interests'] = interests_list orgs_list.append(org_properties) return orgs_list
def create_organization(self, name, latitude, longitude): address = self.coords_to_address(latitude, longitude) data = {'name': name, 'address': address} response = requests.post(self.base_url, data=data, params=self.params) response.raise_for_status() id = response.json()['data']['id'] organization = Organization(id, name, latitude, longitude) return organization
def parseCordisOrganizationRDF(self, entry, graph): Organization = namedtuple('Organization', 'identifier, referenceID, projectName, role, name, shortName, country, activityType, endOfParticipation, city, postalCode, street, homepage, contact, id') org = [] org.append(entry[0]) org.append(entry[1]) org.append(entry[2]) org.append(entry[3]) org.append(entry[5]) org.append(entry[6]) if len(entry[10]) > 1: org.append(self.alpha2Name(entry[10])) else: org.append('') org.append(entry[7]) org.append(entry[8]) org.append('http://dbpedia.org/page/' + parse.quote(self.capitalizeAll(self.setLiterals(entry[12])))) org.append(entry[13]) org.append( entry[11]) org.append((entry[14][:4] != 'http')*'http://' + entry[14]) org.append(parse.quote_plus(entry[17] + entry[18] + entry[6])) org.append(entry[4]) organization = Organization(*org) """ Create triples """ if len(organization.id) > 1: orgRDF = CORG[self.setLiterals(organization.id)] else: orgRDF = CORG[parse.quote_plus(organization.name)] graph.add((orgRDF, RDF.type, FOAF.Organization)) graph.add((orgRDF, CORDIS.organizationName, Literal(self.setLiterals(organization.name)))) graph.add((orgRDF, CORDIS.organizationShortName, Literal(self.setLiterals(organization.shortName)))) if len(organization.country) > 1: graph.add((orgRDF, CORDIS.organizationCountry, DBR[self.setLiterals(organization.country)])) if len(organization.activityType) > 1: graph.add((orgRDF, CORDIS.activityType, Literal(self.setLiterals(organization.activityType)))) if len(organization.endOfParticipation) > 1: graph.add((orgRDF, CORDIS.endOfParticipation, Literal(self.setLiterals(organization.endOfParticipation)))) if len(organization.city) > 1: graph.add((orgRDF, DBO.locationCity, URIRef(organization.city))) if len(organization.street) > 1: graph.add((orgRDF, DBO.address, Literal(self.setLiterals(organization.street)))) if len(organization.postalCode) > 1: graph.add((orgRDF, DBO.postalCode, Literal(self.setLiterals(organization.postalCode)))) if len(organization.homepage) > 1: if ';' in organization.homepage: for homepage in organization.homepage.split(';'): graph.add((orgRDF, FOAF.homepage, URIRef(self.setLiterals(homepage).replace('"', '').replace("'",'')))) if ',' in organization.homepage: for homepage in organization.homepage.split(','): graph.add((orgRDF, FOAF.homepage, URIRef(self.setLiterals(homepage).replace('"', '').replace("'",'')))) if len(organization.contact) > 1: graph.add((orgRDF, FOAF.person, CPEO[organization.contact])) return organization
def get_org(self, org_id): if org_id in self.organizations: org = Organization.get_org(id=org_id) try: org.load() except IOError: logger.exception('Failed to load org conf. %r' % { 'org_id': org_id, }) return return org
def _remove_primary_user(self): logger.debug("Removing primary user. %r" % {"server_id": self.id}) primary_organization = self.primary_organization primary_user = self.primary_user self.primary_organization = None self.primary_user = None if not primary_organization or not primary_user: return org = Organization(primary_organization) user = org.get_user(primary_user) if not user: logger.debug( "Primary user not found, skipping remove. %r" % {"server_id": self.id, "org_id": org.id, "user_id": user.id} ) return if user: user.remove()
def organizations(self): """ Active, verified organizations related to this incident. Handles current and legacy incident/s properties. """ from organization import Organization # avoid circular import # lookup using new incidents field orgs = list( Organization.all().filter('incidents', self.key()) .filter('org_verified', True) .filter('is_active', True) ) # build list of id and look for global admin org_ids = set() seen_global_admin = False for org in orgs: if org.is_global_admin: seen_global_admin = True org_id = org.key().id() if org_id not in org_ids: org_ids.add(org_id) # check legacy incident field legacy_field_orgs = Organization.all().filter('incident', self.key()) \ .filter('org_verified', True) \ .filter('is_active', True) for org in legacy_field_orgs: if org.key().id() not in org_ids: orgs.append(org) # prepend global admin if not encountered if not seen_global_admin: orgs = ( list(Organization.all().filter('name', 'Admin')) + orgs ) return orgs
def run_process(): """.""" try: Organization.run() Fund.run() Person.run() FundingRound.run() HasAcquired.run() Funding.run() HasFund.run() Investment.run() HasAffiliation.run() HasStudiedat.run() except Exception as e: logger = Logger() logger.logg(debug_msg='Error while running cron job.', info_msg='Function = run_process()', warning_msg='Error in executing scheduled job', error_msg='Module = ' + log_file, critical_msg=str(e))
def iter_orgs(self): orgs_dict = {} orgs_sort = [] for org_id in self.organizations: org = Organization.get_org(id=org_id) if not org: continue name_id = '%s_%s' % (org.name, org.id) orgs_dict[name_id] = org orgs_sort.append(name_id) for name_id in sorted(orgs_sort): yield orgs_dict[name_id]
def get_orgs(self): orgs = [] for org_id in self.organizations: org = Organization(org_id) if not os.path.isfile(org.ca_cert.cert_path): logger.warning('Removing non existent organization ' + \ 'from server. %r' % { 'server_id': self.id, 'org_id': org_id, }) self.remove_org(org_id) continue orgs.append(org) return orgs
class TreeHuffman: listOrd = Organization.setlistwords( list(str(input("Digite uma série de caracteres: ")))) while len(listOrd) != 1: listOrd = buildingTree(listOrd) listPilha = [] huffmanList = [] valoresHuffman = [] huffmanList = huffmanCod(listOrd[0], listPilha, huffmanList, valoresHuffman) print(huffmanList) csvHuffman(huffmanList) jsonOrd = json.dumps(listOrd) print("\n\n", jsonOrd)
def get_organizations(self): response = requests.get(self.base_url, params=self.params) response.raise_for_status() organizations = {} data = response.json()['data'] for entry in data: id = int(entry['id']) name = entry['name'] latitude, longitude = self.address_to_coords(entry['address']) organizations[id] = Organization(id, name, latitude, longitude) return organizations
def _remove_primary_user(self): logger.debug('Removing primary user. %r' % { 'server_id': self.id, }) primary_organization = self.primary_organization primary_user = self.primary_user self.primary_organization = None self.primary_user = None if not primary_organization or not primary_user: return org = Organization(primary_organization) user = org.get_user(primary_user) if not user: logger.debug('Primary user not found, skipping remove. %r' % { 'server_id': self.id, 'org_id': org.id, 'user_id': user.id, }) return if user: user.remove()
def _remove_primary_user(self): logger.debug('Removing primary user. %r' % { 'server_id': self.id, }) primary_organization = self.primary_organization primary_user = self.primary_user self.primary_organization = None self.primary_user = None if not primary_organization or not primary_user: return org = Organization(primary_organization) user = org.get_user(primary_user) if not user: logger.debug('Primary user not found, skipping remove. %r' % { 'server_id': self.id, 'org_id': org.id, 'user_id': user.id, }) return if user: user.remove()
def list_organizations(self): """ Returns all organizations for your Trello user :return: a list of Python objects representing the Trello organizations. Each organization has the following noteworthy attributes: - id: the organization's identifier - name: Name of the organization - desc: Description of the organization (optional - may be missing from the returned JSON) - closed: Boolean representing whether this organization is closed or not - url: URL to the organization """ json_obj = self.fetch_json('members/me/organizations') return [Organization.from_json(self, obj) for obj in json_obj]
def add_org(self, org_id): logger.debug('Adding organization to server. %r' % { 'server_id': self.id, 'org_id': org_id, }) org = Organization(org_id) if org.id in self.organizations: logger.debug('Organization already on server, skipping. %r' % { 'server_id': self.id, 'org_id': org.id, }) return self.organizations.append(org.id) self.commit() Event(type=SERVERS_UPDATED) Event(type=SERVER_ORGS_UPDATED, resource_id=self.id)
def _remove_primary_user(self): logger.debug('Removing primary user. %r' % { 'server_id': self.id, }) if not self.primary_organization or not self.primary_user: return org = Organization.get_org(id=self.primary_organization) if org: user = org.get_user(id=self.primary_user) if user: user.remove() self.primary_organization = None self.primary_user = None
def get_organization(self, name): """Get an :class:`~tracker_client.organization.Organization` from specified name. You must be a member of that organization. :param str name: name of organization to get and construct :class:`~tracker_client.organization.Organization` for. :return: The specified organization. :rtype: Organization :raises ValueError: if an invalid organization name is given. """ params = {"orgSlug": slugify(name)} result = self.execute_query(queries.GET_ORG, params) if "error" in result: print("Server error: ", result) raise ValueError("Unable to get organization " + name) return Organization(self, **result["findOrganizationBySlug"])
def _upgrade_data(self): from pritunl import __version__ version = '0.10.1' version_path = os.path.join(self.data_path, VERSION_NAME) if os.path.isfile(version_path): with open(version_path, 'r') as version_file: version = version_file.readlines()[0].strip() if version == '0.10.1': logger.info('Upgrading data from v0.10.1...') from organization import Organization for org in Organization.get_orgs(): for user in org.get_users(): user._upgrade_0_10_2() if version != __version__: with open(version_path, 'w') as version_file: version = version_file.write('%s\n' % __version__)
def _upgrade_data(self): from pritunl import __version__ version = '0.10.1' version_path = os.path.join(self.data_path, VERSION_NAME) if os.path.isfile(version_path): with open(version_path, 'r') as version_file: version = version_file.readlines()[0].strip() if version == '0.10.1': logger.info('Upgrading data from v0.10.1...') from organization import Organization for org in Organization.get_orgs(): for user in org.get_users(): user._upgrade_0_10_2() if version != __version__: with open(version_path, 'w') as version_file: version = version_file.write('%s\n' % __version__)
def add_org(self, org_id): logger.debug('Adding organization to server. %r' % { 'server_id': self.id, 'org_id': org_id, }) org = Organization.get_org(id=org_id) if org.id in self.organizations: logger.debug('Organization already on server, skipping. %r' % { 'server_id': self.id, 'org_id': org.id, }) return org self.organizations.append(org.id) self.commit() Event(type=SERVERS_UPDATED) Event(type=SERVER_ORGS_UPDATED, resource_id=self.id) Event(type=USERS_UPDATED, resource_id=org_id) return org
def test_promote(self): hypothesis = MockHypothesis() orga = Organization() orga.set_strategies(hypothesis=hypothesis, strategy=BestStrategy()) orga.add_layer(1, size=1, efficiency_weight=1.0) orga.add_layer(2, size=3, efficiency_weight=1.0) best_employee = emp(38, 7.5) worst_employee = emp(25, 3.0) average_employee = emp(49, 6.3) # layer 1 has a vacancy orga.layers[2].employees = [worst_employee, best_employee, average_employee] orga.promote(origin=orga.layers[2], destination=orga.layers[1]) self.assertEquals([best_employee], orga.layers[1].employees) self.assertEquals([worst_employee, None, average_employee], orga.layers[2].employees) self.assertTrue(hypothesis.called) self.assertEquals(7.5, orga.layers[1].employees[0].competence)
def AuthenticatedPost(self, org, _): global_admin = False local_admin = False if org.name == GLOBAL_ADMIN_NAME: global_admin = True if org.is_admin == True and global_admin == False: local_admin = True if global_admin == False and local_admin == False: self.redirect("/") return # create form form = (GlobalAdminCreateOrganizationForm(self.request.POST) if global_admin else CreateOrganizationForm(self.request.POST)) events = self._get_events(org, global_admin, local_admin) form.incident.choices = [(str(event.key().id()), event.name) for event in events] if form.validate() and not form.errors: # create new org event = event_db.Event.get_by_id(int(form.incident.data)) new_org = Organization(name=form.name.data, ) new_org.incidents = [event.key()] new_org.save() del (form.incident) del (form.incidents) form.populate_obj(new_org) new_org.save() organization.PutAndCache(new_org) # redirect to the add contact page self.redirect('/admin-create-contact?selected_org=%d' % new_org.key().id()) else: self.response.out.write( template.render({ "form": form, "global_admin": global_admin, }))
def AuthenticatedPost(self, org, _): global_admin = False local_admin = False if org.name == GLOBAL_ADMIN_NAME: global_admin = True if org.is_admin == True and global_admin == False: local_admin = True if global_admin == False and local_admin == False: self.redirect("/") return # create form form = ( GlobalAdminCreateOrganizationForm(self.request.POST) if global_admin else CreateOrganizationForm(self.request.POST) ) events = self._get_events(org, global_admin, local_admin) form.incident.choices = [(str(event.key().id()), event.name) for event in events] if form.validate() and not form.errors: # create new org event = event_db.Event.get_by_id(int(form.incident.data)) new_org = Organization( name=form.name.data, ) new_org.incidents = [event.key()] new_org.save() del(form.incident) del(form.incidents) form.populate_obj(new_org) new_org.save() organization.PutAndCache(new_org) # redirect to the add contact page self.redirect('/admin-create-contact?selected_org=%d' % new_org.key().id()) else: self.response.out.write(template.render({ "form": form, "global_admin": global_admin, }))
def parseCordisOrganization(self, entry): Organization = namedtuple('Organization', 'identifier, referenceID, projectName, role, name, shortName, country, activityType, endOfParticipation, city, postalCode, street, homepage, contact') org = [] org.append(entry[0]) org.append(entry[1]) org.append(entry[2]) org.append(entry[3]) org.append(entry[5]) org.append(entry[6]) if len(entry[10]) > 1: org.append(self.alpha2Name(entry[10])) else: org.append('') org.append(entry[7]) org.append(entry[8]) org.append('http://dbpedia.org/page/' + self.capitalizeAll(entry[12])) org.append(entry[13]) org.append( entry[11]) org.append((entry[14][:4] != 'http')*'http://' + entry[14]) org.append(parse.quote_plus(entry[17] + entry[18] + entry[6])) output = Organization(*org) return [self.createOrganizationOutput(output), output.name, [output.role, output.identifier, output.name]]
def organization_update(name, company): orgs = Organization.fetch(name) orgs.update(company)
def create_work_order_search_form(events, work_types, limiting_event=None): events_by_recency = sorted(events, key=lambda event: event.key().id(), reverse=True) # determine orgs and work types to include if limiting_event: if limiting_event.key() not in [e.key() for e in events]: raise Exception("Event %s unavailable" % limiting_event) orgs = Organization.all().filter('incidents', limiting_event.key()) work_types = [ site.work_type for site in Query(Site, projection=['work_type'], distinct=True) \ .filter('event', limiting_event.key()) if site.work_type in work_types ] else: orgs = Organization.all().filter('incidents in', [event for event in events]) class WorkOrderSearchForm(Form): def __init__(self, *args, **kwargs): super(WorkOrderSearchForm, self).__init__(*args, **kwargs) self.offset.data = 0 # offset set by the form should always be 0 offset = HiddenField(default="0") order = HiddenField() event = SelectField( choices=[ (e.key(), e.name) for e in events_by_recency ], default=events_by_recency[0].key() ) query = TextField("Search") reporting_org = SelectField( choices=[('', '')] + [ (org.key(), org.name) for org in orgs ], default='' ) claiming_org = SelectField( choices=[('', '')] + [ (org.key(), org.name) for org in orgs ], default='' ) work_type = SelectField( choices=[('', '')] + [ (work_type, work_type) for work_type in work_types ], default='' ) status = SelectField( choices=[('', '')] + [ (s, s) for s in Site.status.choices ], default='' ) per_page = SelectField( choices=[ (n, n) for n in [10, 50, 100, 250] ], coerce=int, default=10 ) return WorkOrderSearchForm
def get_org(self, org_id): if org_id in self.organizations: return Organization.get_org(id=org_id)
def _generate_ovpn_conf(self, temp_path): logger.debug('Generating server ovpn conf. %r' % { 'server_id': self.id, }) if not self.primary_organization or not self.primary_user: self._create_primary_user() primary_org = Organization.get_org(id=self.primary_organization) if not primary_org: self._create_primary_user() primary_org = Organization.get_org(id=self.primary_organization) primary_user = primary_org.get_user(self.primary_user) if not primary_user: self._create_primary_user() primary_org = Organization.get_org(id=self.primary_organization) primary_user = primary_org.get_user(self.primary_user) tls_verify_path = os.path.join(temp_path, TLS_VERIFY_NAME) user_pass_verify_path = os.path.join(temp_path, USER_PASS_VERIFY_NAME) client_connect_path = os.path.join(temp_path, CLIENT_CONNECT_NAME) client_disconnect_path = os.path.join(temp_path, CLIENT_DISCONNECT_NAME) ovpn_status_path = os.path.join(temp_path, OVPN_STATUS_NAME) ovpn_conf_path = os.path.join(temp_path, OVPN_CONF_NAME) auth_host = app_server.bind_addr if auth_host == '0.0.0.0': auth_host = 'localhost' for script, script_path in ( (TLS_VERIFY_SCRIPT, tls_verify_path), (USER_PASS_VERIFY_SCRIPT, user_pass_verify_path), (CLIENT_CONNECT_SCRIPT, client_connect_path), (CLIENT_DISCONNECT_SCRIPT, client_disconnect_path), ): with open(script_path, 'w') as script_file: os.chmod(script_path, 0755) # TODO script_file.write(script % ( app_server.local_api_key, '/dev/null', # TODO app_server.web_protocol, auth_host, app_server.port, self.id, )) push = '' if self.mode == LOCAL_TRAFFIC: for network in self.local_networks: push += 'push "route %s %s"\n' % self._parse_network(network) elif self.mode == VPN_TRAFFIC: pass else: push += 'push "redirect-gateway"\n' for dns_server in self.dns_servers: push += 'push "dhcp-option DNS %s"\n' % dns_server if self.search_domain: push += 'push "dhcp-option DOMAIN %s"\n' % self.search_domain server_conf = OVPN_INLINE_SERVER_CONF % ( self.port, self.protocol, self.interface, tls_verify_path, client_connect_path, client_disconnect_path, '%s %s' % self._parse_network(self.network), ovpn_status_path, 4 if self.debug else 1, 8 if self.debug else 3, ) if self.otp_auth: server_conf += 'auth-user-pass-verify %s via-file\n' % ( user_pass_verify_path) if self.lzo_compression: server_conf += 'comp-lzo\npush "comp-lzo"\n' if self.mode in (LOCAL_TRAFFIC, VPN_TRAFFIC): server_conf += 'client-to-client\n' if push: server_conf += push server_conf += '<ca>\n%s\n</ca>\n' % utils.get_cert_block( self.ca_certificate) server_conf += '<cert>\n%s\n</cert>\n' % utils.get_cert_block( primary_user.certificate) server_conf += '<key>\n%s\n</key>\n' % primary_user.private_key server_conf += '<dh>\n%s\n</dh>\n' % self.dh_params with open(ovpn_conf_path, 'w') as ovpn_conf: os.chmod(ovpn_conf_path, 0600) ovpn_conf.write(server_conf)
def _fill_orgs_pool(self): for _ in xrange(app_server.org_pool_size - Organization.get_org_pool_count()): Organization(pool=True)
def _generate_ovpn_conf(self): if not self.org_count: raise ServerMissingOrg('Ovpn conf cannot be generated without ' + \ 'any organizations', { 'server_id': self.id, }) logger.debug('Generating node server ovpn conf. %r' % { 'server_id': self.id, }) if not self.primary_organization or not self.primary_user: self._create_primary_user() if not os.path.isfile(self.dh_param_path): self._generate_dh_param() primary_org = Organization.get_org(id=self.primary_organization) primary_user = primary_org.get_user(self.primary_user) self.generate_ca_cert() push = '' if self.local_networks: for network in self.local_networks: push += 'push "route %s %s"\n' % self._parse_network(network) else: push += 'push "redirect-gateway"\n' for dns_server in self.dns_servers: push += 'push "dhcp-option DNS %s"\n' % dns_server push = push.rstrip() server_conf = OVPN_INLINE_SERVER_CONF % ( self.port, self.protocol, self.interface, '%s', '%s', '%s', '%s %s' % self._parse_network(self.network), '%s', push, '%s', 4 if self.debug else 1, 8 if self.debug else 3, ) if self.otp_auth: server_conf += 'auth-user-pass-verify ' + \ '<%= user_pass_verify_path %> via-file\n' if self.lzo_compression: server_conf += 'comp-lzo\npush "comp-lzo"\n' if self.local_networks: server_conf += 'client-to-client\n' server_conf += '<ca>\n%s\n</ca>\n' % utils.get_cert_block( self.ca_cert_path) server_conf += '<cert>\n%s\n</cert>\n' % utils.get_cert_block( primary_user.cert_path) server_conf += '<key>\n%s\n</key>\n' % open( primary_user.key_path).read().strip() server_conf += '<dh>\n%s\n</dh>\n' % open( self.dh_param_path).read().strip() return server_conf
def organization_inspect(name): orgs = Organization.fetch(name) result = orgs.inspect() util.print_json_result(result)
def organization_list(): orgs_list = Organization.list() util.print_organization_ps_output(orgs_list)
def organization_create(name, company): orgs = Organization(name=name, company=company) orgs.create()