Skip to content

Commit

Permalink
Merge pull request #63 from drillbits/oauth-accessToken
Browse files Browse the repository at this point in the history
Add `Issue channel access token` API
  • Loading branch information
Kazuhiro Kubota authored Jun 25, 2019
2 parents fb90c1c + 13e4bb1 commit a3e3584
Show file tree
Hide file tree
Showing 4 changed files with 386 additions and 0 deletions.
12 changes: 12 additions & 0 deletions linebot/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ const (
APIEndpointLinkToken = "/v2/bot/user/%s/linkToken"

APIEndpointGetMessageDelivery = "/v2/bot/message/delivery/%s"

APIEndpointIssueAccessToken = "/v2/oauth/accessToken"
APIEndpointRevokeAccessToken = "/v2/oauth/revoke"
)

// Client type
Expand Down Expand Up @@ -163,6 +166,15 @@ func (client *Client) post(ctx context.Context, endpoint string, body io.Reader)
return client.do(ctx, req)
}

func (client *Client) postform(ctx context.Context, endpoint string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest("POST", client.url(endpoint), body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return client.do(ctx, req)
}

func (client *Client) put(ctx context.Context, endpoint string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPut, client.url(endpoint), body)
if err != nil {
Expand Down
97 changes: 97 additions & 0 deletions linebot/oauth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2016 LINE Corporation
//
// LINE Corporation licenses this file to you 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:
//
// http://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.

package linebot

import (
"context"
"net/url"
"strings"
)

// IssueAccessToken method
func (client *Client) IssueAccessToken(channelID, channelSecret string) *IssueAccessTokenCall {
return &IssueAccessTokenCall{
c: client,
channelID: channelID,
channelSecret: channelSecret,
}
}

// IssueAccessTokenCall type
type IssueAccessTokenCall struct {
c *Client
ctx context.Context

channelID string
channelSecret string
}

// WithContext method
func (call *IssueAccessTokenCall) WithContext(ctx context.Context) *IssueAccessTokenCall {
call.ctx = ctx
return call
}

// Do method
func (call *IssueAccessTokenCall) Do() (*AccessTokenResponse, error) {
vs := url.Values{}
vs.Set("grant_type", "client_credentials")
vs.Set("client_id", call.channelID)
vs.Set("client_secret", call.channelSecret)
body := strings.NewReader(vs.Encode())

res, err := call.c.postform(call.ctx, APIEndpointIssueAccessToken, body)
if err != nil {
return nil, err
}
defer closeResponse(res)
return decodeToAccessTokenResponse(res)
}

// RevokeAccessToken method
func (client *Client) RevokeAccessToken(accessToken string) *RevokeAccessTokenCall {
return &RevokeAccessTokenCall{
c: client,
accessToken: accessToken,
}
}

// RevokeAccessTokenCall type
type RevokeAccessTokenCall struct {
c *Client
ctx context.Context

accessToken string
}

// WithContext method
func (call *RevokeAccessTokenCall) WithContext(ctx context.Context) *RevokeAccessTokenCall {
call.ctx = ctx
return call
}

// Do method
func (call *RevokeAccessTokenCall) Do() (*BasicResponse, error) {
vs := url.Values{}
vs.Set("access_token", call.accessToken)
body := strings.NewReader(vs.Encode())

res, err := call.c.postform(call.ctx, APIEndpointRevokeAccessToken, body)
if err != nil {
return nil, err
}
defer closeResponse(res)
return decodeToBasicResponse(res)
}
258 changes: 258 additions & 0 deletions linebot/oauth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
// Copyright 2016 LINE Corporation
//
// LINE Corporation licenses this file to you 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:
//
// http://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.

package linebot

import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)

func TestIssueAccessToken(t *testing.T) {
type want struct {
RequestBody []byte
Response *AccessTokenResponse
Error error
}
var testCases = []struct {
ClientID string
ClientSecret string
Response []byte
ResponseCode int
Want want
}{
{
ClientID: "testid",
ClientSecret: "testsecret",
ResponseCode: 200,
Response: []byte(`{}`),
Want: want{
RequestBody: []byte("client_id=testid&client_secret=testsecret&grant_type=client_credentials"),
Response: &AccessTokenResponse{},
},
},
}

var currentTestIdx int
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != http.MethodPost {
t.Errorf("Method %s; want %s", r.Method, http.MethodPost)
}
if r.URL.Path != APIEndpointIssueAccessToken {
t.Errorf("URLPath %s; want %s", r.URL.Path, APIEndpointIssueAccessToken)
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
tc := testCases[currentTestIdx]
if !reflect.DeepEqual(body, tc.Want.RequestBody) {
t.Errorf("RequestBody %s; want %s", body, tc.Want.RequestBody)
}
w.WriteHeader(tc.ResponseCode)
w.Write(tc.Response)
}))
defer server.Close()
client, err := mockClient(server)
if err != nil {
t.Fatal(err)
}
for i, tc := range testCases {
currentTestIdx = i
res, err := client.IssueAccessToken(tc.ClientID, tc.ClientSecret).Do()
if tc.Want.Error != nil {
if !reflect.DeepEqual(err, tc.Want.Error) {
t.Errorf("Error %d %q; want %q", i, err, tc.Want.Error)
}
} else {
if err != nil {
t.Error(err)
}
}
if tc.Want.Response != nil {
if !reflect.DeepEqual(res, tc.Want.Response) {
t.Errorf("Response %d %q; want %q", i, res, tc.Want.Response)
}
}
}
}

func TestIssueAccessTokenCall_WithContext(t *testing.T) {
type fields struct {
c *Client
ctx context.Context
channelID string
channelSecret string
}
type args struct {
ctx context.Context
}

oldCtx := context.Background()
type key string
newCtx := context.WithValue(oldCtx, key("foo"), "bar")

tests := []struct {
name string
fields fields
args args
want context.Context
}{
{
name: "replace context",
fields: fields{
ctx: oldCtx,
},
args: args{
ctx: newCtx,
},
want: newCtx,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
call := &IssueAccessTokenCall{
c: tt.fields.c,
ctx: tt.fields.ctx,
channelID: tt.fields.channelID,
channelSecret: tt.fields.channelSecret,
}
call = call.WithContext(tt.args.ctx)
got := call.ctx
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("IssueAccessTokenCall.WithContext() = %v, want %v", got, tt.want)
}
})
}
}

func TestRevokeAccessToken(t *testing.T) {
type want struct {
RequestBody []byte
Response *BasicResponse
Error error
}
var testCases = []struct {
AccessToken string
Response []byte
ResponseCode int
Want want
}{
{
AccessToken: "testtoken",
ResponseCode: 200,
Response: []byte(`{}`),
Want: want{
RequestBody: []byte("access_token=testtoken"),
Response: &BasicResponse{},
},
},
}

var currentTestIdx int
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if r.Method != http.MethodPost {
t.Errorf("Method %s; want %s", r.Method, http.MethodPost)
}
if r.URL.Path != APIEndpointRevokeAccessToken {
t.Errorf("URLPath %s; want %s", r.URL.Path, APIEndpointIssueAccessToken)
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Fatal(err)
}
tc := testCases[currentTestIdx]
if !reflect.DeepEqual(body, tc.Want.RequestBody) {
t.Errorf("RequestBody %s; want %s", body, tc.Want.RequestBody)
}
w.WriteHeader(tc.ResponseCode)
w.Write(tc.Response)
}))
defer server.Close()
client, err := mockClient(server)
if err != nil {
t.Fatal(err)
}
for i, tc := range testCases {
currentTestIdx = i
res, err := client.RevokeAccessToken(tc.AccessToken).Do()
if tc.Want.Error != nil {
if !reflect.DeepEqual(err, tc.Want.Error) {
t.Errorf("Error %d %q; want %q", i, err, tc.Want.Error)
}
} else {
if err != nil {
t.Error(err)
}
}
if tc.Want.Response != nil {
if !reflect.DeepEqual(res, tc.Want.Response) {
t.Errorf("Response %d %q; want %q", i, res, tc.Want.Response)
}
}
}
}

func TestRevokeAccessTokenCall_WithContext(t *testing.T) {
type fields struct {
c *Client
ctx context.Context
accessToken string
}
type args struct {
ctx context.Context
}

oldCtx := context.Background()
type key string
newCtx := context.WithValue(oldCtx, key("foo"), "bar")

tests := []struct {
name string
fields fields
args args
want context.Context
}{
{
name: "replace context",
fields: fields{
ctx: oldCtx,
},
args: args{
ctx: newCtx,
},
want: newCtx,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
call := &RevokeAccessTokenCall{
c: tt.fields.c,
ctx: tt.fields.ctx,
accessToken: tt.fields.accessToken,
}
call = call.WithContext(tt.args.ctx)
got := call.ctx
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("RevokeAccessTokenCall.WithContext() = %v, want %v", got, tt.want)
}
})
}
}
Loading

0 comments on commit a3e3584

Please sign in to comment.