Skip to content

Commit f6ac35f

Browse files
committed
[client] add auth tokens management methods
1 parent 645149d commit f6ac35f

File tree

6 files changed

+751
-212
lines changed

6 files changed

+751
-212
lines changed

smsgateway/client.go

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,6 @@ const settingsPath = "/settings"
1919
//nolint:revive,staticcheck // backward compatibility
2020
const BASE_URL = BaseURL
2121

22-
type Config struct {
23-
Client *http.Client // Optional HTTP Client, defaults to `http.DefaultClient`
24-
BaseURL string // Optional base URL, defaults to `https://api.sms-gate.app/3rdparty/v1`
25-
User string // Required username
26-
Password string // Required password
27-
}
28-
2922
type Client struct {
3023
*rest.Client
3124

@@ -38,14 +31,19 @@ func NewClient(config Config) *Client {
3831
config.BaseURL = BaseURL
3932
}
4033

34+
headers := make(map[string]string, 1)
35+
if config.Token != "" {
36+
headers["Authorization"] = "Bearer " + config.Token
37+
} else {
38+
headers["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(config.User+":"+config.Password))
39+
}
40+
4141
return &Client{
4242
Client: rest.NewClient(rest.Config{
4343
Client: config.Client,
4444
BaseURL: config.BaseURL,
4545
}),
46-
headers: map[string]string{
47-
"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(config.User+":"+config.Password)),
48-
},
46+
headers: headers,
4947
}
5048
}
5149

@@ -208,3 +206,28 @@ func (c *Client) DeleteWebhook(ctx context.Context, webhookID string) error {
208206

209207
return nil
210208
}
209+
210+
// GenerateToken generates a new access token with specified scopes and ttl.
211+
// Returns the generated token details or an error if the request fails.
212+
func (c *Client) GenerateToken(ctx context.Context, req TokenRequest) (TokenResponse, error) {
213+
path := "/auth/token"
214+
resp := new(TokenResponse)
215+
216+
if err := c.Do(ctx, http.MethodPost, path, c.headers, &req, resp); err != nil {
217+
return *resp, fmt.Errorf("failed to generate token: %w", err)
218+
}
219+
220+
return *resp, nil
221+
}
222+
223+
// RevokeToken revokes an access token with the specified jti (token ID).
224+
// Returns an error if the revocation fails.
225+
func (c *Client) RevokeToken(ctx context.Context, jti string) error {
226+
path := fmt.Sprintf("/auth/token/%s", url.PathEscape(jti))
227+
228+
if err := c.Do(ctx, http.MethodDelete, path, c.headers, nil, nil); err != nil {
229+
return fmt.Errorf("failed to revoke token: %w", err)
230+
}
231+
232+
return nil
233+
}

0 commit comments

Comments
 (0)