Skip to content

Support OAuth #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,29 @@ https://developers.line.biz/en/reference/messaging-api/#issue-link-token
link_token_response = line_bot_api.issue_link_token(<user_id>)
print(link_token_response)

issue\_channel\_token(self, client_id, client_secret, grant_type='client_credentials', timeout=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Issues a short-lived channel access token.

https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token

.. code:: python

channel_token_response = line_bot_api.issue_channel_token(<client_id>, <client_secret>)
print(access_token_response)

revoke\_channel\_token(self, access_token, timeout=None)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Revokes a channel access token.

https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token

.. code:: python

line_bot_api.revoke_channel_token(<access_token>)

※ Error handling
^^^^^^^^^^^^^^^^

Expand Down
58 changes: 57 additions & 1 deletion linebot/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
from .http_client import HttpClient, RequestsHttpClient
from .models import (
Error, Profile, MemberIds, Content, RichMenuResponse, MessageQuotaResponse,
MessageQuotaConsumptionResponse, MessageDeliveryBroadcastResponse, IssueLinkTokenResponse
MessageQuotaConsumptionResponse, MessageDeliveryBroadcastResponse, IssueLinkTokenResponse,
IssueChannelTokenResponse,
)


Expand Down Expand Up @@ -744,7 +745,13 @@ def issue_link_token(self, user_id, timeout=None):
https://developers.line.biz/en/reference/messaging-api/#issue-link-token

:param str user_id: User ID for the LINE account to be linked
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
Default is self.http_client.timeout
:type timeout: float | tuple(float, float)
:rtype: :py:class:`linebot.models.responses.IssueLinkTokenResponse`
:return: IssueLinkTokenResponse instance
"""
response = self._post(
'/v2/bot/user/{user_id}/linkToken'.format(
Expand All @@ -755,6 +762,55 @@ def issue_link_token(self, user_id, timeout=None):

return IssueLinkTokenResponse.new_from_json_dict(response.json)

def issue_channel_token(self, client_id, client_secret,
grant_type='client_credentials', timeout=None):
"""Issues a short-lived channel access token.

https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token

:param str client_id: Channel ID.
:param str client_secret: Channel secret.
:param str grant_type: `client_credentials`
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
Default is self.http_client.timeout
:type timeout: float | tuple(float, float)
:rtype: :py:class:`linebot.models.responses.IssueChannelTokenResponse`
:return: IssueChannelTokenResponse instance
"""
response = self._post(
'/v2/oauth/accessToken',
data={
'client_id': client_id,
'client_secret': client_secret,
'grant_type': grant_type,
},
headers={'Content-Type': 'application/x-www-form-urlencoded'},
timeout=timeout
)

return IssueChannelTokenResponse.new_from_json_dict(response.json)

def revoke_channel_token(self, access_token, timeout=None):
"""Revokes a channel access token.

https://developers.line.biz/en/reference/messaging-api/#revoke-channel-access-token

:param str access_token: Channel access token.
:param timeout: (optional) How long to wait for the server
to send data before giving up, as a float,
or a (connect timeout, read timeout) float tuple.
Default is self.http_client.timeout
:type timeout: float | tuple(float, float)
"""
self._post(
'/v2/oauth/revoke',
data={'access_token': access_token},
headers={'Content-Type': 'application/x-www-form-urlencoded'},
timeout=timeout
)

def _get(self, path, params=None, headers=None, stream=False, timeout=None):
url = self.endpoint + path

Expand Down
1 change: 1 addition & 0 deletions linebot/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
MessageDeliveryBroadcastResponse,
Content as MessageContent, # backward compatibility,
IssueLinkTokenResponse,
IssueChannelTokenResponse,
)
from .rich_menu import ( # noqa
RichMenu,
Expand Down
22 changes: 22 additions & 0 deletions linebot/models/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,25 @@ def __init__(self, link_token=None, **kwargs):
super(IssueLinkTokenResponse, self).__init__(**kwargs)

self.link_token = link_token


class IssueChannelTokenResponse(Base):
"""IssueAccessTokenResponse.

https://developers.line.biz/en/reference/messaging-api/#issue-channel-access-token
"""

def __init__(self, access_token=None, expires_in=None, token_type=None, **kwargs):
"""__init__ method.

:param str access_token: Short-lived channel access token.
:param int expires_in: Time until channel access token expires in seconds
from time the token is issued.
:param str token_type: Bearer.
:param kwargs:
"""
super(IssueChannelTokenResponse, self).__init__(**kwargs)

self.access_token = access_token
self.expires_in = expires_in
self.token_type = token_type
76 changes: 76 additions & 0 deletions tests/api/test_issue_channel_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-

# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import unicode_literals, absolute_import

import sys
import unittest

import responses

from linebot import (
LineBotApi
)

PY3 = sys.version_info[0] == 3
if PY3:
from urllib import parse
else:
import urlparse as parse


class TestLineBotApi(unittest.TestCase):
def setUp(self):
self.tested = LineBotApi('channel_secret')
self.endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/v2/oauth/accessToken'
self.access_token = "W1TeHCgfH2Liwa....."
self.expires_in = 2592000
self.token_type = "Bearer"
self.client_id = 'client_id'
self.client_secret = 'client_secret'

@responses.activate
def test_issue_line_token(self):
responses.add(
responses.POST,
self.endpoint,
json={
"access_token": self.access_token,
"expires_in": self.expires_in,
"token_type": self.token_type
},
status=200
)

issue_access_token_response = self.tested.issue_channel_token(
self.client_id,
self.client_secret
)

request = responses.calls[0].request
self.assertEqual('POST', request.method)
self.assertEqual(self.endpoint, request.url)
self.assertEqual('application/x-www-form-urlencoded', request.headers['content-type'])
self.assertEqual(self.access_token, issue_access_token_response.access_token)
self.assertEqual(self.expires_in, issue_access_token_response.expires_in)
self.assertEqual(self.token_type, issue_access_token_response.token_type)

encoded_body = parse.parse_qs(request.body)
self.assertEqual('client_credentials', encoded_body['grant_type'][0])
self.assertEqual(self.client_id, encoded_body['client_id'][0])
self.assertEqual(self.client_secret, encoded_body['client_secret'][0])


if __name__ == '__main__':
unittest.main()
50 changes: 50 additions & 0 deletions tests/api/test_revoke_channel_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-

# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import unicode_literals, absolute_import

import unittest

import responses

from linebot import (
LineBotApi
)


class TestLineBotApi(unittest.TestCase):
def setUp(self):
self.tested = LineBotApi('channel_secret')
self.endpoint = LineBotApi.DEFAULT_API_ENDPOINT + '/v2/oauth/revoke'
self.access_token = "W1TeHCgfH2Liwa....."

@responses.activate
def test_issue_line_token(self):
responses.add(
responses.POST,
self.endpoint,
status=200
)

self.tested.revoke_channel_token(self.access_token)

request = responses.calls[0].request
self.assertEqual('POST', request.method)
self.assertEqual(self.endpoint, request.url)
self.assertEqual('application/x-www-form-urlencoded', request.headers['content-type'])
self.assertEqual('access_token={}'.format(self.access_token), request.body)


if __name__ == '__main__':
unittest.main()