예제 #1
0
    def post(self):
        required_fields = ["id", "latitude", "longitude"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        try:
            new = Sighting(bugid=json_data["id"],
                           latitude=json_data["latitude"],
                           longitude=json_data["longitude"])

            session.add(new)
            session.commit()
            return jsonify({"success": 1})
        except:
            return jsonify({
                "success": -1,
                "error": "Error adding new user to db"
            })
예제 #2
0
    def post(self):
        required_fields = ["id", "image"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        try:
            new = Picture(bugid=json_data["id"], num_flags=0, picture_link="")
            session.add(new)
            session.commit()

            #TODO: update extension
            image_data = base64.b64decode(json_data["image"])
            if b"php" in image_data or b"<?" in image_data:
                raise Exception("Invalid upload")
            with open("/var/www/html/images/{}.jpg".format(new.id), "wb") as f:
                f.write(image_data)
            new.picture_link = "https://poosgroup5-u.cf/images/{}.jpg".format(
                new.id)
            session.commit()
            return jsonify({"success": 1})
        except Exception as e:
            return jsonify({
                "success": -1,
                "error": "Error adding image to database: " + str(e)
            })
예제 #3
0
    def post(self):
        required_fields = ["id"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        try:
            q = session.query(Sighting).filter_by(bugid=json_data["id"]).all()
            sightings = [{
                "latitude": s.latitude,
                "longitude": s.longitude
            } for s in q]
            return jsonify({"success": 1, "sightings": sightings})
        except Exception as e:
            return jsonify({
                "success": -1,
                "error": "Error getting sightings: " + str(e)
            })
예제 #4
0
    def post(self):
        required_fields = ["username", "password", "isAdmin"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        if session.query(User).filter_by(
                username=json_data["username"]).first():
            return jsonify({"success": -1, "error": "User already registered"})
        # hash password
        ph = PasswordHasher()
        hash = ph.hash(json_data["password"])

        try:
            new_user = User(username=json_data["username"],
                            password=hash,
                            admin=json_data["isAdmin"])

            session.add(new_user)
            session.commit()
            return jsonify({"success": 1})
        except:
            return jsonify({
                "success": -1,
                "error": "Error adding new user to db"
            })
예제 #5
0
    def post(self):
        required_fields = ["id"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        try:
            q = session.query(Picture).filter_by(bugid=json_data["id"]).all()
            pictures = [{
                "url": s.picture_link,
                "imageId": s.id
            } for s in q if s.picture_link]
            return jsonify({"success": 1, "images": pictures})
        except Exception as e:
            return jsonify({
                "success": -1,
                "error": "Error getting images: " + str(e)
            })
예제 #6
0
    def post(self):
        required_fields = ["imageId"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        try:
            q = session.query(Picture).filter_by(
                id=json_data["imageId"]).first()
            q.num_flags += 1
            if q.num_flags >= 5:
                session.delete(q)
            session.commit()
            return jsonify({"success": 1})
        except Exception as e:
            return jsonify({
                "success": -1,
                "error": "Error flagging image: " + str(e)
            })
예제 #7
0
    def get(self):
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        try:
            q = session.query(Submission).all()
            submissions = [{"submission_id": s.id, "bug_id_old": s.bug_id_old, "bug_id_new": s.bug_id_new} for s in q]
            return jsonify({"success": 1, "submissions": submissions})
        except Exception as e:
            return jsonify({"success": -1,
                            "error": "Error getting sightings: " + str(e)})
예제 #8
0
    def wrapper(*args, **kwargs):
        if not request.headers.get('X-Auth-Token'):
            abort(401, message="X-Auth-Token header not provided")
        token = request.headers.get('X-Auth-Token')

        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        if not session.query(Session).filter_by(session_id=token).first():
            abort(401, message="Invalid token")
        # TODO: Validate session based on time maybe
        return func(*args, **kwargs)
예제 #9
0
    def wrapper(*args, **kwargs):
        if not request.headers.get('X-Auth-Token'):
            abort(401, message="X-Auth-Token header not provided")
        token = request.headers.get('X-Auth-Token')

        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        if not session.query(Session).filter_by(session_id=token).first():
            abort(401, message="Invalid token")

        if not session.query(Session).filter_by(
                session_id=token).first().user.admin:
            abort(401, message="This resource is for admins only")

        return func(*args, **kwargs)
예제 #10
0
    def post(self):

        required_fields = ["id", "approve"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({"success": -1,
                                "error": "Missing {} field".format(field)})
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        try:
            q = session.query(Submission).filter_by(id=json_data["id"]).first()
            if json_data["approve"]:
                bug_old = session.query(Bug).filter_by(id=q.bug_id_old).first()
                bug_new = session.query(Bug).filter_by(id=q.bug_id_new).first()
                bug_old.common_name = bug_new.common_name
                bug_old.scientific_name = bug_new.scientific_name
                bug_old.class_id = bug_new.class_id
                bug_old.order_id = bug_new.order_id
                bug_old.family_id = bug_new.family_id
                bug_old.genus_id = bug_new.genus_id
                bug_old.color_id_1= bug_new.color_id_1
                bug_old.color_id_2= bug_new.color_id_2
                bug_old.general_type_id = bug_new.general_type_id
                bug_old.mouth_parts_id = bug_new.mouth_parts_id
                bug_old.wings = bug_new.wings
                bug_old.antenna = bug_new.antenna
                bug_old.hind_legs_jump = bug_new.hind_legs_jump
                bug_old.hairy_furry = bug_new.hairy_furry
                bug_old.thin_body = bug_new.thin_body
                bug_old.description = bug_new.description
                bug_old.additional_advice = bug_new.additional_advice
                session.delete(q)
                session.commit()
            else:
                session.delete(q)
                session.commit()
            return jsonify({"success": 1, })
        except Exception as e:
            return jsonify({"success": -1,
                            "error": "Error getting sightings: " + str(e)})
예제 #11
0
    def post(self):
        required_fields = ["username", "password"]
        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({
                    "success": -1,
                    "error": "Missing {} field".format(field)
                })
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # check to see if username is taken
        user = session.query(User).filter_by(
            username=json_data["username"]).first()
        if not user:
            return jsonify({"success": -1, "error": "User does not exist"})

        try:
            # verify hash
            hash = user.password
            ph = PasswordHasher()
            ph.verify(hash, json_data["password"])

            # create session
            sessID = ''.join([
                random.choice(string.ascii_letters + string.digits)
                for n in range(32)
            ])
            new_session = Session(user_id=user.id,
                                  session_id=sessID,
                                  api_key="",
                                  session_time=datetime.datetime.now(),
                                  is_api=False)
            session.add(new_session)
            session.commit()
            return jsonify({"success": 1, "sessionID": sessID})
        except exceptions.VerifyMismatchError:
            return jsonify({
                "success": -1,
                "error": "Incorrect password provided"
            })
예제 #12
0
    def post(self):
        
        # Define required fields
        required_fields = ["common_name", "scientific_name", "class",
        "order", "family", "genus", "color_1", "color_2", "general_type", 
        "mouth_parts", "wings", "antenna", "hind_legs_jump", "hairy_furry",
        "thin_body", "description", "additional_advice"]
        
        # Get JSON data from request
        # If any required field is missing, the missing field will be sent back in a JSON response
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({"success": -1,
                                "error": "Missing {} field".format(field)})

        # Create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # Check to see if bug entry exists
        if session.query(Bug).filter_by(common_name=json_data["common_name"]).first():
            return jsonify({"success": -1,
                            "error": "Bug already registered"})

        # If there isn't a bug entry, make a new bug from the JSON data
        # and attempt to make a request to the database to add it
        try:
            _class = session.query(Class).filter_by(name=json_data["class"]).first()
            if not _class:
                new_class = Class(name=json_data["class"])
                session.add(new_class)
                session.commit()
                _class = new_class

            order = session.query(Order).filter_by(name=json_data["order"]).first()
            if not order:
                new_order = Order(name=json_data["order"])
                session.add(new_order)
                session.commit()
                order = new_order

            family = session.query(Family).filter_by(name=json_data["family"]).first()
            if not family:
                new_family = Family(name=json_data["family"])
                session.add(new_family)
                session.commit()
                family = new_family

            genus = session.query(Genus).filter_by(name=json_data["genus"]).first()
            if not genus:
                new_genus = Genus(name=json_data["genus"])
                session.add(new_genus)
                session.commit()
                genus = new_genus

            color1 = session.query(Color).filter_by(color=json_data["color_1"]).first()
            if not color1:
                new_color1 = Color(color=json_data["color_1"])
                session.add(new_color1)
                session.commit()
                color1 = new_color1

            color2 = session.query(Color).filter_by(color=json_data["color_2"]).first()
            if not color2:
                new_color2 = Color(color=json_data["color_2"])
                session.add(new_color2)
                session.commit()
                color2 = new_color2

            general_type = session.query(General_Type).filter_by(name=json_data["general_type"]).first()
            if not general_type:
                new_general_type = General_Type(name=json_data["general_type"])
                session.add(new_general_type)
                session.commit()
                general_type = new_general_type

            mouth_parts = session.query(Mouth_Parts).filter_by(name=json_data["mouth_parts"]).first()
            if not mouth_parts:
                new_mouth_parts = Mouth_Parts(name=json_data["mouth_parts"])
                session.add(new_mouth_parts)
                session.commit()
                mouth_parts = new_mouth_parts



            new_bug = Bug(common_name=json_data["common_name"],
                          scientific_name=json_data["scientific_name"],
                          class_id=_class.id,
                          order_id=order.id,
                          family_id=family.id,
                          genus_id=genus.id,
                          color_id_1=color1.id,
                          color_id_2=color2.id,
                          general_type_id=general_type.id,
                          mouth_parts_id=mouth_parts.id,
                          wings=json_data["wings"],
                          antenna=json_data["antenna"],
                          hind_legs_jump=json_data["hind_legs_jump"],
                          hairy_furry=json_data["hairy_furry"],
                          thin_body=json_data["thin_body"],
                          description=json_data["description"],
                          additional_advice=json_data["additional_advice"],
                          approved=True)
            session.add(new_bug)
            session.commit()

            # If successful, return 1, if not return -1 and error status
            return jsonify({"success": 1})
        except Exception as e:
            return jsonify({"success": -1, 
                            "error": str(e)})
예제 #13
0
    def post(self):
        
        required_fields = ["id"]

        # Get JSON data from request
        json_data = request.get_json(force=True)
        for field in required_fields:
            if field not in json_data.keys():
                return jsonify({"success": -1,
                                "error": "Missing {} field".format(field)})

        # Create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])

        # Check to see if bug entry exists via id, if so, go on, if not,
        # post error
        try:
            bug = session.query(Bug).filter_by(id=json_data["id"]).first()
            if not bug:
                return jsonify({"success": -1,
                                "error": "Bug does not exist."})

            common_name = bug.common_name
            scientific_name = bug.scientific_name
            _class = bug._class.name
            order = bug.order.name
            family = bug.family.name
            genus = bug.genus.name
            color_1 = bug.color1.color
            color_2 = bug.color2.color
            general_type = bug.general_type.name
            mouth_parts = bug.mouth_parts.name
            wings = bug.wings
            antenna = bug.antenna
            hind_legs_jump = bug.hind_legs_jump
            hairy_furry = bug.hairy_furry
            thin_body = bug.thin_body
            description = bug.description
            additional_advice = bug.additional_advice  
            pictures = [{"url": s.picture_link, "imageId": s.id} for s in bug.pictures if s.picture_link]
            if not pictures:
                pictures = [{"url": "https://i.imgur.com/DhEi3hk.png", "imageaId": 0}]
            sightings = [{"latitude": s.latitude, "longitude": s.longitude} for s in bug.sightings]

            return jsonify({"success": 1,
                            "common_name": common_name,
                            "description": description,
                            "additional_advice": additional_advice,
                            "characteristics":{
                            "scientific_name": scientific_name,
                            "class": _class,
                            "order": order,
                            "family": family,
                            "genus": genus,
                            "color1": color_1,
                            "color2": color_2,
                            "general_type": general_type,
                            "mouth_parts": mouth_parts,
                            "wings": wings,
                            "antenna": antenna,
                            "hind_legs_jump": hind_legs_jump,
                            "hairy_furry": hairy_furry,
                            "thin_body": thin_body},
                            "sightings": sightings,
                            "pictures": pictures
                            }) 
                                       
        except Exception as e:
            return jsonify({"success": -1,
                            "error": "Error getting bug: " + str(e)})
예제 #14
0
 def get(self):
     session = getSession(app.config["DB_USER"], app.config["DB_PASS"])
     testPass = session.query(User).filter_by(
         username="******").first().password
     return jsonify({"Test Users Password": testPass})
예제 #15
0
    def post(self):
        # Get JSON data from request
        json_data = request.get_json(force=True)
        # create database session
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])
        try:
            q = session.query(Bug).filter_by(approved=True)

            # Filter on common name
            if "Common Name" in json_data.keys():
                q = q.filter(
                    Bug.common_name.like('%' + json_data["Common Name"] + '%'))
            if "Scientific Name" in json_data.keys():
                q = q.filter(
                    Bug.scientific_name.like('%' +
                                             json_data["Scientific Name"] +
                                             '%'))
            if "Class" in json_data.keys():
                q = q.filter(Bug._class.has(name=json_data["Class"]))
            if "Order" in json_data.keys():
                q = q.filter(Bug.order.has(name=json_data["Order"]))
            if "Family" in json_data.keys():
                q = q.filter(Bug.family.has(name=json_data["Family"]))
            if "Genus" in json_data.keys():
                q = q.filter(Bug.genus.has(name=json_data["Genus"]))
            if "General Type" in json_data.keys():
                q = q.filter(
                    Bug.general_type.has(name=json_data["General Type"]))
            if "Mouth Parts" in json_data.keys():
                q = q.filter(
                    Bug.mouth_parts.has(name=json_data["Mouth Parts"]))
            if "Colors" in json_data.keys():
                # don't ask
                if isinstance(json_data["Colors"], str):
                    json_data["Colors"] = [json_data["Colors"]]
                q = q.filter(
                    or_(
                        x.has(color=c) for c in json_data["Colors"]
                        for x in [Bug.color1, Bug.color2]))
            if "Has wings" in json_data.keys():
                if json_data["Has wings"] == "Yes":
                    q = q.filter_by(wings=True)
                elif json_data["Has wings"] == "No":
                    q = q.filter_by(wings=False)
            if "Has antenna" in json_data.keys():
                if json_data["Has antenna"] == "Yes":
                    q = q.filter_by(antenna=True)
                elif json_data["Has antenna"] == "No":
                    q = q.filter_by(antenna=False)
            if "Has hind legs for jumping" in json_data.keys():
                if json_data["Has hind legs for jumping"] == "Yes":
                    q = q.filter_by(hind_legs_jump=True)
                elif json_data["Has hind legs for jumping"] == "No":
                    q = q.filter_by(hind_legs_jump=False)
            if "Has hair" in json_data.keys():
                if json_data["Has hair"] == "Yes":
                    q = q.filter_by(hairy_furry=True)
                elif json_data["Has hair"] == "No":
                    q = q.filter_by(hairy_furry=False)
            if "Has thin body" in json_data.keys():
                if json_data["Has thin body"] == "Yes":
                    q = q.filter_by(thin_body=True)
                elif json_data["Has thin body"] == "No":
                    q = q.filter_by(thin_body=False)

            bugs = [bug.as_dict() for bug in q.all()]

            return jsonify({"success": 1, "results": bugs})

        except Exception as e:
            return jsonify({"success": -1, "error": str(e)})
예제 #16
0
    def get(self):
        session = getSession(app.config["DB_USER"], app.config["DB_PASS"])
        fields = []
        try:
            # Add Common Name
            common_name = {"label": "Common Name", "type": "TEXT"}
            fields.append(common_name)

            # Add Scientific name
            scientific_name = {"label": "Scientific Name", "type": "TEXT"}
            fields.append(scientific_name)

            # Add Class
            c = {"label": "Class", "type": "DROP"}
            c['options'] = sorted(
                [cl.name for cl in session.query(Class).all()])
            fields.append(c)

            # Add Order
            o = {"label": "Order", "type": "DROP"}
            o['options'] = sorted(
                [order.name for order in session.query(Order).all()])
            fields.append(o)

            # Add Familt
            f = {"label": "Family", "type": "DROP"}
            f['options'] = sorted(
                [fa.name for fa in session.query(Family).all()])
            fields.append(f)

            # Add Genus
            g = {"label": "Genus", "type": "DROP"}
            g['options'] = sorted(
                [ge.name for ge in session.query(Genus).all()])
            fields.append(g)

            # Add general type
            gt = {"label": "General Type", "type": "DROP"}
            gt['options'] = sorted(
                [gty.name for gty in session.query(General_Type).all()])
            fields.append(gt)

            # Add mouth parts
            m = {"label": "Mouth Parts", "type": "DROP"}
            m['options'] = sorted(
                [mp.name for mp in session.query(Mouth_Parts).all()])
            fields.append(m)

            # Add color
            colors = {"label": "Colors", "type": "CHECK"}
            colors['options'] = sorted(
                [co.color for co in session.query(Color).all()])
            fields.append(colors)

            # Add wings
            wings = {"label": "Has wings", "type": "DROP"}
            wings['options'] = ["Yes", "No"]
            fields.append(wings)

            # Add antenna
            antenna = {"label": "Has antenna", "type": "DROP"}
            antenna['options'] = ["Yes", "No"]
            fields.append(antenna)

            # Add hing legs jump
            hl = {"label": "Has hind legs for jumping", "type": "DROP"}
            hl['options'] = ["Yes", "No"]
            fields.append(hl)

            # Add hing hair
            hair = {"label": "Has hair", "type": "DROP"}
            hair['options'] = ["Yes", "No"]
            fields.append(hair)

            # Add hing thin body
            thin = {"label": "Has thin body", "type": "DROP"}
            thin['options'] = ["Yes", "No"]
            fields.append(thin)

            return jsonify({"success": 1, "fields": fields})
        except Exception as e:
            return jsonify({"success": -1, "error": str(e)})