def _parse_locations(self, res): if not self.returnGeometry: attrs2Del = ['x', 'y', 'lon', 'lat', 'geom_st_box2d'] popAtrrs = lambda x: res.pop(x) if x in res else x map(popAtrrs, attrs2Del) elif int(self.srid) not in (21781, 2056): self._box2d_transform(res) if int(self.srid) == 4326: try: res['x'] = res['lon'] res['y'] = res['lat'] except KeyError: raise exc.HTTPInternalServerError( 'Sphinx location has no lat/long defined') else: try: pnt = (res['y'], res['x']) x, y = transform_coordinate(pnt, self.DEFAULT_SRID, self.srid) res['x'] = x res['y'] = y except Exception: raise exc.HTTPInternalServerError( 'Error while converting point(x, y) to EPSG:{}'.format( self.srid)) return res
def wrapper(request, *args, user=None, **kwargs): """Redirect user.""" if oauth_condition(request) is False: return view_function(request, *args, user=user, **kwargs) consumer_key = request.params["oauth_consumer_key"] application_instance = find_by_oauth_consumer_key(request.db, consumer_key) client_id = application_instance.developer_key if application_instance is None: raise exc.HTTPInternalServerError() authorization_base_url = build_auth_base_url( application_instance.lms_url, authorization_base_endpoint ) redirect_uri = build_redirect_uri(request.url, redirect_endpoint) oauth_session = requests_oauthlib.OAuth2Session( client_id, redirect_uri=redirect_uri ) authorization_url, state_guid = oauth_session.authorization_url( authorization_base_url ) oauth_state = find_or_create_from_user( request.db, state_guid, user, request.params ) if oauth_state is None: raise exc.HTTPInternalServerError() return exc.HTTPFound(location=authorization_url)
def response_builder(req): # version 1.0 project_id = req.matchdict['project_id'] api_key = req.params['api_key'] ext = req.matchdict['ext'] validator = req.find_service(iface=IValidator, name='credential') site_id = validator.site_id if not site_id: raise exc.HTTPInternalServerError() initiator = req.find_service(iface=IInitiator, name='session') token = initiator.provision(project_id=project_id, site_id=site_id, api_key=api_key, ctx='read') if not token: logger.error('no token') raise exc.HTTPInternalServerError() # minified result = render(tpl_dst('heatmap-' + extension, ext), dict(token=token), req) res = Response(result) res.content_type = 'text/{0:s}'.format( 'javascript' if ext == 'js' else 'css') req.add_response_callback(no_cache) return res
def view_clients_get(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None if client_id is None: raise exception.HTTPBadRequest(detail='Missing required parameters', explanation='Client Id is required') services = request.services() client = None try: clientsStore = services['store.admin.clients'] client = clientsStore.get(client_id) except Exception as e: raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) if client is None: raise exception.HTTPInternalServerError(detail='Client not found', explanation='Client not found') else: raise exception.HTTPOk(detail='client', body={ 'client': { 'id': client[0], 'active': client[1], 'name': client[2], 'address': client[3], 'countryId': client[4], 'currencyId': client[5] } })
def get_key(self, file_id): key = None try: key = self.bucket.get_key(file_id) except S3ResponseError as e: raise exc.HTTPInternalServerError( 'Cannot access file with id=%s: %s' % (file_id, e)) except Exception as e: raise exc.HTTPInternalServerError( 'Cannot access file with id=%s: %s' % (file_id, e)) return key
def wrapper(request, *args, **kwargs): """Route to handle content item selection oauth response.""" if "state" not in request.params or "code" not in request.params: raise exc.HTTPInternalServerError("Invalid Oauth Response") lti_params = lti_params_for(request) application_instance = find_by_oauth_consumer_key( request.db, lti_params["oauth_consumer_key"] ) if application_instance is None: raise exc.HTTPInternalServerError() aes_secret = request.registry.settings["aes_secret"] client_id = application_instance.developer_key client_secret = application_instance.decrypted_developer_secret(aes_secret) token_url = build_canvas_token_url(application_instance.lms_url) state = request.params["state"] session = requests_oauthlib.OAuth2Session(client_id, state=state) oauth_resp = session.fetch_token( token_url, client_secret=client_secret, authorization_response=request.url, code=request.params["code"], ) user = find_user_from_state(request.db, state) if application_instance is None: raise exc.HTTPInternalServerError("Application instance was not found") new_token = build_token_from_oauth_response(oauth_resp) update_user_token(request.db, new_token, user) jwt_token = build_jwt_from_lti_launch( lti_params, request.registry.settings["jwt_secret"] ) return view_function( request, *args, token=new_token, lti_params=lti_params, user=user, jwt=jwt_token, **kwargs )
def index(self): """ Produce a list of packages stored in the global catalog: http://example.com/v1/products/{product_id}/packages """ logger.info("======= index =======") try: # product_id is not used atm product_id = self.request.matchdict.get('product_id', None) if not product_id: return httpexceptions.HTTPBadRequest( json_body={'errors': "Missing Product ID"}) filters = self.request.params.get('filters') kwargs = {} if filters: kwargs['filters'] = filters result = package.get_package_list(**kwargs) if result['status'] == 200: return result else: return httpexceptions.HTTPNotFound(json_body={}) except Exception as e: logger.exception(e) tb = traceback.format_exc() return httpexceptions.HTTPInternalServerError( json_body={'errors': "{0}, {1}".format(e, tb)}, explanation=e, detail=tb)
def api_purchasing_vendor_get(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None vendor_id = params['vendorId'] if 'vendorId' in params else None if client_id is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id and filter is required') services = request.services() vendorStore = services['store.purchasing.vendors'] vendor = {} try: r = vendorStore.get(client_id, vendor_id) vendor = { 'id': r[0], 'name': r[1], 'address': r[2], 'country_id': r[3] } except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='vendor found', body={'vendor': vendor})
def api_hr_members_get(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None member_id = params['memberId'] if 'memberId' in params else None if client_id is None or member_id is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and Member Id is required') services = request.services() membersStore = services['store.hr.members'] member = {} try: r = membersStore.get(client_id, member_id) result_ids = membersStore.get_ids(member_id) identifiers = [{'idType': r[0], 'value': r[1]} for r in result_ids] member = { 'id': r[0], 'firstName': r[1], 'middleName': r[2], 'lastName': r[3], 'prefix': r[4], 'suffix': r[5], 'identifiers': identifiers } except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='member found', body={'member': member})
def api_members_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and filter is required') services = request.services() membersStore = services['store.hr.members'] members = [] try: result = membersStore.filter(client_id, filter) members = [{ 'id': r[0], 'firstName': r[1], 'middleName': r[2], 'lastName': r[3], 'prefix': r[4], 'suffix': r[5] } for r in result] except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail=f'{len(members)} members found', body={'members': members})
def view_clients_roles_permissions(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None role_id = params['roleId'] if 'roleId' in params else None if client_id is None or role_id is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and Role Id is required' ) permissions = [] services = request.services() try: rolesStore = services['store.admin.roles'] result = rolesStore.permissions(client_id, role_id) permissions = [{ 'id': r[0], 'active': r[1], 'name': r[2] } for r in result] except Exception as e: raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='{0} client roles found'.format(len(permissions)), body={ 'permissions': permissions } )
def view_clients_organizations_set_parent(request): params = request.json_body org_id = params['organizationId'] if 'organizationId' in params else None parent_org_id = params[ 'parentOrganizationId'] if 'parentOrganizationId' in params else None if org_id is None or parent_org_id is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Organization Id and Parent Organization Id is required' ) session = request.session client_id = session['client'] services = request.services() try: orgStore = services['store.clients.organizations'] result = orgStore.setParentOrg(client_id, org_id, parent_org_id) except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk( detail='Client Organization assigned', body={'message': 'Client Organization assigned parent'})
def api_hr_shifts_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and filter is required') services = request.services() store = services['store.hr.shifts'] shifts = [] try: result = store.filter(client_id, filter) shifts = [{ 'id': r[0], 'active': r[1], 'created': r[2], 'name': r[3], 'start': r[4], 'end': r[5] } for r in result] except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail=f'{len(result)} shifts found', body={'shifts': shifts})
def api_common_countries_get(request): params = request.json_body country_id = params['countryId'] if 'countryId' in params else None if country_id is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Country Id is required' ) services = request.services() store = services['store.common.countries'] country = {} try: r = store.get(country_id) country = { 'name': r[0], 'alpha_2': r[1], 'alpha_3': r[2], 'id': r[3] } except Exception as e: log.error(e) raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='country found', body={ 'country': country } )
def delete_swatch(self): try: deleted = swatchservice.delete_swatch( self.user_id, self.request.matchdict['swatch_name']) return exp.HTTPOk() if deleted else exp.HTTPNotFound() except: return exp.HTTPInternalServerError()
def api_accounting_account_get(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None account_id = params['accountId'] if 'accountId' in params else None if client_id is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id and Account Id is required') services = request.services() account = {} try: accountStore = services['store.accounting.accounts'] r = accountStore.get(client_id, account_id) account = { 'id': r[0], 'active': r[1], 'created_ts': r[2], 'type_id': r[3], 'name': r[4], 'description': r[5] } except StoreException as e: raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='account found', body={'account': account})
def view_accounting_accounts_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id and filter is required') services = request.services() accounts = [] try: accountStore = services['store.accounting.accounts'] result = accountStore.filter(client_id, filter) accounts = [{ 'id': r[0], 'active': r[1], 'type_id': r[2], 'name': r[3], 'description': r[4] } for r in result] except Exception as e: raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='{0} accounts found'.format(len(accounts)), body={'accounts': accounts})
def view_clients_organizations_update(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None org_id = params['organizationId'] if 'organizationId' in params else None name = params['name'] if 'name' in params else None description = params['description'] if 'description' in params else None if client_id is None or org_id is None or name is None or description is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation= 'Client Id, Organization Id, name and description is required') session = request.session client_id = session['client'] services = request.services() try: orgStore = services['store.clients.organizations'] result = orgStore.update(client_id, org_id, name, description) except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='Client Organization updated', body={'message': 'Client Organization updated'})
def view_client_roles_permission_remove(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None role_id = params['roleId'] if 'roleId' in params else None permission_id = params['permissionId'] if 'permissionId' in params else None if client_id is None or role_id is None or permission_id is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id, Role Id and Permission Id is required' ) services = request.services() try: rolesStore = services['store.admin.roles'] rolesStore.removePermission(client_id, role_id, permission_id) except Exception as e: raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='client role permission removed', body={ 'message': 'Client Role permission removed' } )
def view_clients_user_remove(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None user_id = params['userId'] if 'userId' in params else None if client_id is None or user_id is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id and User Id is required' ) services = request.services() try: usersStore = services['store.admin.users'] usersStore.removeClientUser(client_id, user_id) except Exception as e: log.error(e) raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='Client User removed', body={'message': 'Client User removed'} )
def api_hr_shifts_save(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None shift_id = params['shiftId'] if 'shiftId' in params else None name = params['name'] if 'name' in params else None start = params['start'] if 'start' in params else None end = params['end'] if 'end' in params else None if client_id is None or shift_id is None or name is None or start is None or end is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation= 'Client Id, shift id, name, start and end times are required') services = request.services() store = services['store.hr.shifts'] try: store.save(client_id, shift_id, name, start, end) except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='shift record saved', body={'message': 'shift record saved'})
def view_clients_roles_add(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None role_id = params['roleId'] if 'roleId' in params else None name = params['name'] if 'name' in params else None if not all([client_id, role_id, name]): raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and Role Name is required' ) services = request.services() try: rolesStore = services['store.admin.roles'] rolesStore.add( client_id, role_id, name ) except Exception as e: log.error(e) raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='Client Role added', body={'message': 'Client Role added'} )
def api_common_uom_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None dimension = params['dimension'] if 'dimension' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None or dimension is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id, dimension and filter is required') services = request.services() uoms = [] try: store = services['store.common.uom'] result = [] if filter is None: result = store.all() else: result = store.filter(client_id, dimension, filter) uoms = [{'id': r[0], 'name': r[1], 'symbol': r[2]} for r in result] except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail=f'{len(uoms)} units found', body={'uoms': uoms})
def api_purchasing_po_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and filter is required') services = request.services() poStore = services['store.purchasing.po'] pos = [] try: result = poStore.filter(client_id, filter) pos = [{ 'id': r[0], 'created': r[1], 'description': r[2] } for r in result] except Exception as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail='{0} purchase orders found'.format(len(pos)), body={'purchaseOrders': pos})
def view_client_user_roles_add(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None user_id = params['userId'] if 'userId' in params else None role_ids = params['roleIds'] if 'roleIds' in params else None if client_id is None or user_id is None or role_ids is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id, User Id and Role Ids are required' ) services = request.services() try: usersStore = services['store.admin.users'] usersStore.addClientUserRoles(client_id, user_id, role_ids) except Exception as e: raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='Client User Roles added', body={ 'message': 'Client User Roles added' } )
def api_accounting_transactions_filter(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None filter = params['filter'] if 'filter' in params else None if client_id is None or filter is None: raise exception.HTTPBadRequest( detail='Missing required parameters', explanation='Client Id and filter is required') services = request.services() store = services['store.accounting.transactions'] transactions = [] try: result = store.filter(client_id, filter) transactions = [{ 'transaction_id': r[0], 'created': r[1], 'posted': r[2], 'currency_id': r[3], 'description': r[4] } for r in result] except StoreException as e: log.error(e) raise exception.HTTPInternalServerError(detail=str(e), explanation=str(e)) raise exception.HTTPOk(detail=f'{len(transactions)} transaction found', body={'transactions': transactions})
def view_clients_users_all(request): params = request.json_body client_id = params['clientId'] if 'clientId' in params else None if client_id is None: raise exception.HTTPBadRequest( detail='Missing required parameter', explanation='Client Id is required' ) users = [] services = request.services() try: usersStore = services['store.admin.users'] result = usersStore.getAllClientUsers(client_id) users = [{ 'id': r[0], 'active': r[1], 'email': r[2], 'name': r[3] } for r in result] except Exception as e: raise exception.HTTPInternalServerError( detail=str(e), explanation=str(e) ) raise exception.HTTPOk( detail='{0} client users found'.format(len(users)), body={ 'users': users } )
def error_handler(self, exc, request): req = request.cw_request if isinstance(exc, httpexceptions.HTTPException): request.response = exc elif isinstance(exc, PublishException) and exc.status is not None: request.response = httpexceptions.exception_response(exc.status) else: request.response = httpexceptions.HTTPInternalServerError() request.response.cache_control = 'no-cache' vreg = request.registry['cubicweb.registry'] excinfo = sys.exc_info() req.reset_message() if req.ajax_request: content = self.appli.ajax_error_handler(req, exc) else: try: req.data['ex'] = exc req.data['excinfo'] = excinfo errview = vreg['views'].select('error', req) template = self.appli.main_template_id(req) content = vreg['views'].main_template(req, template, view=errview) except Exception: content = vreg['views'].main_template(req, 'error-template') log.exception(exc) request.response.body = content return request.response
def listener_add(self): log = logs.ice_log(__name__, self.request) # Try to find listener by the data from POST listener = self.findListenerByPost() if not listener: raise exc.HTTPUnauthorized() # If there is no access data connected to current listener, raise exception access = self.accessParams(listener) if not access: log.critical( 'There is no access data for listener with id {}'.format( listener.id, True)) raise exc.HTTPInternalServerError() # Check if user has active account if datetime.now().date() > access.expiration_date: raise exc.HTTPForbidden() # Check if user is not already connected if self.countActiveListeners(listener) >= access.max_listeners: raise exc.HTTPForbidden() # Add user to active_listeners table new_listener = models.ActiveListeners( listener_id=listener.id, listener_ip=self.request.remote_addr) self.request.dbsession.add(new_listener) log.info('Listener with id {} connected to icecast'.format( listener.id)) return Response(headerlist=[("listener_accepted", "1")], status_int=200)
def _get_features(params, extended=False): ''' Returns exactly one feature or raises an excpetion ''' featureIds = params.featureIds.split(',') models = models_from_bodid(params.layerId) if models is None: raise exc.HTTPBadRequest('No Vector Table was found for %s' % params.layerId) for featureId in featureIds: # One layer can have several models for model in models: query = params.request.db.query(model) query = query.filter(model.id == featureId) try: feature = query.one() except (NoResultFound, DataError): feature = None except MultipleResultsFound: raise exc.HTTPInternalServerError( 'Multiple features found for the same id %s' % featureId) if feature is not None: vectorModel = model break if feature is None: raise exc.HTTPNotFound('No feature with id %s' % featureId) feature = _process_feature(feature, params) feature = {'feature': feature} yield feature, vectorModel