Exemple #1
0
def test_logout():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_logout(token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/logout?accessToken={}".
            format(token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
        else:
            assert jsonresp

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(test_handle_logout(token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
async def test_getAuthCode(aiohttp_client):
    remove_existing_db()
    bumper.db = "tests/tmp.db"  # Set db location for testing
    client = await aiohttp_client(create_app)

    # Test without user or token
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/getAuthCode?uid={}&accessToken={}".format(
            None, None
        )
    )
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.ERR_TOKEN_INVALID

    # Test as global_e
    resp = await client.get(
        "/v1/global/auth/getAuthCode?uid={}&deviceId={}".format(None, "dev_1234")
    )
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.ERR_TOKEN_INVALID

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/getAuthCode?uid={}&accessToken={}".format(
            "testuser", "token_1234"
        )
    )
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "authCode" in jsonresp["data"]
    assert "ecovacsUid" in jsonresp["data"]

    # The above should have added an authcode to token, try again to test with existing authcode
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/getAuthCode?uid={}&accessToken={}".format(
            "testuser", "token_1234"
        )
    )
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "authCode" in jsonresp["data"]
    assert "ecovacsUid" in jsonresp["data"]
Exemple #3
0
def test_checkLogin():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_checkLogin(token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/checkLogin?accessToken={}"
            .format(token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
            assert "accessToken" in jsonresp["data"]
            if not token:
                assert jsonresp["data"]["accessToken"] != "token_1234"
            else:
                assert jsonresp["data"]["accessToken"] == "token_1234"

            assert "uid" in jsonresp["data"]
            assert "username" in jsonresp["data"]
        else:
            assert jsonresp

    # Test
    loop.run_until_complete(test_handle_checkLogin())

    # Add a user to db and test with existing users
    bumper.user_add("testuser")
    # Test
    loop.run_until_complete(test_handle_checkLogin())

    # Remove dev from tmpuser
    bumper.user_remove_device("tmpuser", "dev_1234")

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(test_handle_checkLogin(token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Exemple #4
0
    def _auth_any(self, devid, country, request):
        try:
            user_devid = devid
            countrycode = country
            user = bumper.user_by_deviceid(user_devid)
            bots = bumper.db_get().table("bots").all()

            if user:  # Default to user 0
                tmpuser = user
                bumper.user_add_device(tmpuser["userid"], user_devid)
            else:
                bumper.user_add("tmpuser")  # Add a new user
                tmpuser = bumper.user_get("tmpuser")
                bumper.user_add_device(tmpuser["userid"], user_devid)

            for bot in bots:  # Add all bots to the user
                bumper.user_add_bot(tmpuser["userid"], bot["did"])

            if "checkLogin" in request.path:  # If request was to check a token do so
                checkToken = self.check_token(
                    countrycode, tmpuser, request.query["accessToken"]
                )
                isGood = json.loads(checkToken.text)
                if isGood["code"] == "0000":
                    return isGood

            # Deactivate old tokens and authcodes
            bumper.user_revoke_expired_tokens(tmpuser["userid"])

            body = {
                "code": bumper.RETURN_API_SUCCESS,
                "data": {
                    "accessToken": self.generate_token(tmpuser),  # Generate a token
                    "country": countrycode,
                    "email": "*****@*****.**",
                    "uid": "fuid_{}".format(tmpuser["userid"]),
                    "username": "******".format(tmpuser["userid"]),
                },
                "msg": "操作成功",
                "time": bumper.get_milli_time(datetime.utcnow().timestamp()),
            }

            return body

        except Exception as e:
            confserverlog.exception("{}".format(e))
async def test_logout(aiohttp_client):
    remove_existing_db()
    bumper.db = "tests/tmp.db"  # Set db location for testing
    client = await aiohttp_client(create_app)

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/logout?accessToken={}".
        format("token_1234"))

    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
Exemple #6
0
def test_getAuthCode():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_getAuthCode(uid=None, token=None):
        resp = await client.get(
            "/1/private/us/en/dev_1234/ios/1/0/0/user/getAuthCode?uid={}&accessToken={}"
            .format(uid, token))
        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            if token:
                assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
                assert "authCode" in jsonresp["data"]
                assert "ecovacsUid" in jsonresp["data"]
            else:
                assert jsonresp["code"] == bumper.ERR_TOKEN_INVALID
        else:
            assert jsonresp

    # Test without user or token
    loop.run_until_complete(test_handle_getAuthCode())

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    # Test
    loop.run_until_complete(
        test_handle_getAuthCode(uid="testuser", token="token_1234"))

    # The above should have added an authcode to token, try again to test with existing authcode
    # Test
    loop.run_until_complete(
        test_handle_getAuthCode(uid="testuser", token="token_1234"))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
async def test_getUserAccountInfo(aiohttp_client):
    remove_existing_db()
    bumper.db = "tests/tmp.db"  # Set db location for testing
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    bumper.user_add_authcode("testuser", "token_1234", "auth_1234")
    bumper.user_add_bot("testuser", "did_1234")
    bumper.bot_add("sn_1234", "did_1234", "class_1234", "res_1234", "com_1234")

    client = await aiohttp_client(create_app)

    resp = await client.get(
        "/v1/private/us/en/dev_1234/global_e/1/0/0/user/getUserAccountInfo")
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == "0000"
    assert jsonresp["msg"] == "操作成功"
    assert jsonresp["data"]["userName"] == "fusername_testuser"
Exemple #8
0
def test_user_db():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db

    # Test os_db_path
    platform.system = mock.MagicMock(return_value="Windows")
    p = platform.system()
    os.getenv = mock.MagicMock(return_value="C:\AppData")
    o = os.getenv("APPDATA")
    assert_equals(bumper.os_db_path(),
                  os.path.join(os.getenv("APPDATA"), "bumper.db"))

    platform.system = mock.MagicMock(return_value="Linux")
    assert_equals(bumper.os_db_path(),
                  os.path.expanduser("~/.config/bumper.db"))

    bumper.db = "tests/tmp.db"  # Set db location for testing
    bumper.user_add("testuser")  # Add testuser

    assert_equals(bumper.user_get("testuser")["userid"],
                  "testuser")  # Test that testuser was created and returned

    bumper.user_add_device("testuser", "dev_1234")  # Add device to testuser

    assert_equals(bumper.user_by_deviceid("dev_1234")["userid"],
                  "testuser")  # Test that testuser was found by deviceid

    bumper.user_remove_device("testuser",
                              "dev_1234")  # Remove device from testuser

    assert_true(
        "dev_1234" not in bumper.user_get("testuser")
        ["devices"])  # Test that dev_1234 was not found in testuser devices

    bumper.user_add_bot("testuser", "bot_1234")  # Add bot did to testuser

    assert_true("bot_1234" in bumper.user_get("testuser")
                ["bots"])  # Test that bot was found in testuser's bot list

    bumper.user_remove_bot("testuser",
                           "bot_1234")  # Remove bot did from testuser

    assert_true("bot_1234" not in bumper.user_get("testuser")
                ["bots"])  # Test that bot was not found in testuser's bot list

    bumper.user_add_token("testuser", "token_1234")  # Add token to testuser

    assert_true(bumper.check_token(
        "testuser", "token_1234"))  # Test that token was found for testuser

    assert_true(bumper.user_get_token(
        "testuser", "token_1234"))  # Test that token was returned for testuser

    bumper.user_add_authcode(
        "testuser", "token_1234",
        "auth_1234")  # Add authcode to token_1234 for testuser
    assert_true(bumper.check_authcode(
        "testuser", "auth_1234"))  # Test that authcode was found for testuser

    bumper.user_revoke_authcode("testuser", "token_1234",
                                "auth_1234")  # Remove authcode from testuser
    assert_false(bumper.check_authcode(
        "testuser",
        "auth_1234"))  # Test that authcode was not found for testuser
    bumper.user_revoke_token("testuser",
                             "token_1234")  # Remove token from testuser
    assert_false(bumper.check_token(
        "testuser",
        "token_1234"))  # Test that token was not found for testuser
    bumper.user_add_token("testuser", "token_1234")  # Add token_1234
    bumper.user_add_token("testuser", "token_4321")  # Add token_4321
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  2)  # Test 2 tokens are available
    bumper.user_revoke_all_tokens("testuser")  # Revoke all tokens
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  0)  # Test 0 tokens are available

    db = TinyDB("tests/tmp.db")
    tokens = db.table("tokens")
    tokens.insert({
        "userid":
        "testuser",
        "token":
        "token_1234",
        "expiration":
        "{}".format(datetime.datetime.now() + datetime.timedelta(seconds=-10)),
    })  # Add expired token
    db.close()
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  1)  # Test 1 tokens are available
    bumper.user_revoke_expired_tokens("testuser")  # Revoke expired tokens
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  0)  # Test 0 tokens are available

    db = TinyDB("tests/tmp.db")
    tokens = db.table("tokens")
    tokens.insert({
        "userid":
        "testuser",
        "token":
        "token_1234",
        "expiration":
        "{}".format(datetime.datetime.now() + datetime.timedelta(seconds=-10)),
    })  # Add expired token
    db.close()
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  1)  # Test 1 tokens are available
    bumper.revoke_expired_tokens()  # Revoke expired tokens
    assert_equals(len(bumper.user_get_tokens("testuser")),
                  0)  # Test 0 tokens are available
async def test_postUsersAPI(aiohttp_client):
    remove_existing_db()
    bumper.db = "tests/tmp.db"  # Set db location for testing
    client = await aiohttp_client(create_app)

    # Test FindBest
    postbody = {"todo": "FindBest", "service": "EcoMsgNew"}
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test EcoUpdate
    postbody = {"todo": "FindBest", "service": "EcoUpdate"}
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test loginByItToken - Uses the authcode
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    bumper.user_add_authcode("testuser", "token_1234", "auth_1234")
    bumper.user_add_bot("testuser", "did_1234")
    bumper.bot_add("sn_1234", "did_1234", "class_1234", "res_1234", "com_1234")
    # Test
    postbody = {
        "country": "US",
        "last": "",
        "realm": "ecouser.net",
        "resource": "dev_1234",
        "todo": "loginByItToken",
        "token": "auth_1234",
        "userId": "testuser",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test as EcoVacs Home (global_e)
    postbody = {
        "country": "US",
        "edition": "ECOGLOBLE",
        "last": "",
        "org": "ECOWW",
        "resource": "dev_1234",
        "todo": "loginByItToken",
        "token": "auth_1234",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test as EcoVacs Home (global_e) & Post Form
    postbody = {
        "country": "US",
        "edition": "ECOGLOBLE",
        "last": "",
        "org": "ECOWW",
        "resource": "dev_1234",
        "todo": "loginByItToken",
        "token": "auth_1234",
    }
    resp = await client.post("/api/users/user.do", data=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test GetDeviceList
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "GetDeviceList",
        "userid": "testuser",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test SetDeviceNick
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "SetDeviceNick",
        "nick": "botnick",
        "did": "did_1234",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test AddOneDevice - Same as set nick for some bots
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "AddOneDevice",
        "nick": "botnick",
        "did": "did_1234",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"

    # Test DeleteOneDevice - remove bot
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "DeleteOneDevice",
        "did": "did_1234",
    }
    resp = await client.post("/api/users/user.do", json=postbody)
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["result"] == "ok"
async def test_checkLogin(aiohttp_client):
    remove_existing_db()
    bumper.db = "tests/tmp.db"  # Set db location for testing
    client = await aiohttp_client(create_app)

    # Test without token
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/checkLogin?accessToken={}".
        format(None))
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "accessToken" in jsonresp["data"]
    assert jsonresp["data"]["accessToken"] != "token_1234"
    assert "uid" in jsonresp["data"]
    assert "username" in jsonresp["data"]

    # Add a user to db and test with existing users
    bumper.user_add("testuser")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/checkLogin?accessToken={}".
        format(None))
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "accessToken" in jsonresp["data"]
    assert jsonresp["data"]["accessToken"] != "token_1234"
    assert "uid" in jsonresp["data"]
    assert "username" in jsonresp["data"]

    # Test again using global_e app
    bumper.user_add("testuser")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/global_e/1/0/0/user/checkLogin?accessToken={}"
        .format(None))
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "accessToken" in jsonresp["data"]
    assert jsonresp["data"]["accessToken"] != "token_1234"
    assert "uid" in jsonresp["data"]
    assert "username" in jsonresp["data"]

    # Remove dev from tmpuser
    bumper.user_remove_device("tmpuser", "dev_1234")

    # Add a token to user and test
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/ios/1/0/0/user/checkLogin?accessToken={}".
        format("token_1234"))
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "accessToken" in jsonresp["data"]
    assert jsonresp["data"]["accessToken"] == "token_1234"
    assert "uid" in jsonresp["data"]
    assert "username" in jsonresp["data"]

    # Test again using global_e app
    bumper.user_add("testuser")
    resp = await client.get(
        "/v1/private/us/en/dev_1234/global_e/1/0/0/user/checkLogin?accessToken={}"
        .format("token_1234"))
    assert resp.status == 200
    text = await resp.text()
    jsonresp = json.loads(text)
    assert jsonresp["code"] == bumper.RETURN_API_SUCCESS
    assert "accessToken" in jsonresp["data"]
    assert jsonresp["data"]["accessToken"] == "token_1234"
    assert "uid" in jsonresp["data"]
    assert "username" in jsonresp["data"]
Exemple #11
0
def test_user_db():

    bumper.db = "tests/tmp.db"  # Set db location for testing
    bumper.user_add("testuser")  # Add testuser

    assert (bumper.user_get("testuser")["userid"] == "testuser"
            )  # Test that testuser was created and returned

    bumper.user_add_device("testuser", "dev_1234")  # Add device to testuser

    assert (bumper.user_by_deviceid("dev_1234")["userid"] == "testuser"
            )  # Test that testuser was found by deviceid

    bumper.user_remove_device("testuser",
                              "dev_1234")  # Remove device from testuser

    assert "dev_1234" not in bumper.user_get("testuser")["devices"]
    # Test that dev_1234 was not found in testuser devices

    bumper.user_add_bot("testuser", "bot_1234")  # Add bot did to testuser

    assert "bot_1234" in bumper.user_get("testuser")["bots"]
    # Test that bot was found in testuser's bot list

    bumper.user_remove_bot("testuser",
                           "bot_1234")  # Remove bot did from testuser

    assert "bot_1234" not in bumper.user_get("testuser")["bots"]
    # Test that bot was not found in testuser's bot list

    bumper.user_add_token("testuser", "token_1234")  # Add token to testuser

    assert bumper.check_token("testuser", "token_1234")
    # Test that token was found for testuser

    assert bumper.user_get_token("testuser", "token_1234")
    # Test that token was returned for testuser

    bumper.user_add_authcode(
        "testuser", "token_1234",
        "auth_1234")  # Add authcode to token_1234 for testuser
    assert bumper.check_authcode("testuser", "auth_1234")
    # Test that authcode was found for testuser

    bumper.user_revoke_authcode("testuser", "token_1234",
                                "auth_1234")  # Remove authcode from testuser
    assert bumper.check_authcode("testuser", "auth_1234") == False
    # Test that authcode was not found for testuser
    bumper.user_revoke_token("testuser",
                             "token_1234")  # Remove token from testuser
    assert (bumper.check_token("testuser", "token_1234") == False
            )  # Test that token was not found for testuser
    bumper.user_add_token("testuser", "token_1234")  # Add token_1234
    bumper.user_add_token("testuser", "token_4321")  # Add token_4321
    assert len(
        bumper.user_get_tokens("testuser")) == 2  # Test 2 tokens are available
    bumper.user_revoke_all_tokens("testuser")  # Revoke all tokens
    assert len(
        bumper.user_get_tokens("testuser")) == 0  # Test 0 tokens are available

    db = TinyDB("tests/tmp.db")
    tokens = db.table("tokens")
    tokens.insert({
        "userid":
        "testuser",
        "token":
        "token_1234",
        "expiration":
        "{}".format(datetime.now() + timedelta(seconds=-10)),
    })  # Add expired token
    db.close()
    assert len(
        bumper.user_get_tokens("testuser")) == 1  # Test 1 tokens are available
    bumper.user_revoke_expired_tokens("testuser")  # Revoke expired tokens
    assert len(
        bumper.user_get_tokens("testuser")) == 0  # Test 0 tokens are available

    db = TinyDB("tests/tmp.db")
    tokens = db.table("tokens")
    tokens.insert({
        "userid":
        "testuser",
        "token":
        "token_1234",
        "expiration":
        "{}".format(datetime.now() + timedelta(seconds=-10)),
    })  # Add expired token
    db.close()
    assert len(
        bumper.user_get_tokens("testuser")) == 1  # Test 1 tokens are available
    bumper.revoke_expired_tokens()  # Revoke expired tokens
    assert len(
        bumper.user_get_tokens("testuser")) == 0  # Test 0 tokens are available
Exemple #12
0
def test_postUsersAPI():
    if os.path.exists("tests/tmp.db"):
        os.remove("tests/tmp.db")  # Remove existing db
    bumper.db = "tests/tmp.db"  # Set db location for testing
    loop = asyncio.get_event_loop()
    client = TestClient(TestServer(app), loop=loop)
    loop.run_until_complete(client.start_server())
    root = "http://{}".format(confserver.address)

    async def test_handle_postUsersApi(postbody=None):
        resp = await client.post("/api/users/user.do", json=postbody)

        assert resp.status == 200
        text = await resp.text()
        jsonresp = json.loads(text)
        if jsonresp:
            assert jsonresp["result"] == "ok"
        else:
            assert jsonresp

    # Test FindBest
    postbody = {"todo": "FindBest", "service": "EcoMsgNew"}
    # Test
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test EcoUpdate
    postbody = {"todo": "FindBest", "service": "EcoUpdate"}
    # Test
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test loginByItToken - Uses the authcode
    bumper.user_add("testuser")
    bumper.user_add_device("testuser", "dev_1234")
    bumper.user_add_token("testuser", "token_1234")
    bumper.user_add_authcode("testuser", "token_1234", "auth_1234")
    bumper.user_add_bot("testuser", "did_1234")
    bumper.bot_add("sn_1234", "did_1234", "class_1234", "res_1234", "com_1234")
    # Test
    postbody = {
        "country": "US",
        "last": "",
        "realm": "ecouser.net",
        "resource": "dev_1234",
        "todo": "loginByItToken",
        "token": "auth_1234",
        "userId": "testuser",
    }
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test GetDeviceList
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "GetDeviceList",
        "userid": "testuser",
    }
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test SetDeviceNick
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "SetDeviceNick",
        "nick": "botnick",
        "did": "did_1234",
    }
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test AddOneDevice - Same as set nick for some bots
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "AddOneDevice",
        "nick": "botnick",
        "did": "did_1234",
    }
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    # Test DeleteOneDevice - remove bot
    postbody = {
        "auth": {
            "realm": "ecouser.net",
            "resource": "dev_1234",
            "token": "token_1234",
            "userid": "testuser",
            "with": "users",
        },
        "todo": "DeleteOneDevice",
        "did": "did_1234",
    }
    loop.run_until_complete(test_handle_postUsersApi(postbody))

    loop.run_until_complete(
        client.close())  # Close test server after all tests are done
Exemple #13
0
        def _auth_any(self, devid, apptype, country, request):
            try:
                user_devid = devid
                countrycode = country
                user = bumper.user_by_deviceid(user_devid)
                bots = bumper.db_get().table("bots").all()

                if user:  # Default to user 0
                    tmpuser = user
                    if "global_" in apptype:  # EcoVacs Home
                        login_details = EcoVacsHome_Login()
                        login_details.ucUid = "fuid_{}".format(
                            tmpuser["userid"])
                        login_details.loginName = "fusername_{}".format(
                            tmpuser["userid"])
                        login_details.mobile = None
                    else:
                        login_details = EcoVacs_Login()

                    login_details.accessToken = self.generate_token(tmpuser)
                    login_details.uid = "fuid_{}".format(tmpuser["userid"])
                    login_details.username = "******".format(
                        tmpuser["userid"])
                    login_details.country = countrycode
                    login_details.email = "*****@*****.**"
                    bumper.user_add_device(tmpuser["userid"], user_devid)
                else:
                    bumper.user_add("tmpuser")  # Add a new user
                    tmpuser = bumper.user_get("tmpuser")
                    if "global_" in apptype:  # EcoVacs Home
                        login_details = EcoVacsHome_Login()
                        login_details.ucUid = "fuid_{}".format(
                            tmpuser["userid"])
                        login_details.loginName = "fusername_{}".format(
                            tmpuser["userid"])
                        login_details.mobile = None
                    else:
                        login_details = EcoVacs_Login()

                    login_details.accessToken = self.generate_token(tmpuser)
                    login_details.uid = "fuid_{}".format(tmpuser["userid"])
                    login_details.username = "******".format(
                        tmpuser["userid"])
                    login_details.country = countrycode
                    login_details.email = "*****@*****.**"
                    bumper.user_add_device(tmpuser["userid"], user_devid)

                for bot in bots:  # Add all bots to the user
                    if "did" in bot:
                        bumper.user_add_bot(tmpuser["userid"], bot["did"])
                    else:
                        confserverlog.error("No DID for bot: {}".format(bot))

                if "checkLogin" in request.path:  # If request was to check a token do so
                    checkToken = self.check_token(apptype, countrycode,
                                                  tmpuser,
                                                  request.query["accessToken"])
                    isGood = json.loads(checkToken.text)
                    if isGood["code"] == "0000":
                        return isGood

                # Deactivate old tokens and authcodes
                bumper.user_revoke_expired_tokens(tmpuser["userid"])

                body = {
                    "code": bumper.RETURN_API_SUCCESS,
                    "data": json.loads(login_details.toJSON()),
                    # {
                    #    "accessToken": self.generate_token(tmpuser),  # Generate a token
                    #    "country": countrycode,
                    #    "email": "*****@*****.**",
                    #    "uid": "fuid_{}".format(tmpuser["userid"]),
                    #    "username": "******".format(tmpuser["userid"]),
                    # },
                    "msg": "操作成功",
                    "time": self.get_milli_time(datetime.utcnow().timestamp()),
                }

                return body

            except Exception as e:
                confserverlog.exception("{}".format(e))