def settings_colours_add(): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: name = request.json.get('name', None) except: return Response('not_json') if not name: return jsonify({'error': 'Žiadna farba nebola zadaná'}), 400 colour = models.Colour(name=name) try: colour.save() except peewee.IntegrityError: return jsonify({'error': 'Farba už existuje'}), 400 except: return Response('server_error') return jsonify({'id': colour.id}), 200
def get(event, context): """ get key-value or all key-values from dynamodb :param event: :param context: :return: LambdaProxyResponse """ try: params = event['pathParameters'] if params is not None and 'id' in params: item = table.get_item( Key={ keyName: params['id'] }, ) logger.info(item) if 'Item' in item: return Response(hStat.OK, item['Item']).marshal() else: return Response(hStat.NOT_FOUND).marshal() # TODO: handle when >1MB returned. items = table.scan() logger.info(items['Items']) return Response(hStat.OK, items['Items']).marshal() except ClientError as e: error = e.response['Error'] logger.error(error) return Response(hStat.INTERNAL_SERVER_ERROR, error).marshal()
def cats_adopt(uuid): # get current user current_user = get_jwt_identity() try: # if user does not exist in DB, forbidden user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') try: match = models.Cat.get(models.Cat.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') if not match.adoptive or (match.adopted_by and match.adopted_by != user.uuid): return jsonify({'error': 'Mačku nie je možné adoptovať'}), 400 if match.adopted_by == user.uuid: match.adoptive = True match.adopted_by = None else: match.adoptive = False match.adopted_by = user.uuid try: match.save() except: return Response('server_error') return Response('empty')
def settings_breeds_add(): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: name = request.json.get('name', None) except: return Response('not_json') if not name: return jsonify({'error': 'Žiadne plemeno nebolo zadané'}), 400 breed = models.Breed(name=name) try: breed.save() except peewee.IntegrityError: return jsonify({'error': 'Plemeno už existuje'}), 400 except: return Response('server_error') return jsonify({'id': breed.id}), 200
def cats_like(uuid): # get current user current_user = get_jwt_identity() try: # if user does not exist in DB, forbidden user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') try: models.Cat.get(models.Cat.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') try: models.Favourite.get((models.Favourite.user == user.uuid) & (models.Favourite.cat == uuid)) except peewee.DoesNotExist: models.Favourite(user=user.uuid, cat=uuid).save() except: return Response('server_error') return Response('empty')
def auth_get_users(): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') query = models.User.select() response = {} response['count'] = len(query) response['users'] = [] for user in query: response['users'].append({ 'uuid': user.uuid, 'email': user.email, 'firstname': user.firstname, 'lastname': user.lastname, 'activated': True if user.activated else False, 'admin': True if user.admin else False, 'created_at': user.created_at.strftime(Config['date_format']), 'updated_at': user.updated_at.strftime(Config['date_format']) }) return jsonify(response), 200
def put_items_from_body(errors, event): """ puts k-v items from body into dynamodb :param errors: :param event: :param log: :return: LambdaProxyResponse """ if event['body'] is not None: body = json.loads(event['body'], cls=DynamoDBDecoder) with table.batch_writer() as batch: try: for k, v in body.items(): res = batch.put_item(Item={keyName: k, 'Value': v}) logger.info(res) except ClientError as e: error = json.dumps(e.response['Error']) logger.error(error) errors.append(error) except TypeError: raise TypeError(errors) return Response(hStat.OK, {'errors': errors}).marshal() else: return Response(400, {'errors': 'Bad Request'}).marshal()
def settings_health_statuses_add(): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: name = request.json.get('name', None) except: return Response('not_json') if not name: return jsonify({'error': 'Žiadny zdravotný stav nebol zadaný'}), 400 health_status = models.HealthStatus(name=name) try: health_status.save() except peewee.IntegrityError: return jsonify({'error': 'Zdravotný stav už existuje'}), 400 except: return Response('server_error') return jsonify({'id': health_status.id}), 200
def handle_commands(content_lower, message_parts, ev_room, ev_room_name, ev_user_id, ev_user_name, wrap2, content, message_id): message_url = "//chat.{host}/transcript/message/{id}#{id}".format(host=wrap2.host, id=message_id) second_part_lower = "" if len(message_parts) < 2 else message_parts[1].lower() if command_aliases.get(second_part_lower): second_part_lower = command_aliases.get(second_part_lower) match = re.match(r"[!/]*[\w-]+", content_lower) command = match.group(0) if match else "" if re.compile("^:[0-9]{4,}$").search(message_parts[0]): msg_id = int(message_parts[0][1:]) msg = wrap2.get_message(msg_id) msg_content = msg.content_source quiet_action = ("-" in second_part_lower) if str(msg.owner.id) != GlobalVars.smokeDetector_user_id[ev_room] or msg_content is None: return Response(command_status=False, message=None) post_url = fetch_post_url_from_msg_content(msg_content) post_site_id = fetch_post_id_and_site_from_msg_content(msg_content) if post_site_id is not None: post_type = post_site_id[2] else: post_type = None subcommand_parameters = { 'msg_content': msg_content, 'ev_room': ev_room, 'ev_room_name': ev_room_name, 'ev_user_id': ev_user_id, 'ev_user_name': ev_user_name, 'message_url': message_url, 'msg': msg, 'post_site_id': post_site_id, 'post_type': post_type, 'post_url': post_url, 'quiet_action': quiet_action, 'second_part_lower': second_part_lower, 'wrap2': wrap2, } if second_part_lower not in subcmds: return Response(command_status=False, message=None) # Unrecognized subcommand return subcmds[second_part_lower](**subcommand_parameters) # Process additional commands command_parameters = { 'content': content, 'content_lower': content_lower, 'ev_room': ev_room, 'ev_room_name': ev_room_name, 'ev_user_id': ev_user_id, 'ev_user_name': ev_user_name, 'message_parts': message_parts, 'message_url': message_url, 'wrap2': wrap2, } if command not in cmds: return Response(command_status=False, message=None) # Unrecognized command, can be edited later. return cmds[command](**command_parameters)
def auth_activate(seed): try: match = models.Activation.get(models.Activation.seed == Sanitize(seed)) user = models.User.get(models.User.uuid == match.user) user.activated = True user.save() match.delete_instance() except peewee.DoesNotExist: return Response('empty') except: return Response('server_error') return Response('empty')
def auth_delete_user(uuid): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if uuid != user.uuid and not user.admin: return Response('forbidden') try: match = models.User.get(models.User.uuid == uuid) activations = models.Activation.select().where( models.Activation.user == match.uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') match.delete_instance() for a in activations: a.delete_instance() if uuid == user.uuid: blacklist.add(get_raw_jwt()['jti']) try: pictures = models.Picture.select().where(models.Picture.owner == uuid) for picture in pictures: if picture.uuid == Confg['default_picture']: continue try: os.remove(Config['upload_folder'] + str(picture.uuid) + '.' + Config['image_store_format']) picture.delete_instance() except: pass except: pass try: models.Favourite.delete().where( models.Favourite.user == uuid).execute() except: pass try: models.Comment.delete().where(models.Comment.author == uuid).execute() except: pass return Response('empty')
def update_items(errors, event, p_params, q_params): if p_params is not None and q_params is not None and 'id' in p_params and 'value' in q_params: res = table.put_item(Item={keyName: p_params['id'], 'Value': q_params['value']}, ExpressionAttributeValues={':id_val': p_params['id']}, ConditionExpression=f"contains(Id, :id_val)") logger.info(res) return Response(hStat.OK).marshal() elif 'headers' in event and 'Accept' in event['headers'] and event['headers']['Accept'] == 'application/json': return put_items_from_body(errors, event) else: unaccept_content_type = Response(hStat.UNSUPPORTED_MEDIA_TYPE, { "errors": "please use path/query param combo or application/json"}).marshal() logger.error(unaccept_content_type) return unaccept_content_type
def update(event, context): errors = [] try: p_params = event["pathParameters"] q_params = event["queryStringParameters"] return update_items(errors, event, p_params, q_params) except ClientError as e: error = e.response['Error'] logger.error(error) return Response(hStat.INTERNAL_SERVER_ERROR, error).marshal() except TypeError as e: logger.error(e) return Response(hStat.BAD_REQUEST, 'Bad Request').marshal()
def cats_delete(uuid): # get current user current_user = get_jwt_identity() try: # if user does not exist in DB, forbidden user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: match = models.Cat.get(models.Cat.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') try: for p in json.loads(match.pictures): picture = models.Picture.get(models.Picture.uuid == p) try: picture.delete_instance() except: pass try: os.remove(Config['upload_folder'] + str(p) + '.' + Config['image_store_format']) except: pass except: pass try: models.Favourite.delete().where(models.Favourite.cat == uuid).execute() except: pass try: models.Comment.delete().where(models.Comment.cat == uuid).execute() except: pass match.delete_instance() return Response('empty')
def shelterneeds_get(): # get current user current_user = get_jwt_identity() try: # if user does not exist in DB, forbidden user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if user.admin: shelterneeds = models.ShelterNeeds.select() else: shelterneeds = models.ShelterNeeds.select().where( models.ShelterNeeds.hide == False) response = {} response['count'] = len(shelterneeds) response['shelterneeds'] = [] for need in shelterneeds: response['shelterneeds'].append({ "uuid": need.uuid, "category": need.category, "name": need.name, "details": need.details, "hide": True if need.hide else False }) return jsonify(response), 200
def settings_colours_delete(id): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: colour = models.Colour.get(models.Colour.id == id) except: return Response('empty') colour.delete_instance() return Response('empty')
def settings_health_statuses_delete(id): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: health_status = models.HealthStatus.get(models.HealthStatus.id == id) except: return Response('empty') health_status.delete_instance() return Response('empty')
def pictures_get(uuid): current_user = get_jwt_identity() try: models.User.get(models.User.uuid == current_user) except: return Response('forbidden') try: models.Picture.get(models.Picture.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') return send_file(Config['upload_folder'] + uuid + '.' + Config['image_store_format'], mimetype='image/png')
def settings_breeds_delete(id): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: breed = models.Breed.get(models.Breed.id == id) except: return Response('empty') breed.delete_instance() return Response('empty')
def is_authorized(self, request): try: user_id = request.args['userId'] resource_name = request.args['resourceName'] except KeyError: return Response(status=400, response={ "status": 400, "message": "Missing query param 'userId' or 'resourceName'" }) user = User.query.get(user_id) resource = Resource.query.filter(Resource.name == resource_name).first() if user is None or resource is None: return Response(status=400, response={"error": "Invalid 'userId' or 'resourceName'"}) is_authorized = not set(user.groups).isdisjoint(resource.groups) # check if both user and resource has relation with the same group return Response(response={"authorized": is_authorized}, status=200 if is_authorized else 403)
def add(self, request, group_id): Group.query.get_or_404(group_id) try: group_id = int(group_id) data = load_body(request) resources_ids = map(lambda item: item['resourceId'], data) resources = list() for resource_id in resources_ids: resource = Resource.query.get(resource_id) # XXX: if single query is executed each loop then ehance to execute one query using filters if not resource: Resource.query.session.rollback() return Response(status=404, response={ "status": 404, "message": "Resource Not Found, resourceId: %s" % resource_id }) else: resources.append(resource) for resource in resources: if group_id not in resource.groups: resource.groups = resource.groups + [group_id] except KeyError as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=400, response={ "status": 400, "message": "Missing key in body" }) except IntegrityError as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=400, response={ "status": 400, "message": "Resource already exists" }) except Exception as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=500, response={ "status": 500, "message": "Internal Server Error" }) else: db.session.commit() return Response(status=204)
def shelterneeds_add(): # get current user current_user = get_jwt_identity() try: # if user does not exist in DB, forbidden user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not user.admin: return Response('forbidden') try: category = request.json.get('category', None) name = request.json.get('name', None) details = request.json.get('details', None) hide = request.json.get('hide', None) except: return Response('not_json') if not category: return jsonify({"error": "Kategória nebola zadaná"}), 400 if not name: return jsonify({"error": "Názov nebol zadaný"}), 400 if not details: return jsonify({"error": "Detailný popis nebol zadaný"}), 400 if not hide: hide = False shelterneed = models.ShelterNeeds(uuid=uuid.uuid4(), category=Sanitize(category), name=Sanitize(name), details=Sanitize(details), hide=hide) try: shelterneed.save() except: return Response('server_error') return Response('empty')
def _not_found_response(self): """ Возврат ответа, когда вызываемый ресурс не найден """ return Response( 404, DEFAULT_HEADERS, html_render('error_page.html', title='404 page', main_text='404 error', ext_text=f'Ресурс "{self.uri}" не найден'))
def _method_not_allowed_response(self): """ Возврат ответа, когда вызываемый метод не поддерживается для ресурса """ return Response( 405, DEFAULT_HEADERS, html_render('error_page.html', title='405 page', main_text='405 error', ext_text=f'Метод "{self.req_method}" недоступен ' f'для ресурса "{self.uri}"'))
def pictures_add(): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if not 'image/' in request.headers.get('Content-type'): return Response('invalid_format') image = ConvertImage(request.get_data(), Config['picture_width'], Config['picture_height']) if not image: return Response('invalid_image') try: picture = models.Picture(uuid=uuid.uuid4(), owner=user.uuid) picture.save() except: return Response('server_error') fullpath = Config['upload_folder'] + \ str(picture.uuid) + '.' + Config['image_store_format'] if not os.path.exists(Config['upload_folder']): if Config['debug']: print('Debug: Creating leading directories for: %s' % Config['upload_folder']) os.makedirs(Config['upload_folder']) try: if Config['debug']: print('Debug: Storing image into: %s' % fullpath) with open(fullpath, 'wb+') as f: f.write(image.getbuffer()) f.close() except: return Response('server_error') return jsonify({'uuid': picture.uuid}), 200
def auth_login(): if not request.is_json: return Response('not_json') try: email = request.json.get('email', None) password = request.json.get('password', None) except: return Response('not_json') if not email: return jsonify({'error': 'E-mailová adresa nebola zadaná'}), 400 if not password: return jsonify({'error': 'Heslo nebolo zadané'}), 400 if not isinstance(email, str) or not isinstance(password, str): return Response('invalid_format') # Try to get user by provided email try: match = models.User.get(models.User.email == Sanitize(email)) except peewee.DoesNotExist: return jsonify({'error': 'Používateľ neexistuje'}), 400 except: return Response('server_error') if not match.activated: return jsonify({'error': 'Účet nie je aktivovaný'}), 400 # Compare password hashes salt = bytes.fromhex(match.password[:(Config['hash_salt_length'] * 2)]) if match.password == MakeHash(Sanitize(password), salt): token = create_access_token(identity=match.uuid) return jsonify({ 'token': token, 'token_type': app.config['JWT_HEADER_TYPE'], 'expires': Config['jwt_expires'], 'uuid': match.uuid, }) else: return jsonify({'error': 'Nesprávne heslo'}), 400
def create(event, context): """ create function is used for creating new and overriding old key-value items :param event: :param context: :return: LambdaProxyResponse """ errors = [] try: if 'headers' in event and 'Accept' in event['headers'] and event['headers']['Accept'] == 'application/json': return put_items_from_body(errors, event) else: return Response(hStat.UNSUPPORTED_MEDIA_TYPE).marshal() except ClientError as e: error = e.response['Error'] logger.error(error) return Response(hStat.INTERNAL_SERVER_ERROR, error).marshal() except TypeError as e: logger.error(e) return Response(hStat.BAD_REQUEST, 'Bad Request').marshal()
def pictures_delete(uuid): current_user = get_jwt_identity() try: user = models.User.get(models.User.uuid == current_user) except: return Response('forbidden') if uuid == Config['default_picture']: return Response('empty') try: picture = models.Picture.get(models.Picture.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') if not user.admin and not picture.owner == user.uuid: return Response('forbidden') fullpath = Config['upload_folder'] + \ str(picture.uuid) + '.' + Config['image_store_format'] if os.path.exists(fullpath): os.remove(fullpath) picture.delete_instance() return Response('empty')
def cats_get(uuid): current_user = get_jwt_identity() try: models.User.get(models.User.uuid == current_user) except: return Response('forbidden') try: cat = models.Cat.get(models.Cat.uuid == uuid) except peewee.DoesNotExist: return Response('invalid') except: return Response('server_error') comments = 0 try: comments = len( models.Comment.select().where(models.Comment.cat == cat.uuid)) except: pass return jsonify({ "uuid": cat.uuid, "name": cat.name, "age": cat.age, "sex": True if cat.sex else False, "breed": cat.breed, "health_status": cat.health_status, "castrated": True if cat.castrated else False, "vaccinated": True if cat.vaccinated else False, "dewormed": True if cat.dewormed else False, "colour": cat.colour, "description": cat.description, "health_log": cat.health_log, "adoptive": True if cat.adoptive else False, "pictures": json.loads(cat.pictures), "comments": comments, "created_at": cat.created_at.strftime(Config['date_format']), "updated_at": cat.updated_at.strftime(Config['date_format']) }), 200
def add(self, request, group_id): try: group_id = int(group_id) data = load_body(request) users_ids = map(lambda item: item['userId'], data) users = list() for user_id in users_ids: user = User.query.get(user_id) # XXX: if single query is executed each loop then ehance to execute one query using filters if not user: user = User(id=user_id, groups=[group_id]) db.session.add(user) else: users.append(user) for user in users: if group_id not in user.groups: user.groups = user.groups + [group_id] except KeyError as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=400, response={ "status": 400, "message": "Missing key in body" }) except IntegrityError as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=400, response={ "status": 400, "message": "Resource already exists" }) except Exception as err: print("Error: %s\nStacktrace: %s" % (err, traceback.format_exc())) db.session.rollback() return Response(status=500, response={ "status": 500, "message": "Internal Server Error" }) else: db.session.commit() return Response(status=204)