示例#1
0
	def send_token(self, username, method):
		if ucr.is_false('umc/self-service/passwordreset/backend/enabled'):
			msg = _('The password reset was disabled via the Univention Configuration Registry.')
			MODULE.error('send_token(): {}'.format(msg))
			raise UMC_Error(msg)
		MODULE.info("send_token(): username: '******' method: '{}'.".format(username, method))
		try:
			plugin = self.password_reset_plugins[method]
		except KeyError:
			MODULE.error("send_token() method '{}' not in {}.".format(method, self.password_reset_plugins.keys()))
			raise UMC_Error(_("Unknown recovery method '{}'.").format(method))

		if self.is_blacklisted(username, 'passwordreset'):
			raise MissingContactInformation()

		# check if the user has the required attribute set
		user = self.get_udm_user(username=username)
		username = user["username"]

		if len(user[plugin.udm_property]) > 0:
			# found contact info
			self.send_message(username, method, user[plugin.udm_property])

		# no contact info
		raise MissingContactInformation()
    def execute(self, method, request, *args, **kwargs):
        self.__requests[request.id] = (request, method)

        try:
            function = getattr(self, method)
        except AttributeError:
            message = self._(
                'Method %(method)r (%(path)r) in %(module)r does not exist.\n\n%(traceback)s'
            ) % {
                'method': method,
                'path': request.arguments,
                'module': self.__class__.__module__,
                'traceback': traceback.format_exc()
            }
            self.finished(request.id, None, message=message, status=500)
            return

        try:
            MODULE.info('Executing %r' %
                        (request.arguments or request.command, ))
            self._parse_accept_language(request)
            if ucr.is_false('umc/server/disable-security-restrictions', True):
                self.security_checks(request, function)
            function.__func__(self, request, *args, **kwargs)
        except (KeyboardInterrupt, SystemExit):
            self.finished(
                request.id,
                None,
                self.
                _('The UMC service is currently shutting down or restarting. Please retry soon.'
                  ),
                status=503)
            raise
        except:
            self.__error_handling(request, method, *sys.exc_info())
示例#3
0
	def send_verification_token(self, username):
		MODULE.info("send_verification_token(): username: {}".format(username))
		ucr.load()
		if ucr.is_false('umc/self-service/account-verification/backend/enabled', True):
			msg = _('The account verification was disabled via the Univention Configuration Registry.')
			MODULE.error('send_verification_token(): {}'.format(msg))
			raise UMC_Error(msg)
		invalid_information = {
			'success': False,
			'failType': 'INVALID_INFORMATION'
		}
		users_mod = UDM.machine().version(2).get('users/user')
		try:
			user = users_mod.get_by_id(username)
		except NoObject:
			return invalid_information
		try:
			email = user.props.PasswordRecoveryEmail
		except AttributeError:
			return invalid_information
		else:
			if not email:
				return invalid_information
		self.send_message(username, 'verify_email', email, raise_on_success=False)
		return {
			'success': True,
			'data': {
				'username': username,
			}
		}
示例#4
0
	def set_contact(self, username, password, email=None, mobile=None):
		if ucr.is_false('umc/self-service/protect-account/backend/enabled'):
			msg = _('The account protection was disabled via the Univention Configuration Registry.')
			MODULE.error('set_contact(): {}'.format(msg))
			raise UMC_Error(msg)
		MODULE.info("set_contact(): username: {} password: ***** email: {} mobile: {}".format(username, email, mobile))
		dn, username = self.auth(username, password)
		if self.is_blacklisted(username, 'passwordreset'):
			raise ServiceForbidden()
		try:
			return self.set_contact_data(dn, email, mobile)
		except Exception:
			raise UMC_Error(_('Changing contact data failed.'), status=500)
示例#5
0
	def deregister_account(self, username, password):
		MODULE.info("deregister_account(): username: {} password: *****".format(username))
		ucr.load()
		if ucr.is_false('umc/self-service/account-deregistration/enabled', True):
			msg = _('The account deregistration was disabled via the Univention Configuration Registry.')
			MODULE.error('deregister_account(): {}'.format(msg))
			raise UMC_Error(msg)
		dn, username = self.auth(username, password)
		if self.is_blacklisted(username, 'account-deregistration'):
			raise ServiceForbidden()
		try:
			return self._deregister_account(username)
		except Exception:
			raise UMC_Error(_('Account could not be deleted'), status=500)
示例#6
0
    def vnc(self, request):
        """Returns a ultraVNC file for the given computer."""

        # check whether VNC is enabled
        if ucr.is_false('ucsschool/umc/computerroom/ultravnc/enabled', True):
            raise UMC_Error('VNC is disabled')

        try:
            with open('/usr/share/ucs-school-umc-computerroom/ultravnc.vnc',
                      'rb') as fd:
                content = fd.read()
        except (IOError, OSError):
            raise UMC_Error('VNC template file does not exists')

        port = ucr.get('ucsschool/umc/computerroom/vnc/port', '11100')
        hostname = request.options['computer'].ipAddress

        response = content.replace('@%@HOSTNAME@%@',
                                   hostname).replace('@%@PORT@%@', port)
        self.finished(request.id, response, mimetype='application/x-vnc')
示例#7
0
	def get_reset_methods(self, username):
		if ucr.is_false('umc/self-service/passwordreset/backend/enabled'):
			msg = _('The password reset was disabled via the Univention Configuration Registry.')
			MODULE.error('get_reset_methods(): {}'.format(msg))
			raise UMC_Error(msg)
		if self.is_blacklisted(username, 'passwordreset'):
			raise NoMethodsAvailable()

		user = self.get_udm_user(username=username)
		if not self.password_reset_plugins:
			raise NoMethodsAvailable()

		# return list of method names, for all LDAP attribs user has data
		reset_methods = [{
			"id": p.send_method(),
			"label": p.send_method_label()
		} for p in self.password_reset_plugins.values() if user[p.udm_property]]
		if not reset_methods:
			raise NoMethodsAvailable()
		return reset_methods
示例#8
0
	def verify_contact(self, token, username, method):
		MODULE.info('verify_contact(): token: {} username: {} method: {}'.format(token, username, method))
		ucr.load()
		if ucr.is_false('umc/self-service/account-verification/backend/enabled', True):
			msg = _('The account verification was disabled via the Univention Configuration Registry.')
			MODULE.error('verify_contact(): {}'.format(msg))
			raise UMC_Error(msg)
		users_mod = UDM.admin().version(1).get('users/user')
		try:
			user = users_mod.get_by_id(username)
		except NoObject:
			return {
				'success': False,
				'failType': 'INVALID_INFORMATION',
			}
		next_steps = ucr.get('umc/self-service/account-verification/next-steps/%s' % self.locale.language, '')
		if not next_steps:
			next_steps = ucr.get('umc/self-service/account-verification/next-steps', '')
		plugin = self._get_send_plugin(method)
		if getattr(user.props, plugin.udm_property) == 'TRUE':  # cleanup. map property to actual boolean?
			return {
				'success': True,
				'successType': 'ALREADY_VERIFIED',
				'data': {
					'username': username,
					'nextSteps': next_steps,
				}
			}
		self._check_token(username, token, token_application=plugin.message_application())
		setattr(user.props, plugin.udm_property, 'TRUE')
		user.save()
		self.db.delete_tokens(token=token, username=username)
		return {
			'success': True,
			'successType': 'VERIFIED',
			'data': {
				'username': username,
				'nextSteps': next_steps,
			}
		}
示例#9
0
	def get_contact(self, username, password):
		"""
		Get users contact data.

		:return: list of dicts with users contact data
		"""
		if ucr.is_false('umc/self-service/protect-account/backend/enabled'):
			msg = _('The account protection was disabled via the Univention Configuration Registry.')
			MODULE.error('get_contact(): {}'.format(msg))
			raise UMC_Error(msg)
		dn, username = self.auth(username, password)
		if self.is_blacklisted(username, 'passwordreset'):
			raise ServiceForbidden()

		user = self.get_udm_user(username=username)
		if not self.password_reset_plugins:
			raise ServiceForbidden()

		return [{
			"id": p.send_method(),
			"label": p.send_method_label(),
			"value": user[p.udm_property]
		} for p in self.password_reset_plugins.values() if p.udm_property in user]
示例#10
0
	def create_self_registered_account(self, attributes):
		MODULE.info('create_self_registered_account(): attributes: {}'.format(attributes))
		ucr.load()
		if ucr.is_false('umc/self-service/account-registration/backend/enabled', True):
			msg = _('The account registration was disabled via the Univention Configuration Registry.')
			MODULE.error('create_self_registered_account(): {}'.format(msg))
			raise UMC_Error(msg)
		# filter out attributes that are not valid to set
		allowed_to_set = set(['PasswordRecoveryEmail', 'password'] + [attr.strip() for attr in ucr.get('umc/self-service/account-registration/udm_attributes', '').split(',') if attr.strip()])
		attributes = {k: v for (k, v) in attributes.items() if k in allowed_to_set}
		# validate attributes
		res = self._validate_user_attributes(attributes, self._update_required_attr_of_props_for_registration)
		# check username taken
		if 'username' in attributes:
			try:
				UDM.machine().version(2).get('users/user').get_by_id(attributes['username'])
			except NoObject:
				pass
			else:
				res['username'] = {
					'isValid': False,
					'message': _('The username is already taken'),
				}
		invalid = {k: v for (k, v) in res.items() if not (all(v['isValid']) if isinstance(v['isValid'], list) else v['isValid'])}
		if len(invalid):
			return {
				'success': False,
				'failType': 'INVALID_ATTRIBUTES',
				'data': invalid,
			}

		# check for missing required attributes from umc/self-service/account-registration/udm_attributes/required
		required_attrs = [attr.strip() for attr in ucr.get('umc/self-service/account-registration/udm_attributes/required', '').split(',') if attr.strip()]
		not_found = [attr for attr in required_attrs if attr not in attributes]
		if not_found:
			msg = _('The account could not be created:\nInformation provided is not sufficient. The following properties are missing:\n%s') % ('\n'.join(not_found),)
			MODULE.error('create_self_registered_account(): {}'.format(msg))
			raise UMC_Error(msg)

		univention.admin.modules.update()
		lo, po = get_admin_connection()

		# get usertemplate
		template_dn = ucr.get('umc/self-service/account-registration/usertemplate', '')
		usertemplate = None
		if template_dn:
			usertemplate_mod = univention.admin.modules.get('settings/usertemplate')
			univention.admin.modules.init(lo, po, usertemplate_mod, None, True)
			try:
				usertemplate = usertemplate_mod.object(None, lo, None, template_dn)
			except udm_errors.noObject:
				msg = _('The user template "{}" set by the "umc/self-service/account-registration/usertemplate" UCR variable does not exist. A user account can not be created. Please contact your system administrator.'.format(template_dn))
				MODULE.error('create_self_registered_account(): {}'.format(msg))
				raise UMC_Error(msg)

		# init user module with template
		usersmod = univention.admin.modules.get('users/user')
		univention.admin.modules.init(lo, po, usersmod, usertemplate, True)

		# get user container
		udm = UDM.machine().version(2)
		user_position = univention.admin.uldap.position(po.getBase())
		container_dn = ucr.get('umc/self-service/account-registration/usercontainer', None)
		if container_dn:
			try:
				container = udm.obj_by_dn(container_dn)
			except NoObject:
				msg = _('The container "{}" set by the "umc/self-service/account-registration/usercontainer" UCR variable does not exist. A user account can not be created. Please contact your system administrator.'.format(container_dn))
				MODULE.error('create_self_registered_account(): {}'.format(msg))
				raise UMC_Error(msg)
			else:
				user_position.setDn(container.dn)
		else:
			for dn in usersmod.object.get_default_containers(lo):
				try:
					container = udm.obj_by_dn(dn)
				except NoObject:
					pass
				else:
					user_position.setDn(container.dn)
					break

		# create user
		attributes['PasswordRecoveryEmailVerified'] = 'FALSE'
		attributes['RegisteredThroughSelfService'] = 'TRUE'
		new_user = usersmod.object(None, lo, user_position)
		new_user.open()
		for key, value in attributes.items():
			if key in new_user and value:
				new_user[key] = value
		try:
			new_user.create()
		except univention.admin.uexceptions.base as exc:
			MODULE.error('create_self_registered_account(): could not create user: %s' % (traceback.format_exc(),))
			return {
				'success': False,
				'failType': 'CREATION_FAILED',
				'data': _('The account could not be created:\n%s') % UDM_Error(exc),
			}
		finally:
			# TODO cleanup
			# reinit user module without template.
			# This has to be done since the modules are singletons?
			univention.admin.modules.update()
			self._usersmod = None
			#  univention.admin.modules.init(lo, po, usersmod, None, True)
		try:
			self.send_message(new_user['username'], 'verify_email', new_user['PasswordRecoveryEmail'], raise_on_success=False)
		except Exception:
			verify_token_successfully_send = False
		else:
			verify_token_successfully_send = True
		return {
			'success': True,
			'verifyTokenSuccessfullySend': verify_token_successfully_send,
			'data': {
				'username': new_user['username'],
				'email': new_user['PasswordRecoveryEmail'],
			}
		}