constanze/oauth.go

88 lines
2.2 KiB
Go

package main
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"io"
"net/url"
)
type OAuthApp struct {
ClientId string `json:"client_id" yaml:"client_id"`
ClientSecret string `json:"client_secret" yaml:"client_secret"`
}
type OAuthToken struct {
AccessToken string `json:"access_token" yaml:"access_token"`
Me string `json:"me" yaml:"me"`
RefreshToken string `json:"refresh_token" yaml:"refresh_token"`
Scope string `json:"scope" yaml:"scope"`
TokenType string `json:"token_type" yaml:"token_type"`
}
func CreateOAuthApp(instanceUrl string, clientName string, scopes string) (OAuthApp, error) {
uri, err := url.JoinPath(instanceUrl, "/api/v1/apps")
if err != nil {
return OAuthApp{}, err
}
request := map[string]interface{}{
"client_name": clientName,
"redirect_uris": "urn:ietf:wg:oauth:2.0:oob",
"scopes": scopes,
}
response, err := Post(uri, request)
if err != nil {
return OAuthApp{}, err
}
body, err := io.ReadAll(response.Body)
app := &OAuthApp{}
err = json.Unmarshal(body, app)
if err != nil {
return OAuthApp{}, err
}
return *app, nil
}
func RequestToken(instanceUrl string, oauthApp OAuthApp, scopes string, code string) (OAuthToken, error) {
log.Debug("Requesting token")
args := map[string]interface{}{
"client_id": oauthApp.ClientId,
"client_secret": oauthApp.ClientSecret,
"code": code,
"grant_type": "authorization_code",
"redirect_uri": "urn:ietf:wg:oauth:2.0:oob",
"scope": scopes,
}
tokenUrl, err := url.JoinPath(instanceUrl, "/oauth/token")
if err != nil {
return OAuthToken{}, err
}
response, err := Post(tokenUrl, args)
if err != nil {
return OAuthToken{}, err
}
body, err := io.ReadAll(response.Body)
token := &OAuthToken{}
err = json.Unmarshal(body, token)
if err != nil {
return OAuthToken{}, err
}
return *token, nil
}
func AuthorizeUrl(instanceUrl string, oauthApp OAuthApp, scopes string) (string, error) {
args := url.Values{
"client_id": {oauthApp.ClientId},
"redirect_uri": {"urn:ietf:wg:oauth:2.0:oob"},
"response_type": {"code"},
"scope": {scopes},
}.Encode()
authUrl, err := url.JoinPath(instanceUrl, "/oauth/authorize")
if err != nil {
return "", err
}
return authUrl + "?" + args, nil
}