66 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Go
		
	
	
	
			
		
		
	
	
			66 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Go
		
	
	
	
| package util
 | |
| 
 | |
| import (
 | |
| 	"fmt"
 | |
| 	"github.com/davidebianchi/go-jsonclient"
 | |
| 	"net/http"
 | |
| 	"net/url"
 | |
| )
 | |
| 
 | |
| type oAuthAccessTokenReq struct {
 | |
| 	ClientID     string `json:"client_id"`
 | |
| 	ClientSecret string `json:"client_secret"`
 | |
| 	Code         string `json:"code"`
 | |
| 	GrantType    string `json:"grant_type"`
 | |
| 	RedirectURI  string `json:"redirect_uri"`
 | |
| }
 | |
| type oAuthAccessTokenResp struct {
 | |
| 	AccessToken  string `json:"access_token"`
 | |
| 	TokenType    string `json:"token_type"`
 | |
| 	ExpiresIn    int    `json:"expires_in"`
 | |
| 	RefreshToken string `json:"refresh_token"`
 | |
| }
 | |
| 
 | |
| func GetOAuthToken(oAuthAccessTokenURL, clientID, clientSecret, code, redirectURI string) (string, error) {
 | |
| 	u, err := url.Parse(oAuthAccessTokenURL)
 | |
| 	if err != nil {
 | |
| 		logger.Errorf(`failed to parse oAuthAccessTokenURL. error: %s`, err.Error())
 | |
| 		return ``, err
 | |
| 	}
 | |
| 
 | |
| 	client, err := jsonclient.New(jsonclient.Options{
 | |
| 		BaseURL: fmt.Sprintf(`%s://%s/`, u.Scheme, u.Host),
 | |
| 	})
 | |
| 	if err != nil {
 | |
| 		logger.Errorf(`failed to create access_token client. error: %s`, err.Error())
 | |
| 		return ``, err
 | |
| 	}
 | |
| 
 | |
| 	req, err := client.NewRequest(http.MethodPost, u.Path, &oAuthAccessTokenReq{
 | |
| 		ClientID:     clientID,
 | |
| 		ClientSecret: clientSecret,
 | |
| 		Code:         code,
 | |
| 		GrantType:    `authorization_code`,
 | |
| 		RedirectURI:  redirectURI,
 | |
| 	})
 | |
| 	if err != nil {
 | |
| 		logger.Errorf(`failed to create access_token request. error: %s`, err.Error())
 | |
| 		return ``, err
 | |
| 	}
 | |
| 
 | |
| 	atResp := new(oAuthAccessTokenResp)
 | |
| 
 | |
| 	resp, err := client.Do(req, atResp)
 | |
| 	if err != nil {
 | |
| 		logger.Errorf(`failed to request access_token. error: %s`, err.Error())
 | |
| 		return ``, err
 | |
| 	}
 | |
| 
 | |
| 	if resp.StatusCode >= 300 {
 | |
| 		logger.Errorf(`access_token request return wrong code. code: %d, err_msg: %s`, resp.StatusCode, resp.Status)
 | |
| 		return ``, err
 | |
| 	}
 | |
| 
 | |
| 	return atResp.AccessToken, nil
 | |
| }
 |