Beispiel #1
0
def post_install():
    if path.exists(path.join(current_dir, 'tokens.json')):
        return 'Someone already authd', 400
    # Verify the "state" parameter

    # Retrieve the auth code from the request params
    code_param = request.args['code']

    # An empty string is a valid token for this request
    client = WebClient()

    # Request the auth tokens from Slack
    response = client.oauth_v2_access(
        client_id=client_id,
        client_secret=client_secret,
        code=code_param
    )
    # Save the bot token to an environmental variable or to your data store
    # for later use
    tokens = {
        "scope": response['authed_user']['scope'],
        "token_type": response['authed_user']['token_type'],
        "user_token": response['authed_user']['access_token']
    }
     
    with open(path.join(current_dir, 'tokens.json'), 'w') as f:
        json.dump(tokens, f)

    # Don't forget to let the user know that OAuth has succeeded!
    return "Installation is completed!"
Beispiel #2
0
def register(code):
    client = WebClient()

    try:
        response = client.oauth_v2_access(client_id=client_id,
                                          client_secret=client_secret,
                                          code=code)

        SlackBotToken.create(
            team_id=response["team"]["id"],
            team_name=response["team"]["name"],
            scope=response["scope"],
            token_type=response["token_type"],
            access_token=response["access_token"],
            bot_user_id=response["bot_user_id"],
        )
    except Exception as e:
        return str(e)

    return "I choose you successfully installed!"
Beispiel #3
0
def oauth_callback():
    # Retrieve the auth code and state from the request params
    if "code" in request.args:
        state = request.args["state"]
        if state_service.consume(state):
            code = request.args["code"]
            client = WebClient()  # no prepared token needed for this app
            response = client.oauth_v2_access(
                client_id=client_id,
                client_secret=client_secret,
                redirect_uri=redirect_uri,
                code=code
            )
            logger.info(f"oauth.v2.access response: {response}")
            database.save(response)
            return "Thanks for installing this app!"
        else:
            return make_response(f"Try the installation again (the state value is already expired)", 400)

    error = request.args["error"] if "error" in request.args else ""
    return make_response(f"Something is wrong with the installation (error: {error})", 400)
Beispiel #4
0
def authorisation_grant(client_id, client_secret, code, redirect_uri):
    client = WebClient()

    try:
        response = client.oauth_v2_access(
            client_id=client_id,
            client_secret=client_secret,
            code=code,
            redirect_uri=redirect_uri,
        )
    except SlackApiError as e:
        logging.warning(e)
        logging.warning("returning success=False")
        return AuthorisationGrantResponse(success=False)

    return AuthorisationGrantResponse(
        success=True,
        team=response.data["team"]["id"],
        user=response.data["authed_user"]["id"],
        token=response.data["authed_user"]["access_token"],
        scope=response.data["authed_user"]["scope"],
    )
Beispiel #5
0
async def authorize(code: str):
    client = WebClient()
    try:
        response = client.oauth_v2_access(
            code=code,
            client_id=settings.SLACK_CLIENT_ID,
            client_secret=settings.SLACK_CLIENT_SECRET,
            redirect_uri='',
        )
    except SlackApiError as e:
        logger.error(e, exc_info=True)
        return HTMLResponse('インストールに失敗しました',
                            status_code=HTTPStatus.BAD_REQUEST)
    slack_response = parse_obj_as(SlackResponse, response.data)
    try:
        team_conf = TeamConf.get(slack_response.team.id)
        team_conf.access_token = slack_response.access_token
        team_conf.save()
    except TeamConf.DoesNotExist:
        TeamConf(slack_response.team.id,
                 access_token=slack_response.access_token).save()
    return HTMLResponse('登録が完了しました')
class TestWebClient(unittest.TestCase):
    def setUp(self):
        setup_mock_web_api_server(self)
        self.client = WebClient(
            token="xoxb-api_test",
            base_url="http://localhost:8888",
        )

    def tearDown(self):
        cleanup_mock_web_api_server(self)

    pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE)
    pattern_for_package_identifier = re.compile("slackclient/(\\S+)")

    def test_subsequent_requests_with_a_session_succeeds(self):
        resp = self.client.api_test()
        assert resp["ok"]
        resp = self.client.api_test()
        assert resp["ok"]

    def test_api_calls_include_user_agent(self):
        self.client.token = "xoxb-api_test"
        resp = self.client.api_test()
        self.assertEqual(200, resp.status_code)

    def test_builtin_api_methods_send_json(self):
        self.client.token = "xoxb-api_test"
        resp = self.client.api_test(msg="bye")
        self.assertEqual(200, resp.status_code)
        self.assertEqual("bye", resp["args"]["msg"])

    def test_requests_can_be_paginated(self):
        self.client.token = "xoxb-users_list_pagination"
        users = []
        for page in self.client.users_list(limit=2):
            users = users + page["members"]
        self.assertTrue(len(users) == 4)

    def test_response_can_be_paginated_multiple_times(self):
        self.client.token = "xoxb-conversations_list_pagination"
        # This test suite verifies the changes in #521 work as expected
        response = self.client.conversations_list(limit=1)
        ids = []
        for page in response:
            ids.append(page["channels"][0]["id"])
        self.assertEqual(ids, ["C1", "C2", "C3"])

        # The second iteration starting with page 2
        # (page1 is already cached in `response`)
        self.client.token = "xoxb-conversations_list_pagination2"
        ids = []
        for page in response:
            ids.append(page["channels"][0]["id"])
        self.assertEqual(ids, ["C1", "C2", "C3"])

    def test_request_pagination_stops_when_next_cursor_is_missing(self):
        self.client.token = "xoxb-users_list_pagination_1"
        users = []
        for page in self.client.users_list(limit=2):
            users = users + page["members"]
        self.assertTrue(len(users) == 2)

    def test_json_can_only_be_sent_with_post_requests(self):
        with self.assertRaises(err.SlackRequestError):
            self.client.api_call("fake.method", http_verb="GET", json={})

    def test_slack_api_error_is_raised_on_unsuccessful_responses(self):
        self.client.token = "xoxb-api_test_false"
        with self.assertRaises(err.SlackApiError):
            self.client.api_test()
        self.client.token = "xoxb-500"
        with self.assertRaises(err.SlackApiError):
            self.client.api_test()

    def test_slack_api_rate_limiting_exception_returns_retry_after(self):
        self.client.token = "xoxb-rate_limited"
        try:
            self.client.api_test()
        except err.SlackApiError as slack_api_error:
            self.assertFalse(slack_api_error.response["ok"])
            self.assertEqual(429, slack_api_error.response.status_code)
            self.assertEqual(30, int(slack_api_error.response.headers["Retry-After"]))

    def test_the_api_call_files_argument_creates_the_expected_data(self):
        self.client.token = "xoxb-users_setPhoto"
        resp = self.client.users_setPhoto(
            image="tests/slack_sdk_fixture/slack_logo.png"
        )
        self.assertEqual(200, resp.status_code)

    def test_issue_560_bool_in_params_sync(self):
        self.client.token = "xoxb-conversations_list"
        self.client.conversations_list(exclude_archived=1)  # ok
        self.client.conversations_list(exclude_archived="true")  # ok
        self.client.conversations_list(exclude_archived=True)  # ok

    def test_issue_690_oauth_v2_access(self):
        self.client.token = ""
        resp = self.client.oauth_v2_access(
            client_id="111.222", client_secret="secret", code="codeeeeeeeeee"
        )
        self.assertIsNone(resp["error"])
        with self.assertRaises(err.SlackApiError):
            self.client.oauth_v2_access(
                client_id="999.999", client_secret="secret", code="codeeeeeeeeee"
            )

    def test_issue_690_oauth_access(self):
        self.client.token = ""
        resp = self.client.oauth_access(
            client_id="111.222", client_secret="secret", code="codeeeeeeeeee"
        )
        self.assertIsNone(resp["error"])
        with self.assertRaises(err.SlackApiError):
            self.client.oauth_access(
                client_id="999.999", client_secret="secret", code="codeeeeeeeeee"
            )

    def test_issue_705_no_param_request_pagination(self):
        self.client.token = "xoxb-users_list_pagination"
        users = []
        for page in self.client.users_list():
            users = users + page["members"]
        self.assertTrue(len(users) == 4)

    def test_token_param(self):
        client = WebClient(base_url="http://localhost:8888")
        with self.assertRaises(err.SlackApiError):
            client.users_list()
        resp = client.users_list(token="xoxb-users_list_pagination")
        self.assertIsNone(resp["error"])
        with self.assertRaises(err.SlackApiError):
            client.users_list()

    def test_timeout_issue_712(self):
        client = WebClient(base_url="http://localhost:8888", timeout=1)
        with self.assertRaises(socket.timeout):
            client.users_list(token="xoxb-timeout")

    def test_html_response_body_issue_718(self):
        client = WebClient(base_url="http://localhost:8888")
        try:
            client.users_list(token="xoxb-html_response")
            self.fail("SlackApiError expected here")
        except err.SlackApiError as e:
            self.assertTrue(
                str(e).startswith(
                    "Received a response in a non-JSON format: <!DOCTYPE HTML PUBLIC"
                ),
                e,
            )

    def test_user_agent_customization_issue_769(self):
        client = WebClient(
            base_url="http://localhost:8888",
            token="xoxb-user-agent this_is test",
            user_agent_prefix="this_is",
            user_agent_suffix="test",
        )
        resp = client.api_test()
        self.assertTrue(resp["ok"])

    def test_default_team_id(self):
        client = WebClient(base_url="http://localhost:8888", team_id="T_DEFAULT")
        resp = client.users_list(token="xoxb-users_list_pagination")
        self.assertIsNone(resp["error"])