auth/auth.go

103 lines
2.2 KiB
Go
Raw Normal View History

package kekskurseauth
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
2024-09-13 09:05:36 +00:00
"time"
)
type Auth struct {
2024-09-13 09:05:36 +00:00
authConfig AuthConfig
clientConfig ClientConfig
}
2024-09-13 09:05:36 +00:00
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiredIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
CreatedAt time.Time
}
func NewAuthWithConfig(config ClientConfig, authConfig AuthConfig) (Auth, error) {
a := Auth{}
2024-09-13 09:05:36 +00:00
a.authConfig = authConfig
a.clientConfig = config
return a, nil
}
2024-09-13 09:05:36 +00:00
func NewAuthWithConfigurationURL(config ClientConfig, url string) (Auth, error) {
a := Auth{}
2024-09-13 09:05:36 +00:00
a.clientConfig = config
authConfig := AuthConfig{}
res, err := http.Get(url)
if err != nil {
return Auth{}, fmt.Errorf("%w: %q", ErrCantGetConfiguratorData, err)
}
defer res.Body.Close()
bodyContent, err := io.ReadAll(res.Body)
if err != nil {
return Auth{}, fmt.Errorf("%w: %q", ErrCantGetConfiguratorData, err)
}
2024-09-13 09:05:36 +00:00
err = json.Unmarshal(bodyContent, &authConfig)
if err != nil {
return Auth{}, fmt.Errorf("%w: %q", ErrCantGetConfiguratorData, err)
}
2024-09-13 09:05:36 +00:00
a.authConfig = authConfig
return a, nil
}
2024-09-13 09:05:36 +00:00
func (a Auth) GetAuthorizationURL(state string) (string, error) {
if a.authConfig.AuthorizationEndpoint == "" {
return "", fmt.Errorf("%w: %s", ErrCantGetAuthorizationURL, "AuthorizationEndpoint in config is empty")
}
2024-09-13 09:05:36 +00:00
if a.clientConfig.ClientID == "" {
return "", fmt.Errorf("%w: %s", ErrCantGetAuthorizationURL, "clientid in config is empty")
}
2024-09-13 09:05:36 +00:00
url, err := url.Parse(a.authConfig.AuthorizationEndpoint)
if err != nil {
return "", fmt.Errorf("%w: %q", ErrCantGetAuthorizationURL, err)
}
values := url.Query()
2024-09-13 09:05:36 +00:00
values.Set("client_id", a.clientConfig.ClientID)
if a.clientConfig.RedirectURL != "" {
values.Set("redirect_uri", a.clientConfig.RedirectURL)
}
2024-09-13 09:05:36 +00:00
if len(a.clientConfig.Scope) > 0 {
values.Set("scope", strings.Join(a.clientConfig.Scope, "+"))
}
if state != "" {
values.Set("state", state)
}
values.Set("response_type", "code")
url.RawQuery = values.Encode()
return url.String(), nil
}
2024-09-13 09:05:36 +00:00
func (a Auth) GetTokenFromCode(code string) (Token, error) {
t := Token{}
form := url.Values{}
form.Add("grant_type", "authorization_code")
form.Add("code", code)
return t, nil
}