104 lines
2.3 KiB
Go
104 lines
2.3 KiB
Go
package idms
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"clintonambulance.com/calculate_negative_points/internal/config"
|
|
"resty.dev/v3"
|
|
)
|
|
|
|
type Method string
|
|
|
|
const Get Method = "GET"
|
|
const Post Method = "POST"
|
|
const Put Method = "PUT"
|
|
const Delete Method = "Delete"
|
|
|
|
type ResponsePagination struct {
|
|
Count int `json:"count"`
|
|
Current int `json:"current"`
|
|
EndIndex int `json:"end_index"`
|
|
Next int `json:"next"`
|
|
Previous int `json:"previous"`
|
|
StartIndex int `json:"start_index"`
|
|
TotalPages int `json:"total_pages"`
|
|
}
|
|
|
|
type IdmsResponse[T any] struct {
|
|
Pagination ResponsePagination `json:"pagination"`
|
|
Results []T `json:"results"`
|
|
}
|
|
|
|
type TokenResponse struct {
|
|
AccessToken string `json:"access_token"`
|
|
}
|
|
|
|
type IdmsRequest[T any] struct {
|
|
Method Method
|
|
Path string
|
|
ResponseDecoder *IdmsResponse[T]
|
|
}
|
|
|
|
func newRestyRequest(url string, path string) *resty.Request {
|
|
client := resty.New()
|
|
formattedUrl := fmt.Sprintf("%s%s", url, path)
|
|
req := client.R()
|
|
req.SetURL(formattedUrl)
|
|
defer client.Close()
|
|
|
|
return req
|
|
}
|
|
|
|
func GetToken(config *config.ApplicationConfig) (string, error) {
|
|
req := newRestyRequest(config.Idms.BaseUrl, "/application/o/token/")
|
|
|
|
req.SetResult(&TokenResponse{})
|
|
req.SetMethod(string(Post))
|
|
req.SetFormData(map[string]string{
|
|
"client_id": config.Idms.Id.Value(),
|
|
"grant_type": "client_credentials",
|
|
"password": config.Idms.Password.Value(),
|
|
"scope": "goauthentik.io/api",
|
|
"username": "service",
|
|
})
|
|
|
|
res, err := req.Send()
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
data := res.Result().(*TokenResponse).AccessToken
|
|
|
|
return data, nil
|
|
}
|
|
|
|
func NewRequest[T any](path string, method Method) IdmsRequest[T] {
|
|
return IdmsRequest[T]{
|
|
Method: method,
|
|
Path: path,
|
|
ResponseDecoder: &IdmsResponse[T]{},
|
|
}
|
|
}
|
|
|
|
func (r IdmsRequest[T]) Perform(config *config.ApplicationConfig, bodyData interface{}, headers map[string]string) ([]T, error) {
|
|
req := newRestyRequest(config.Idms.BaseUrl, r.Path)
|
|
token, err := GetToken(config)
|
|
|
|
if err != nil {
|
|
return []T{}, err
|
|
}
|
|
|
|
req.SetResult(r.ResponseDecoder).SetAuthToken(token).SetContentType("application/json")
|
|
req.SetMethod(string(r.Method))
|
|
res, err := req.Send()
|
|
|
|
if err != nil {
|
|
return []T{}, err
|
|
}
|
|
|
|
data := res.Result().(*IdmsResponse[T]).Results
|
|
|
|
return data, nil
|
|
}
|