def upload(self, request): AzureAuth.uninitialize(self.adconnection_alias) try: adconnection_id = request.body.get('adconnection_id') or 'common' adconnection_id = urlparse.urlparse(adconnection_id).path.strip('/').split('/')[0] with open(request.options[0]['tmpfile']) as fd: manifest = Manifest(fd, adconnection_id, request.body['domain']) manifest.transform() except ManifestError as exc: raise UMC_Error(str(exc)) try: AzureAuth.store_manifest(manifest, self.adconnection_alias) except ADConnectionIDError: raise UMC_Error(_("Invalid federation metadata document address (e.g. https://login.microsoftonline.com/3e7d9eb4-c4a1-4cfd-893e-a8ec29e46b77/federationmetadata/2007-06/federationmetadata.xml).")) except AzureError as exc: raise UMC_Error(str(exc)) try: authorizationurl = AzureAuth.get_authorization_url(self.adconnection_alias) except AzureError as exc: raise UMC_Error(str(exc)) self.finished(request.id, { 'authorizationurl': authorizationurl, }, message=_('The manifest has been successfully uploaded.'))
def state(self): options = self.azure_response if not options: return progress(message=_('Waiting for authorization to be completed.'), waiting=True) if options['id_token']: try: AzureAuth.parse_id_token(options['id_token'], self.adconnection_alias) AzureAuth.store_tokens(adconnection_alias=self.adconnection_alias, consent_given=True) aa = AzureAuth("office365", self.adconnection_alias) aa.write_saml_setup_script(self.adconnection_alias) aa.set_ucs_overview_link() aa.retrieve_access_token() # not really necessary, but it'll make sure everything worked except AzureError as exc: self.init() raise UMC_Error(str(exc)) options['id_token'] = None if self.adconnection_alias: ucrv_set = '{}{}={}'.format( adconnection_alias_ucrv, self.adconnection_alias, AzureAuth.load_azure_ids(self.adconnection_alias)['adconnection_id'] ) MODULE.process('Setting UCR {}...'.format(ucrv_set)) handler_set([ucrv_set]) return progress(message=_('Successfully authorized. Starting synchronization.')) elif options['error']: self.init() raise UMC_Error(_('Microsoft reported an error condition during authorization. It might help to reauthorize. Error message: {error}: {error_description}').format(**options)) elif AzureAuth.is_initialized(self.adconnection_alias): self.init() try: ah = AzureHandler(ucr, "wizard", self.adconnection_alias) users = ah.list_users() MODULE.process('Retrieved list of users: %r' % users) #except TokenError as exc: # return except AzureError as exc: raise UMC_Error(str(exc)) try: subprocess.call(["systemctl", "restart", "univention-directory-listener.service"]) except (EnvironmentError,): pass return progress(message=_('Successfully initialized'), finished=True) return progress(message=_('Not yet initialized.'))
def security_checks(self, request, function): if request.http_method not in (u'POST', u'PUT', u'DELETE') and not getattr(function, 'allow_get', False): status = 405 if request.http_method in (u'GET', u'HEAD') else 501 raise UMC_Error(self._('The requested HTTP method is not allowed on this resource.'), status=status, headers={'Allow': 'POST'}) if getattr(function, 'xsrf_protection', True) and request.cookies.get('UMCSessionId') != request.headers.get('X-Xsrf-Protection'.title()): raise UMC_Error(self._('Cross Site Request Forgery attack detected. Please provide the "UMCSessionId" cookie value as HTTP request header "X-Xsrf-Protection".'), status=403) if getattr(function, 'referer_protection', True) and request.headers.get('Referer') and not urlparse.urlparse(request.headers['Referer']).path.startswith('/univention/'): # FIXME: we must also check the netloc/hostname/IP raise UMC_Error(self._('The "Referer" HTTP header must start with "/univention/".'), status=503) content_type = request.headers.get('Content-Type', '') allowed_content_types = ('application/json', 'application/x-www-form-urlencoded', 'multipart/form-data') if content_type and not re.match('^(%s)($|\s*;)' % '|'.join(re.escape(x) for x in allowed_content_types), content_type): raise UMC_Error(self._('The requested Content-Type is not acceptable. Please use one of %s.' % (', '.join(allowed_content_types))), status=406)
def profile_get(self, profileDN): """ Returns one profile. """ try: return self.profiles[profileDN] except LookupError: raise UMC_Error(_('Unknown profile %s') % (profileDN, ))
def umc_error_as_thread_result(self, request): # UVMM uses this to pass-through traceback from internal umc calls to the frontend try: raise UMC_Error("This is an UMC Error") except UMC_Error as result: etype, value, _ = sys.exc_info() thread = FakeThread() thread.exc_info = (etype, value, None) self.thread_finished_callback(thread, result, request)
def enable_printer(self, printer='', on=False): """ enable or disable a printer, depending on args. """ cmd = 'univention-cups-enable' if on else 'univention-cups-disable' (stdout, stderr, status) = self._shell_command([cmd, printer]) if status: raise UMC_Error( _('Could not %s printer: %s') % ( _('activate') if on else _('deactivate'), stderr, ))
def partitions_info(self, request): result = {} try: fs = fstab.File('/etc/fstab') mt = fstab.File('/etc/mtab') except IOError as error: MODULE.error('Could not open %s' % error.filename) raise UMC_Error(_('Could not open %s') % error.filename, 500) partition = fs.find(spec=request.options['partitionDevice']) if not partition: raise UMC_Error(_('No partition found')) mounted_partition = mt.find(spec=partition.spec) if not mounted_partition: raise UMC_Error(_('This partition is currently not mounted')) result['mountPoint'] = mounted_partition.mount_point result['filesystem'] = mounted_partition.type result['options'] = mounted_partition.options self.finished(request.id, result)
def cancel_jobs(self, jobs, printer=''): """ cancels one or more print jobs. Job IDs are passed as an array that can be directly passed on to the _shell_command() method """ args = ['/usr/bin/cancel', '-U', '%s$' % self._hostname] for job in jobs: args.append(job) args.append(printer) (stdout, stderr, status) = self._shell_command(args) if status: raise UMC_Error(_('Could not cancel job: %s') % (stderr, ))
def _do_activate_quota(partitions, activate): result = [] try: fs = fstab.File() except IOError as error: raise UMC_Error(_('Could not open %s') % error.filename, 500) failed = [] for device in partitions: fstab_entry = fs.find(spec=device) if not fstab_entry: failed.append(_('Device %r could not be found') % (device, )) continue try: status = _do_activate_quota_partition(fs, fstab_entry, activate) except QuotaActivationError as exc: failed.append('%s: %s' % (fstab_entry.spec, exc)) continue if fstab_entry.mount_point == '/' and fstab_entry.type == 'xfs': try: enable_quota_in_kernel(activate) except QuotaActivationError as exc: failed.append('%s: %s' % (fstab_entry.spec, exc)) continue result.append(status) if failed: message = _('Failed to activate quota support: ') if activate else _( 'Failed to deactivate quota support: ') message += '\n'.join(failed) raise UMC_Error(message) message = _('Quota support successfully activated') if activate else _( 'Quota support successfully deactivated') raise UMC_Error(message, 200, {'objects': result})
def _check_error(self, request, partition_name): try: fs = fstab.File('/etc/fstab') mt = fstab.File('/etc/mtab') except IOError as error: MODULE.error('Could not open %s' % error.filename) raise UMC_Error(_('Could not open %s') % error.filename, 500) partition = fs.find(spec=partition_name) if partition: mounted_partition = mt.find(spec=partition.spec) if mounted_partition: if not mounted_partition.hasopt( 'usrquota') and not mounted_partition.hasopt( 'usrjquota=aquota.user'): raise UMC_Error( _('The following partition is mounted without quota support: %s' ) % partition_name) else: raise UMC_Error( _('The following partition is currently not mounted: %s') % partition_name) else: raise UMC_Error(_('No partition found (%s)') % partition_name)
def _thread(request): partition = request.options['partitionDevice'] user = request.options['user'] if not isinstance(user, str): # Py2 user = user.encode('utf-8') size_soft = request.options['sizeLimitSoft'] size_hard = request.options['sizeLimitHard'] file_soft = request.options['fileLimitSoft'] file_hard = request.options['fileLimitHard'] self._check_error(request, partition) if tools.setquota(partition, user, tools.byte2block(size_soft), tools.byte2block(size_hard), file_soft, file_hard): raise UMC_Error( _('Failed to modify quota settings for user %(user)s on partition %(partition)s.' ) % { 'user': user, 'partition': partition })
def _thread(request): partitions = [] failed = [] # Determine different partitions for obj in request.options: partitions.append(obj['object'].split('@', 1)[-1]) for partition in set(partitions): self._check_error(request, partition) # Remove user quota for obj in request.options: (user, _, partition) = obj['object'].partition('@') if not isinstance(user, str): # Py2 user = user.encode('utf-8') if tools.setquota(partition, user, 0, 0, 0, 0): failed.append(user) if failed: raise UMC_Error( _('Could not remove the following user: %s') % ', '.join(failed))
def partitions_query(self, request): result = [] try: fs = fstab.File('/etc/fstab') mt = fstab.File('/etc/mtab') except IOError as error: MODULE.error('Could not open %s' % error.filename) raise UMC_Error(_('Could not open %s') % error.filename, 500) partitions = fs.get(['xfs', 'ext4', 'ext3', 'ext2'], False) for partition in partitions: list_entry = {} list_entry['partitionDevice'] = partition.spec list_entry['mountPoint'] = partition.mount_point list_entry['partitionSize'] = None list_entry['freeSpace'] = None list_entry['inUse'] = tools.quota_is_enabled(partition) mounted_partition = mt.find(spec=partition.spec) if mounted_partition: partition_info = df.DeviceInfo(partition.mount_point) list_entry['partitionSize'] = tools.block2byte(partition_info.size(), 'GB', 1) list_entry['freeSpace'] = tools.block2byte(partition_info.free(), 'GB', 1) result.append(list_entry) self.finished(request.id, result)
def umc_error_traceback(self): raise UMC_Error("This is an UMC Error")
def _response(self, request): if request.command != 'UPLOAD': raise UMC_Error(_('%s can only be used as UPLOAD') % (function.__name__)) return function(self, request)