def upload_photo(self, id, **kwargs): try: file = flask.request.files.get('file', None) if not file: raise exception.BadRequest() token = self.get_token(self.get_token_id()) domain_id = self.get_domain_id_from_token(token) user_id = token.user_id if not (domain_id and user_id): raise exception.BadRequest() kwargs['domain_id'] = domain_id kwargs['user_id'] = user_id kwargs['type_image'] = 'UserPhoto' image = self.manager.api.images().create(file=file, **kwargs) kwargs.pop('type_image') kwargs['photo_id'] = image.id self.manager.upload_photo(id=id, **kwargs) response = {'image': image.to_dict()} except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=utils.to_json(response), status=201, mimetype="application/json")
def _validate_order_by(order_by: Optional[str], resource: Type[Any]): if order_by is None: return None order_by_post_split = order_by.split(',') for item in order_by_post_split: splited_item = item.split() if len(splited_item) < 3 and len(splited_item) > 0: if len(splited_item) == 1 or (splited_item[1] == 'asc' or splited_item[1] == 'desc'): attr = splited_item[0] if hasattr(resource, attr): table_name = resource.__tablename__ columns = resource.metadata.tables[table_name].columns\ ._all_columns columns_name = list( map(lambda item: item.name, columns)) if attr not in columns_name: raise exception.BadRequest(f'{attr} is \ not a column in table {table_name}') else: raise exception.BadRequest(f'{attr} is \ not a attribute in class {resource.__name__}') else: raise exception.BadRequest( 'Each order_by item must be the \ attribute name and optionally "asc" (sort ascending) or\ "desc" (sort descending)') else: raise exception.BadRequest('each order_by item must be one or\ two words at most')
def get_pagination(cls, resource: Type[Any], **kwargs): try: page = kwargs.pop('page', None) page = int(page) if page is not None else None page_size = kwargs.pop('page_size', None) page_size = int(page_size) if page_size is not None else None order_by = kwargs.pop('order_by', None) name_pagination_column = 'pagination_column' if order_by is None and page is not None and page_size is not None \ and hasattr(resource, name_pagination_column): order_by = getattr(resource, name_pagination_column) if page_size is not None and page_size <= 0: raise exception.BadRequest( 'page_size must be greater than to zero') if page is not None and page < 0: raise exception.BadRequest( 'page must be greater than or equal to zero') cls._validate_order_by(order_by, resource) except BadRequest as br: raise exception.BadRequest(br.message) except ValueError: raise exception.BadRequest('page or page_size is invalid') return cls(page=page, page_size=page_size, order_by=order_by)
def pre(self, session, id, **kwargs): old_password = kwargs.pop('old_password', None) self.password = kwargs.pop('password', None) if not (id and self.password and old_password): raise exception.BadRequest() super().pre(session=session, id=id) if not self._check_password(old_password, self.entity.password): raise exception.BadRequest() return True
def pre(self, session, token_id, domain_id, user_admin_id): if not (user_admin_id or domain_id): raise exception.BadRequest( 'ERROR! Not enough data to Activate Domain') self.token_id = token_id self.domain_id = domain_id self.user_admin_id = user_admin_id roles = self.manager.api.roles().list(name='Admin') if not roles: raise exception.BadRequest('ERROR! Role Admin not found') self.role_admin = roles[0] return True
def pre(self, session, id: str, **kwargs) -> bool: self.keys = kwargs.get('keys', []) if not self.keys: raise exception.BadRequest('Erro! keys are empty') super().pre(session, id=id) return self.entity.is_stable()
def instantiate(self, **kwargs): try: embedded = {} for attr in self.resource.embedded(): if attr not in kwargs: raise Exception() embedded.update({attr: kwargs.pop(attr)}) instance = self.resource(**kwargs) for attr in embedded: value = embedded[attr] var = getattr(self.resource, attr) # TODO(samueldmq): is this good enough? should we discover it? mapped_attr = {self.resource.individual() + '_id': instance.id} if isinstance(value, list): setattr(instance, attr, [ var.property.mapper.class_(id=uuid.uuid4().hex, **dict(ref, **mapped_attr)) for ref in value ]) else: # TODO(samueldmq): id is inserted here. it is in the # manager for the entities. do it all in the resource # contructor setattr( instance, attr, var.property.mapper.class_(id=uuid.uuid4().hex, **dict( value, **mapped_attr))) except Exception: # TODO(samueldmq): replace with specific exception raise exception.BadRequest() return instance
def list(self): filters = self._filters_parse() filters = self._filters_cleanup(filters) try: filters = self._parse_list_options(filters) entities = self.manager.list(**filters) with_pagination = False require_pagination = filters.get('require_pagination', False) page = filters.get('page', None) page_size = filters.get('page_size', None) if (page and page_size is not None) and require_pagination is True: with_pagination = True count = self.manager.count(**(self._clean_filters(**filters))) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) except ValueError: raise exception.BadRequest('page or page_size is invalid') collection = self._entities_to_dict( entities, self._get_include_dicts()) response = {self.collection_wrap: collection} if with_pagination: response.update({'pagination': {'page': int(page), 'page_size': int(page_size), 'total': count}}) return flask.Response(response=utils.to_json(response), status=200, mimetype="application/json")
def send_email(type_email, token_id, user, domain): try: sparkpost = SparkPost() (app_name, base_url, noreply_email, email_subject, email_use_sandbox) = _get_variables() if type_email in [TypeEmail.USER_CREATED, TypeEmail.FORGOT_PASSWORD]: html = get_html_reset_password( app_name, base_url, type_email, token_id, domain, user) elif type_email is TypeEmail.ACTIVATE_ACCOUNT: html = get_html_activate_account(app_name, base_url, type_email.template, token_id, user, domain) elif type_email is TypeEmail.UPDATED_PASSWORD: return None else: raise exception.BadRequest() sparkpost.transmissions.send( use_sandbox=email_use_sandbox, recipients=[user.email], html=html, from_email=noreply_email, subject=email_subject ) except Exception: # TODO(fdoliveira): do something here! pass
def pre(self, session, id, **kwargs): super().pre(session, id=id) policies = self.manager.api.policies().list(capability_id=id) if policies: message = 'You can\'t remove this capability because' + \ ' there are policies associated' raise exception.BadRequest(message) return True
def remove_setting(self, key: str): if not self._has_setting(key): raise exception.BadRequest(f"Erro! Setting {key} not exists") settings = self.settings value = settings.pop(key) self._save_settings(settings) return value
def update(self, entity, data, session): # try: # entity = self.get(id, session) # except exc.NoResultFound: # raise exception.NotFound() for attr in self.resource.embedded(): if attr in data: value = data.pop(attr) var = getattr(self.resource, attr) # TODO(samueldmq): is this good enough? should we discover it? mapped_attr = {self.resource.individual() + '_id': id} if isinstance(value, list): setattr(entity, attr, [ var.property.mapper.class_(id=self.removeId(ref), **dict(ref, **mapped_attr)) for ref in value ]) else: # TODO(samueldmq): id is inserted here. it is in the # manager for the entities. do it all in the resource # contructor setattr( entity, attr, var.property.mapper.class_(id=uuid.uuid4().hex, **dict( value, **mapped_attr))) for key, value in data.items(): if hasattr(entity, key): try: setattr(entity, key, value) except AttributeError: raise exception.BadRequest( f'Error! The attribute {key} is read only') else: raise exception.BadRequest( f'Error! The attribute {key} not exists') if not entity.is_stable(): raise exception.PreconditionFailed() session.flush() return entity
def _get_activate_data(self): data = flask.request.get_json() user_id = data.get('user_id', None) domain_id = data.get('domain_id', None) if not (user_id and domain_id): raise exception.BadRequest() return (user_id, domain_id)
def pre(self, session, id, name, **kwargs): domain = self.manager.api.domains().get(id=id) if not domain: raise exception.NotFound('ERROR! Domain not found') self.domain_id = domain.id if not name: raise exception.BadRequest('ERROR! Invalid name') self.name = name return True
def _get_application_id(self, session, user_id): result_application = session.query(Domain.application_id). \ join(User). \ filter(User.id == user_id). \ first() if not result_application.application_id: raise exception.BadRequest( 'This user is not associated with any applications') return result_application.application_id
def do(self, session, **kwargs): self.manager.api.domains().update(id=self.domain_id, active=True) self.manager.api.users().update(id=self.user_admin_id, active=True) self.manager.api.grants().create(user_id=self.user_admin_id, role_id=self.role_admin.id) self.manager.api.tokens().delete(id=self.token_id) domain = self.manager.api.domains().get(id=self.domain_id) if not domain: raise exception.BadRequest('ERROR! Domain not found') return domain
def pre(self, session, username, email, password, domain_name, domain_display_name, application_name): self.username = username self.email = email self.password = password self.domain_name = domain_name self.domain_display_name = domain_display_name self.application_name = application_name user_params_ok = username and email and password app_params_ok = domain_name and application_name if not user_params_ok and app_params_ok: raise exception.BadRequest( 'ERROR! Not enough data to register domain') applications = \ self.manager.api.applications().list(name=application_name) if not applications: raise exception.BadRequest('ERROR! Application name not found.') self.application = applications[0] return True
def _get_register_data(self): data = flask.request.get_json() username = data.get('username', 'admin') email = data.get('email', None) password = data.get('password', None) domain_name = data.get('domain', None) application_name = data.get('application', None) if not (username and email and password and domain_name and application_name): raise exception.BadRequest() return (username, email, password, domain_name, application_name)
def do(self, session, **kwargs): domains = self.manager.api.domains().list(name=self.domain_name) if not domains: self._register_domain(self.domain_name, self.domain_display_name, self.application.id, self.username, self.email, self.password) else: domain = domains[0] users = self.manager.api.users().list(email=self.email, domain_id=domain.id) if domain.active: raise exception.BadRequest('Domain already activated') if not users or domain.display_name != self.domain_display_name: raise exception.BadRequest('Domain already registered') self.user = users[0] self.manager.api.users().reset(id=self.user.id, password=self.password) return True
def do(self, session, **kwargs): super().do(session) # TODO (araujobd) check a better way to improve this # only way to validate resolution of image was after # save temporary file so if exceeds should trigger rollback folder = self.manager.get_upload_folder(self.entity, self.entity.domain_id) error_message = ImageHandler.verify_size_resolution_image( folder, self.entity.filename) if error_message is not None: shutil.rmtree(folder) raise exception.BadRequest(error_message) return self.entity
def _parse_list_options(self, filters): _filters = filters.copy() options = _filters.pop('list_options', None) if 'active' in _filters.keys(): return _filters try: options = ListOptions.new(options) except KeyError: raise exception.BadRequest(ListOptions.invalid_message_error()) value = options.value['value'] if value is not None: _filters['active'] = value return _filters
def notify(self, id): data = flask.request.get_json() try: type_email = TypeEmail.value_of(data.get('type_email', None)) token = self.get_token(self.get_token_id()) if not type_email or not token: raise exception.BadRequest() self.manager.notify(id=id, type_email=type_email, token=token) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=None, status=204, mimetype="application/json")
def upload_logo(self, id): try: token = flask.request.headers.get('token') file = flask.request.files.get('file', None) if not file: raise exception.BadRequest('ERROR! File not found in request.') image = self.manager.upload_logo(id=id, token=token, file=file) response = {'image': image.to_dict()} except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=utils.to_json(response), status=201, mimetype="application/json")
def get_nextval(self, id): data = flask.request.get_json() try: if 'name' not in data: raise exception.BadRequest('ERROR! "name" não not defined') response = self.manager.get_nextval(id=id, name=data['name']) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) response = {'nextval': response} return flask.Response(response=utils.to_json(response), status=200, mimetype="application/json")
def reset_my_password(self): if not flask.request.is_json: return flask.Response( response=exception.BadRequestContentType.message, status=exception.BadRequestContentType.status) data = flask.request.get_json() try: token = self.get_token(self.get_token_id()) if not token: raise exception.BadRequest() self.manager.reset(id=token.user_id, **data) self.manager.api.tokens().delete(id=token.id) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=None, status=204, mimetype="application/json")
def activate(self): try: (user_id, domain_id) = self._get_activate_data() domain = self.manager.api.domains().get(id=domain_id) user = self.manager.api.users().get(id=user_id) if not (domain and user): raise exception.BadRequest() role_admin = self._get_role_admin() self.manager.api.domains().update(id=domain.id, active=True) self.manager.api.users().update(id=user.id, active=True) self.manager.api.grants().create(user_id=user.id, role_id=role_admin.id) self.manager.api.tokens().delete(id=self._get_token_id()) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=None, status=204, mimetype="application/json")
def pre(self, session, id: str, **kwargs) -> bool: self.role_id = id self.application_id = kwargs.get('application_id', None) resources = kwargs.get('resources', None) if ((not (self.role_id and self.application_id)) or resources is None): raise exception.OperationBadRequest() try: self.manager.api.applications().get(id=self.application_id) except exception.NotFound: raise exception.BadRequest('Invalid application') routes = self.manager.api.routes().list(sysadmin=False, bypass=False, active=True) capabilities = self.manager.api.capabilities().list( application_id=self.application_id) policies = self.manager.api.policies().list(role_id=self.role_id) self.capabilities = self._filter_capabilities(routes, capabilities, policies, resources) return self.driver.get(id, session) is not None
def update_password(self, id): data = flask.request.get_json() try: token = self.get_token(self.get_token_id()) password = data.get('password', None) old_password = data.get('old_password', None) if token.user_id != id: error = exception.InfoSystemException() error.status = 401 error.message = "Not Authorized" raise error if not password or not old_password: raise exception.BadRequest() self.manager.update_password(id=id, password=password, old_password=old_password) except exception.InfoSystemException as exc: return flask.Response(response=exc.message, status=exc.status) return flask.Response(response=None, status=204, mimetype="application/json")
def pre(self, session, id, **kwargs): self.password = kwargs.get('password', None) if not (id and self.password): raise exception.BadRequest() super().pre(session=session, id=id) return True
def pre(self, session, id, type_email, **kwargs): self.user = self.manager.get(id=id) self.type_email = type_email if not self.user or not self.type_email: raise exception.BadRequest() return True