Ejemplo n.º 1
0
def get_resources(user):
    resource_type_as_string = request.json["type"]

    try:
        resource_type = ResourceType(resource_type_as_string)

        project = User(user).get_active_project()
        resources = project.get_resources(resource_type)

        results = []
        for resource in resources:
            results.append(Resources.get(resource, resource_type).to_JSON())

        return jsonify(results)

    except ValueError:
        raise ResourceTypeException()

    except ResourceTypeException:
        return jsonify({"error_message": "Received an unknown type of resource"}), 400

    except Exception as e:
        print(f"Error getting resource list {e}")
        tb1 = traceback.TracebackException.from_exception(e)
        print("".join(tb1.format()))
        return jsonify({"error_message": "Error getting resources"}), 400
    def setUp(self):
        self.user_id_1 = user_dao.save_user(
            User("user1", "password", "nickname", "avatar_url",
                 datetime(1998, 5, 7)))
        self.user_id_2 = user_dao.save_user(
            User("user2", "password", "nickname", "avatar_url",
                 datetime(2000, 2, 20)))

        self.dialog_id = ""
Ejemplo n.º 3
0
def callback(client: WebApplicationClient):
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send a request to get tokens! Yay tokens!
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that you have tokens (yay) let's find and hit the URL
    # from Google that gives you the user's profile information,
    # including their Google profile image and email
    user_info_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(user_info_endpoint)
    user_info_response = requests.get(uri, headers=headers, data=body)

    # You want to make sure their email is verified.
    # The user authenticated with Google, authorized your
    # app, and now you've verified their email through Google!
    if user_info_response.json().get("email_verified"):
        unique_id = user_info_response.json()["sub"]
        users_email = user_info_response.json()["email"]
        picture = user_info_response.json()["picture"]
        users_name = user_info_response.json()["name"]
    else:
        return "User email not available or not verified by Google.", 400

    # Create a user in your db with the information provided by Google
    user = user_dao.get_user_by_google_id(unique_id)
    if user is None:
        user = User(unique_id, users_name, users_email, picture, "")
        user_dao.save_user(user)
        # TODO send request about birthday
    else:
        if user.profile_pic != picture:
            user.profile_pic = picture
            user_dao.update_picture(user.id, picture)

    # Begin user session by logging the user in
    login_user(user)
Ejemplo n.º 4
0
def get_active_project(user):
    try:
        active_project = User(user.get("_id")).get_active_project()
        if not active_project:
            return jsonify({})
        else:
            return jsonify({"project_id": active_project.get_id()})

    except Exception as e:
        print(f"Error when getting active project {e}")
        return jsonify({"error_message": "Error getting active project"}), 400
Ejemplo n.º 5
0
def unlink_resource(user):
    try:
        resource_id = bson.ObjectId(request.json["resource_id"])

        project = User(user).get_active_project()
        project.remove_resource(resource_id)

        return jsonify({"success_message": "Resource unlinked from project"})

    except Exception as e:
        print(e)
        return jsonify({"error_message": "Error unlinking resource from project"}), 400
Ejemplo n.º 6
0
def launch_plugin(user):
    try:
        resource_id = bson.ObjectId(request.json["resource_id"])
        plugin_name = request.json["plugin_name"]

        project = User(user).get_active_project()
        resource = Resource(resource_id)

        resource.launch_plugin(project.get_id(), plugin_name)
        return jsonify({"sucess_message": "ok"})

    except Exception as e:
        print(f"[launch_plugin]: {e}")
        return jsonify({"error_message": "Error launching plugin"}), 400
Ejemplo n.º 7
0
def ping(user):
    try:
        timestamp = time.time()
        active_project = User(user.get("_id")).get_active_project()
        if active_project:
            updates = active_project.get_updates(timestamp)
            return jsonify(updates)
        else:
            return jsonify([])

    except Exception as e:
        tb1 = traceback.TracebackException.from_exception(e)
        print("".join(tb1.format()))
        return jsonify({"error_message": "Server error :("}), 400
Ejemplo n.º 8
0
def get_resources(user):
    try:
        project_id = request.json["project_id"]
        user_projects = [str(project) for project in User(user).get_projects()]

        # User unable to load the project
        if not project_id in user_projects:
            return (
                jsonify({
                    "error_message":
                    f"User is not allowed to load project {project_id}"
                }),
                400,
            )

        project = Project(project_id)
        resources = project.get_resources()

        results = []
        for resource in resources:
            results.append(ResourceManager.get(resource).to_JSON())

        return jsonify(results)

    except Exception as e:
        print(f"Error getting resource list {e}")
        tb1 = traceback.TracebackException.from_exception(e)
        print("".join(tb1.format()))
        return jsonify({"error_message": "Error getting resources"}), 400
Ejemplo n.º 9
0
def launch_plugin(user):
    try:
        resource_id = bson.ObjectId(request.json["resource_id"])
        resource_type_as_string = request.json["resource_type"]
        plugin_name = request.json["plugin_name"]

        project = User(user).get_active_project()
        resource_type = ResourceType(resource_type_as_string)
        resource = Resources.get(resource_id, resource_type)

        resource.launch_plugin(project.get_id(), plugin_name)
        return jsonify({"sucess_message": "ok"})

    except Exception as e:
        print(e)
        return jsonify(
            {"error_message": "Error unlinking resource from project"}), 400
    def setUp(self):
        self.user_id_1 = user_dao.save_user(
            User("user1", "password", "nickname", "avatar_url",
                 datetime(1998, 5, 7)))
        self.user_id_2 = user_dao.save_user(
            User("user2", "password", "nickname", "avatar_url",
                 datetime(2000, 2, 20)))

        self.group_event_id_test_create = ""
        self.group_event_id_test_delete = ""
        self.group_event_id_test_leave = ""

        self.member_id_test_create = ""
        self.member_id_test_delete_1 = ""
        self.member_id_test_delete_2 = ""
        self.member_id_test_leave_1 = ""
        self.member_id_test_leave_2 = ""
        self.event_chat_id = ""
Ejemplo n.º 11
0
def set_active_project(user):
    try:
        project_id = request.json["project_id"]
        User(user).set_active_project(project_id)
        return jsonify({})

    except Exception as e:
        print(f"Error when setting an active project {e}")
        return jsonify({"error_message": "Error during active project setting"}), 400
Ejemplo n.º 12
0
def get_projects(user):
    try:
        projects = User(user).get_projects()
        user_projects = Projects.get_project_docs(projects, ["name", "creation_date"])
        return jsonify(desobjectid_cursor(user_projects))

    except Exception as e:
        print(f"Error when retrieving project {e}")
        return jsonify({"error_message": "Error when retrieving a project"}), 400
    def setUp(self):
        self.sender_invites = user_dao.save_user(
            User("user1", "password", "nickname", "avatar_url",
                 datetime(1998, 5, 7)))
        self.receiver_invites = user_dao.save_user(
            User("user2", "password", "nickname", "avatar_url",
                 datetime(2000, 2, 20)))
        self.group_event_id = group_event_dao.save(
            GroupEvent("group_event", False, datetime.today(), "address",
                       "description"))

        self.invite_to_friend_id_test_send = ""
        self.invite_to_event_id_test_send = ""

        self.invite_to_friend_id_test_accept_invite = ""
        self.invite_to_event_id_test_accept_invite = ""

        self.chat_id = ""
        self.member_id = ""
Ejemplo n.º 14
0
def create_resource(user):
    try:
        resource_name = request.json["resource_name"].strip()
        resource_type = request.json["resource_type"].lower()

        resource_type = ResourceType.get_type_from_string(resource_type)

        resource = Resources.get(resource_name, resource_type, get_by_name=True)

        project = User(user).get_active_project()
        project.add_resource(resource)

        response = []
        response.append(
            {
                "success_message": f"Added new resource: {resource_name}",
                "new_resource": resource.to_JSON(),
                "type": resource.get_type_value(),
            }
        )

        resource.launch_plugins(project.get_id())

        # Deal with the case of URL resources where we have the chance to add a Domain or IP
        if resource.get_type() == ResourceType.URL:
            ip_or_domain = urllib.parse.urlparse(resource_name).netloc
            resource_type = ResourceType.validate_ip_or_domain(ip_or_domain)
            if ip_or_domain:
                resource = Resources.get(ip_or_domain, resource_type, get_by_name=True)
                project.add_resource(resource)
                response.append(
                    {
                        "success_message": f"Added new resource: {ip_or_domain}",
                        "new_resource": resource.to_JSON(),
                        "type": resource.get_type_value(),
                    }
                )
                resource.launch_plugins(project.get_id())

        # TODO: Deal with the case of domain -> IP
        # TODO: Deal with the case of emails -> domains -> IP

        return jsonify(response)

    except ResourceTypeException:
        return jsonify({"error_message": "Trying to add an unkown resource type"}), 400

    except Exception as e:
        tb1 = traceback.TracebackException.from_exception(e)
        print("".join(tb1.format()))
        return jsonify({"error_message": "Server error :("}), 400
Ejemplo n.º 15
0
def add_new_tag(user):
    try:
        project = User(user).get_active_project()
        name = request.json["tag"]["name"]
        color = request.json["tag"]["color"]

        TagManager().new({"name": name, "color": color})

        return jsonify({"sucess_message": "ok"})

    except Exception as e:
        print(e)
        return jsonify({"error_message": "Error adding new tag"}), 400
Ejemplo n.º 16
0
def get_projects(user):
    try:
        projects = User(user).get_projects()
        if not projects:
            return jsonify([])

        user_projects = Projects.get_project_docs(projects, ["name", "creation_date"])
        return jsonify(desobjectid_cursor(user_projects))

    except Exception as e:
        print(f"Error when retrieving projects")
        tb1 = traceback.TracebackException.from_exception(e)
        print("".join(tb1.format()))
        return jsonify({"error_message": "Error when retrieving projects"}), 400
Ejemplo n.º 17
0
def create_user_from_json(json):
    if json is None:
        return None

    return User(json['google_id'],
                json['name'],
                json['email'],
                json['profile_pic'],
                json['birthday'],
                json['_id'],
                json['event_id_list'],
                json['friend_id_list'],
                json['chat_id_list'],
                json['invite_id_list'])
Ejemplo n.º 18
0
def get_plugins(user):
    try:
        resource_id = bson.ObjectId(request.json["resource_id"])
        project_id = bson.ObjectId(request.json["project_id"])
        resource_type_as_string = request.json["resource_type"]

        project = User(user).get_active_project()
        resource_type = ResourceType(resource_type_as_string)
        resource = Resources.get(resource_id, resource_type)
        plugin_list = resource.get_plugins(project_id)

        return json.dumps(plugin_list, default=str)

    except Exception as e:
        print(e)
        return jsonify(
            {"error_message": "Error unlinking resource from project"}), 400
Ejemplo n.º 19
0
def delete_project(user):
    try:
        project_id = request.json["project_id"]
        Projects.delete(project_id)
        User(user.get("_id")).remove_project(project_id)

        return jsonify({"success_message": f"Selected project deleted"})

    except ProjectNotExistsException as e:
        print(f"Selected project for deletion does not exists {e}")
        return (
            jsonify({
                "error_message":
                "Deletion error: Could not find any project with that ID"
            }),
            400,
        )

    except Exception as e:
        print(f"Error when deleting a project {e}")
        return jsonify({"error_message": "Error during deletion"}), 400
Ejemplo n.º 20
0
def new_project(user):
    try:
        name = request.json["name"]
        project_id = Projects.create(name, user)
        User(user).add_project(project_id)

        return jsonify({"success_message": f"New project {name} created"})

    except ProjectNameException:
        print(f"Project name error")
        return (jsonify({"error_message": "Project name error"}), 400)

    except ProjectExistException:
        print(f"Project already exists in database")
        return (
            jsonify({"error_message": "A project with that name already exists"}),
            400,
        )

    except Exception as e:
        print(f"Error when creating new project {e}")
        return jsonify({"error_message": "Error when creating a new project"}), 400
Ejemplo n.º 21
0
def rename_project(user):
    try:
        project_id = bson.ObjectId(request.json["id"])
        new_name = request.json["new_name"]

        if not new_name.isalnum() or len(new_name) > PROJECT_NAME_LIMIT:
            raise ProjectNameException

        if project_id in User(user.get("_id")).get_projects():
            project = Project(project_id)
            if project.rename(new_name):
                return jsonify({"success_message": f"Successful renaming"})

        return jsonify({"error_message": "The name is not valid"}), 400

    except ProjectNameException as e:
        print(f"Project name error")
        return jsonify({"error_message": "The name is not valid"}), 400

    except Exception as e:
        print(f"Error when renaming project {e}")
        return jsonify({"error_message": "Error when renaming project"}), 400
    def setUp(self):
        self.user_id = user_dao.save_user(
            User("user1", "password", "nickname", "avatar_url", datetime(1998, 5, 7)))

        self.single_event_id_test_create = ""
        self.single_event_id_test_delete = ""
Ejemplo n.º 23
0
def save_user(user: User):
    json = user.to_json_for_db()

    user_id = users_collection.insert_one(json).inserted_id
    user.set_id(user_id)
    return user_id
Ejemplo n.º 24
0
def get_current_user(user: User):
    return json_util.dumps(user.to_json())
Ejemplo n.º 25
0
class TestUser(TestCase):
    def setUp(self):
        self.user = User("login", "password", "nickname", "avatar_url",
                         datetime(1998, 5, 7), "id")

    def test_add_event(self):
        self.assertEqual(len(self.user.event_id_list), 0)
        self.user.add_event("event_id_1")
        self.assertEqual(len(self.user.event_id_list), 1)
        self.user.add_event("event_id_2")
        self.assertEqual(len(self.user.event_id_list), 2)

    def test_delete_event(self):
        self.assertEqual(len(self.user.event_id_list), 2)
        self.user.delete_event("event_id_1")
        self.assertEqual(len(self.user.event_id_list), 1)
        self.user.delete_event("event_id_2")
        self.assertEqual(len(self.user.event_id_list), 0)

    def test_add_friend(self):
        self.assertEqual(len(self.user.friend_id_list), 0)
        self.user.add_friend("friend_id_1")
        self.assertEqual(len(self.user.friend_id_list), 1)
        self.user.add_friend("friend_id_2")
        self.assertEqual(len(self.user.friend_id_list), 2)

    def test_delete_friend(self):
        self.assertEqual(len(self.user.friend_id_list), 2)
        self.user.delete_friend("friend_id_1")
        self.assertEqual(len(self.user.friend_id_list), 1)
        self.user.delete_friend("friend_id_2")
        self.assertEqual(len(self.user.friend_id_list), 0)

    def test_add_chat(self):
        self.assertEqual(len(self.user.chat_id_list), 0)
        self.user.add_chat("chat_id_1")
        self.assertEqual(len(self.user.chat_id_list), 1)
        self.user.add_chat("chat_id_2")
        self.assertEqual(len(self.user.chat_id_list), 2)

    def test_delete_chat(self):
        self.assertEqual(len(self.user.chat_id_list), 2)
        self.user.delete_chat("chat_id_1")
        self.assertEqual(len(self.user.chat_id_list), 1)
        self.user.delete_chat("chat_id_2")
        self.assertEqual(len(self.user.chat_id_list), 0)

    def test_add_invite(self):
        self.assertEqual(len(self.user.invite_id_list), 0)
        self.user.add_invite("invite_id_1")
        self.assertEqual(len(self.user.invite_id_list), 1)
        self.user.add_invite("invite_id_2")
        self.assertEqual(len(self.user.invite_id_list), 2)

    def test_delete_invite(self):
        self.assertEqual(len(self.user.invite_id_list), 2)
        self.user.delete_invite("invite_id_1")
        self.assertEqual(len(self.user.invite_id_list), 1)
        self.user.delete_invite("invite_id_2")
        self.assertEqual(len(self.user.invite_id_list), 0)
Ejemplo n.º 26
0
 def setUp(self):
     self.user = User("login", "password", "nickname", "avatar_url",
                      datetime(1998, 5, 7), "id")