def get_exceptions(result: object): """ Catch and return errors from a request result. :param result: A requests session result. :return: A jsend formatted result with either success or failure. :rtype: dict """ logger.debug('Examining result for exceptions.') # Determine if they gave us JSON, if not set the data to nothing. try: r_json = {'results': result.json()} except JSONDecodeError: logger.debug('Results are not JSON.') r_json = {'results': []} try: result.raise_for_status() except HTTPError: logger.debug('HTTP Error Code: %s detected', result.status_code) return jsend.fail(r_json) # 204 is essentially an error, so we catch it. if result.status_code == 204: return jsend.fail(r_json) else: return jsend.success(r_json)
def on_post(self, req, resp): """ Implement POST """ request_body = req.bounded_stream.read() json_params = json.loads(request_body) data = json_params["submission"] if data and data["data"] and data["data"]["notifyMeByTextMessage"]: _from_number = os.environ.get('TWILIO_FROM') _to_number = data["data"]["phoneNumber"] _message = self.get_sms(data) # Update .env with Live Credentials to send actual sms account_sid = os.environ.get('TWILIO_SID') auth_token = os.environ.get('TWILIO_TOKEN') client = Client(account_sid, auth_token) message = client.messages.create( to=_to_number, from_=_from_number, #test From number from twilio body=_message) if message.sid: resp.status = falcon.HTTP_200 resp.body = json.dumps(jsend.success({'message': 'SMS sent!'})) else: resp.status = falcon.HTTP_400 resp.body = json.dumps( jsend.fail({'message': 'Failed to send SMS'}))
def collect(self, cert_id, format_type): """ Poll for certificate availability after submission. :param int cert_id: The certificate ID :param str format_type: The format type to use (example: 'X509 PEM Certificate only') :return: The certificate_id or the certificate depending on whether the certificate is ready (check status code) :rtype: dict """ result = self.client.service.collect( authData=self.auth, id=cert_id, formatType=ComodoCA.format_type[format_type]) # The certificate is ready for collection if result.statusCode == 2: return jsend.success({ 'certificate': result.SSL.certificate, 'certificate_status': 'issued', 'certificate_id': cert_id }) # The certificate is not ready for collection yet elif result.statusCode == 0: return jsend.fail({ 'certificate_id': cert_id, 'certificate': '', 'certificate_status': 'pending' }) # Some error occurred else: return self._create_error(result.statusCode)
def to_dict(self): ''' Transforms this exception to a dict ''' if self.status_code >= 400 and self.status_code < 500: result = dict( jsend.fail({ 'message': self.message, 'payload': self.payload })) elif self.status_code >= 500: result = dict( jsend.error(self.message, self.status_code, self.payload)) return result
def get_cert_types(self): """ Collect the certificate types that are available to the customer. :return: A list of dictionaries of certificate types :rtype: list """ url = self._create_url('types') result = self._get(url) if result.status_code == 200: return jsend.success({'types': result.json()}) else: return jsend.fail(result.json())
def run(self, req): """on get request return Welcome message """ jdata = jsend.error('ERROR') if 'id' in req.params: data = self.process(req.params['id']) if isinstance(data, list): jdata = jsend.success({'locations': self.etl(data)}) elif isinstance(data, str): jdata = jsend.error(data) elif isinstance(data, dict): jdata = jsend.fail(data) return jdata
def collect(self, cert_id, format_type): """ Collect a certificate. :param int cert_id: The certificate ID :param str format_type: The format type to use: Allowed values: 'x509' - for X509, Base64 encoded, 'x509CO' - for X509 Certificate only, Base64 encoded, 'x509IO' - for X509 Intermediates/root only, Base64 encoded, 'base64' - for PKCS#7 Base64 encoded, 'bin' - for PKCS#7 Bin encoded, 'x509IOR' - for X509 Intermediates/root only Reverse, Base64 encoded :return: The certificate_id or the certificate depending on whether the certificate is ready (check status code) :rtype: dict """ url = self._create_url('collect/{}/{}'.format(cert_id, format_type)) logger.debug('Collecting certificate at URL: %s' % url) result = self._get(url) logger.debug('Collection result code: %s' % result.status_code) # The certificate is ready for collection if result.status_code == 200: return jsend.success({ 'certificate': result.content.decode(result.encoding), 'certificate_status': 'issued', 'certificate_id': cert_id }) # The certificate is not ready for collection yet elif result.status_code == 400 and result.json()['code'] == 0: return jsend.fail({ 'certificate_id': cert_id, 'certificate': '', 'certificate_status': 'pending' }) # Some error occurred else: return jsend.fail(result.json())
def renew(self, cert_id): """ Renew a certificate by ID. :param int cert_id: The certificate ID :return: The result of the operation, 'Successful' on success :rtype: dict """ url = self._create_url('renewById/{}'.format(cert_id)) result = self.session.post(url, json='') if result.status_code == 200: return jsend.success({'certificate_id': result.json()['sslId']}) else: return jsend.fail(result.json())
def create_user(): username = request.json['username'] email = request.json['email'] password = request.json['password'] username_taken = User.query.filter_by(username=username).first() email_taken = User.query.filter_by(email=email).first() fail_data = {} if username_taken: fail_data.update({'username': '******'}) if email_taken: fail_data.update({'email': 'Email already taken.'}) if fail_data: return jsend.fail(fail_data) new_user = User(username, email, password) db.session.add(new_user) db.session.commit() user = User.query.filter_by(username=username).first() return jsend.success(user.serialize)
def test_fail_data_must_be_dict(self): try: jsend.fail(data=1) except ValueError: return self.fail()
def test_fail(self): ret = jsend.fail(data={'key': 'value'}) self.assertTrue(jsend.is_fail(ret)) self.assertEqual(ret['data']['key'], 'value')
def create_failed_response(error_message, status_code=400, headers=None): if headers: return jsend.fail({"error": error_message}), status_code, headers else: return jsend.fail({"error": error_message}), status_code
def test_fail(self): jsend_obj = jsend.fail(data={'key': 'value'}) self.assertTrue(jsend_obj.is_fail) self.assertEqual(jsend_obj.data['key'], 'value')
def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): email = request.data.get('email') password = request.data.get('password') if email and password != "": if self.queryset.filter(email=email).exists(): user = self.queryset.get(email=email) is_password = check_password(password, user.password) if is_password: authenticate(self, request, email=user.email, password=user.password) if user.is_active: login(request, user) payload = { "id": user.id, "email": user.email, "exp": datetime.datetime.utcnow() + timedelta(seconds=604800) } return Response( jsend.success({ "token": jwt.encode(payload, settings.SECRET_KEY), "user": serializer.data, "user_id": user.id }), status=status.HTTP_201_CREATED, ) else: return Response( (jsend.error("Account is inactive")), status=status.HTTP_403_FORBIDDEN, ) else: return Response( (jsend.error("'password' : ['Incorrect password']") ), status=status.HTTP_401_UNAUTHORIZED, ) else: return Response( (jsend.error("email or password does not match")), status=status.HTTP_401_UNAUTHORIZED, ) else: return Response( (jsend.fail({ "email": ["Email is required"], "password": ["Password is required"], })), status=status.HTTP_400_BAD_REQUEST, )
def add_host(building: str, department: str, contact: str, phone: str, name: str, session: object, url: str, comment: str = None, ip: str = None, site_name: str = "UCB", subnet: str = None): """ Add a host to DDI. :param str building: The UCB building the host is located in. :param str contact: The UCB contact person for the host. :param str department: The UCB department the host is affiliated with. :param str phone: The phone number associated with the host. :param str name: The FQDN for the host, must be unique. :param object session: The requests session object. :param str url: The URL of the DDI server. :param str comment: An optional comment. :param str ip: The optional IP address to give to the host, either ip or subnet must be defined. :param str site_name: The site name to use, defaults to UCB. :param str subnet: The optional subnet to use (e.g. 172.23.23.0) either ip or subnet must be defined. :return: The JSON result of the operation. :rtype: str """ ip_class_parameters = { 'hostname': name.split('.')[0], 'ucb_buildings': building, 'ucb_dept_aff': department, 'ucb_ph_no': phone, 'ucb_resp_per': contact } # Add the comment if it was passed in if comment: ip_class_parameters['ucb_comment'] = comment ip_class_parameters = urllib.parse.urlencode(ip_class_parameters) # If an IP is specified that is more specific than a subnet, if neither # we fail. if ip: logger.debug('IP address: %s specified for host addition.', ip) ip = ip elif subnet: logger.debug('Subnet: %s specified, automatic IP discover started.', subnet) r = get_free_ipv4(subnet, session, url) if jsend.success(r): # Get the first free IP address offered. ip = r['data']['results'][0]['hostaddr'] logger.debug('IP: %s, automatically obtained.', ip) else: return r else: return jsend.fail({}) payload = { 'hostaddr': ip, 'name': name, 'site_name': site_name, 'ip_class_parameters': ip_class_parameters } logger.debug( 'Add operation invoked on Host: %s with IP: %s, Building: %s, ' 'Department: %s, Contact: %s Phone: %s, and Payload: %s', name, ip, building, department, contact, phone, payload) r = session.post(url + 'rest/ip_add', json=payload) result = get_exceptions(r) return result
def on_post(self, req, resp): """handle the post request""" """check for required fields""" if not all(x in req.params.keys() for x in ['dbi_no', 'block', 'lot']): resp.body = json.dumps( jsend.error("dbi_no, block, and lot are required")) resp.status = falcon.HTTP_400 return """check dbi_no is in correct format""" """YYYYMMDDNNNN""" is_valid_dbi_no = False dbi_no = req.params.get('dbi_no') if len(dbi_no) == 12 and re.match(r'\d+$', dbi_no) is not None: is_valid_dbi_no = True # The following lines of code are commented out in order to enable fake dbi_no. # Keeping the code around in case fake dbi_no are no longer necessary. # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # date_part = dbi_no[:8] # try: # datetime.datetime.strptime(date_part, '%Y%m%d') # is_valid_dbi_no = True # except: # pass # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if not is_valid_dbi_no: resp.body = json.dumps(jsend.error("invalid dbi_no")) resp.status = falcon.HTTP_400 return """job_size is integer""" if req.params.get('job_size', False): try: int(req.params.get('job_size').replace(',', '')) except: resp.body = json.dumps( jsend.error("job_size should be an integer")) resp.status = falcon.HTTP_400 return """dbi_date in YYYY/MM/DD format""" if req.params.get('dbi_date', False): try: datetime.datetime.strptime(req.params.get('dbi_date'), '%Y/%m/%d') except: resp.body = json.dumps( jsend.error("dbi_date should be in YYYY/MM/DD format")) resp.status = falcon.HTTP_400 return api_params = {'revision': None} api_params.update(req.params) response = FireRequest.post(api_params) if response and response.status_code == 200: return_id = response.headers.get('id', False) payload = {'message': response.headers.get('result_message')} if return_id: # response returned an id payload['id'] = return_id resp.body = json.dumps(jsend.success(payload)) resp.status = falcon.HTTP_200 else: # no id means something went wrong resp.body = json.dumps(jsend.fail(payload)) resp.status = falcon.HTTP_500 else: resp.body = json.dumps(jsend.error(Records.ERROR_MSG)) resp.status = str( response.status_code) + " " + responses[response.status_code]
def on_post(self, req, resp): """ Implement POST """ request_body = req.bounded_stream.read() json_params = json.loads(request_body) message = json_params.get('message', '') slack_channel = json_params.get('channel', os.environ.get('SLACK_CHANNEL')) #blocks = json_params.get('blocks', None) blocks = None slack_token = json_params.get('SLACK_API_TOKEN', os.environ.get('SLACK_API_TOKEN')) if slack_token and slack_channel: response = self.post_message_to_slack(message, slack_token, slack_channel, blocks) if response["ok"]: print("Message sent to {}".format(slack_channel)) resp.status = falcon.HTTP_200 resp.body = json.dumps( jsend.success( {'message': 'Slack message sent to ' + slack_channel})) else: print("Message failed to sent, error {}".format( response["error"])) resp.status = falcon.HTTP_400 resp.body = json.dumps( jsend.fail({ 'message': 'Failed to send Slack message, error: ' + response["error"] })) #post a file file_path = json_params.get('file_path', '') if file_path != '': response = urllib.request.urlopen(file_path) data = response.read() file_upload_text = json_params.get('file_upload_text', 'file upload') file_name = json_params.get('file_name', '_file_name') posted_file = self.post_file_to_slack(file_upload_text, slack_token, slack_channel, file_name, data) if posted_file["ok"]: print("File uploaded to {}".format(slack_channel)) resp.status = falcon.HTTP_200 resp.body = json.dumps( jsend.success( {'message': 'File posted to ' + slack_channel})) else: print("File failed to upload, error: {}".format( posted_file["error"])) resp.status = falcon.HTTP_400 resp.body = json.dumps( jsend.fail({ 'message': 'Failed to post file, error: ' + posted_file['error'] }))