-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
368 lines (309 loc) · 11.9 KB
/
client.go
File metadata and controls
368 lines (309 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright 2017-2026 Allow2 Pty Ltd. All rights reserved.
// Use of this source code is governed by the Allow2 API and SDK Licence.
// Package allow2service provides the Allow2 Parental Freedom Service SDK for Go.
//
// This SDK is for web services with user accounts (SaaS, forums, web apps, etc.).
// It handles OAuth2 pairing, permission checking, all 3 request types,
// voice codes, and feedback via the Allow2 Service API.
//
// Each linked service account maps to exactly one Allow2 child -- there is
// no child selector in Service API integrations.
package allow2service
// Option is a functional option for configuring Allow2Client.
type Option func(*Allow2Client)
// WithHTTPClient sets a custom HTTP client.
func WithHTTPClient(c HTTPClient) Option {
return func(a *Allow2Client) {
a.http = c
}
}
// WithAPIHost sets the Allow2 API base URL.
func WithAPIHost(host string) Option {
return func(a *Allow2Client) {
a.apiHost = host
}
}
// WithServiceHost sets the Allow2 Service base URL.
func WithServiceHost(host string) Option {
return func(a *Allow2Client) {
a.serviceHost = host
}
}
// WithCacheTTL sets the permission check cache TTL in seconds.
func WithCacheTTL(ttl int) Option {
return func(a *Allow2Client) {
a.cacheTTL = ttl
}
}
// Allow2Client is the main entry point for the Allow2 Go SDK (Service API).
//
// It wraps OAuth2 authorization, permission checking, request creation,
// feedback, and offline voice code features into a single coherent API.
type Allow2Client struct {
clientID string
clientSecret string
tokenStorage TokenStorage
cache Cache
http HTTPClient
apiHost string
serviceHost string
cacheTTL int
oauth *oauth2Manager
checker *permissionChecker
requests *requestManager
feedback *feedbackManager
}
// New creates a new Allow2Client with the given credentials, storage, cache,
// and optional functional options.
func New(clientID, clientSecret string, tokenStorage TokenStorage, cache Cache, opts ...Option) *Allow2Client {
c := &Allow2Client{
clientID: clientID,
clientSecret: clientSecret,
tokenStorage: tokenStorage,
cache: cache,
apiHost: "https://api.allow2.com",
serviceHost: "https://service.allow2.com",
cacheTTL: 60,
}
for _, opt := range opts {
opt(c)
}
if c.http == nil {
c.http = newDefaultHTTPClient()
}
c.oauth = &oauth2Manager{
clientID: c.clientID,
clientSecret: c.clientSecret,
tokenStorage: c.tokenStorage,
httpClient: c.http,
apiHost: c.apiHost,
}
c.checker = &permissionChecker{
httpClient: c.http,
cache: c.cache,
serviceHost: c.serviceHost,
cacheTTL: c.cacheTTL,
}
c.requests = &requestManager{
httpClient: c.http,
apiHost: c.apiHost,
}
c.feedback = &feedbackManager{
httpClient: c.http,
apiHost: c.apiHost,
}
return c
}
// ──────────────────────────────────────────────────────────
// OAuth2
// ──────────────────────────────────────────────────────────
// GetAuthorizeURL builds the OAuth2 authorization URL to redirect the user to.
// The user will be asked to link their Allow2 child account to your service.
// Pass an empty string for state if not using CSRF protection (not recommended).
func (c *Allow2Client) GetAuthorizeURL(userID, redirectURI, state string) string {
return c.oauth.GetAuthorizeURL(userID, redirectURI, state)
}
// ExchangeCode exchanges an authorization code for OAuth2 tokens.
// Call this in your redirect_uri callback handler.
func (c *Allow2Client) ExchangeCode(userID, code, redirectURI string) (*OAuthTokens, error) {
return c.oauth.ExchangeCode(userID, code, redirectURI)
}
// CheckPairingStatus checks whether a user's Allow2 account pairing is still valid.
func (c *Allow2Client) CheckPairingStatus(userID string) bool {
return c.oauth.CheckPairingStatus(userID)
}
// Unpair removes a user's stored OAuth2 tokens.
func (c *Allow2Client) Unpair(userID string) error {
return c.oauth.Unpair(userID)
}
// IsPaired checks whether the user has stored OAuth2 tokens (i.e., has been paired).
func (c *Allow2Client) IsPaired(userID string) bool {
return c.oauth.HasTokens(userID)
}
// ──────────────────────────────────────────────────────────
// Permission Checking
// ──────────────────────────────────────────────────────────
// ActivityInput represents an activity to check permissions for.
type ActivityInput struct {
ID int `json:"id"`
Log bool `json:"log"`
}
// Check checks permissions for a user's linked Allow2 child account.
// Pass an empty string for timezone to use server default.
func (c *Allow2Client) Check(userID string, activities []ActivityInput, timezone string) (*CheckResult, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
result, err := c.checker.Check(accessToken, userID, activities, timezone)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return nil, err
}
return result, nil
}
// IsAllowed is a convenience method that checks if all specified activities are currently allowed.
func (c *Allow2Client) IsAllowed(userID string, activityIDs []int) (bool, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return false, err
}
result, err := c.checker.IsAllowed(accessToken, userID, activityIDs)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return false, err
}
return result, nil
}
// ──────────────────────────────────────────────────────────
// Requests (More Time, Day Type Change, Ban Lift)
// ──────────────────────────────────────────────────────────
// RequestMoreTime requests more time for an activity.
func (c *Allow2Client) RequestMoreTime(userID string, activityID, minutes int, message string) (*RequestResult, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
result, err := c.requests.RequestMoreTime(accessToken, userID, activityID, minutes, message)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return nil, err
}
return result, nil
}
// RequestDayTypeChange requests a day type change (e.g., treat today as a weekend).
func (c *Allow2Client) RequestDayTypeChange(userID string, dayTypeID int, message string) (*RequestResult, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
result, err := c.requests.RequestDayTypeChange(accessToken, userID, dayTypeID, message)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return nil, err
}
return result, nil
}
// RequestBanLift requests lifting a ban on an activity.
func (c *Allow2Client) RequestBanLift(userID string, activityID int, message string) (*RequestResult, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
result, err := c.requests.RequestBanLift(accessToken, userID, activityID, message)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return nil, err
}
return result, nil
}
// GetRequestStatus polls the status of a pending request.
// Returns "pending", "approved", or "denied".
func (c *Allow2Client) GetRequestStatus(requestID, statusSecret string) (string, error) {
return c.requests.GetRequestStatus(requestID, statusSecret)
}
// GetRequestToken obtains a temporary request token from the Allow2 API.
// Used by integrations that manage the request creation flow themselves.
func (c *Allow2Client) GetRequestToken(userID string, nonce string) (map[string]interface{}, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
return c.requests.GetTempToken(accessToken, nonce)
}
// ──────────────────────────────────────────────────────────
// Voice Codes (Offline Approval)
// ──────────────────────────────────────────────────────────
// GenerateVoiceChallenge generates an offline voice code challenge-response pair.
// Pass empty strings for userID and date to use defaults.
func (c *Allow2Client) GenerateVoiceChallenge(secret string, reqType RequestType, activityID, minutes int, userID, date string) (*VoiceCodePair, error) {
if secret == "" {
return nil, &Allow2Error{
Message: "A pairing secret is required for voice code generation. " +
"This should be stored during the OAuth2 pairing process.",
}
}
return GenerateVoiceChallenge(secret, reqType, activityID, minutes, date)
}
// VerifyVoiceResponse verifies a voice code response entered by the child.
// Pass empty strings for userID and date to use defaults.
func (c *Allow2Client) VerifyVoiceResponse(secret, challenge, response, userID, date string) bool {
if secret == "" {
return false
}
return VerifyVoiceResponse(secret, challenge, response, date)
}
// ──────────────────────────────────────────────────────────
// Feedback
// ──────────────────────────────────────────────────────────
// SubmitFeedback submits feedback from the user. Returns the discussion ID.
func (c *Allow2Client) SubmitFeedback(userID string, category FeedbackCategory, message string) (string, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return "", err
}
result, err := c.feedback.Submit(accessToken, userID, category, message)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return "", err
}
return result, nil
}
// LoadFeedback loads all feedback discussion threads for the user.
func (c *Allow2Client) LoadFeedback(userID string) ([]interface{}, error) {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return nil, err
}
result, err := c.feedback.Load(accessToken, userID)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return nil, err
}
return result, nil
}
// ReplyToFeedback replies to an existing feedback discussion thread.
func (c *Allow2Client) ReplyToFeedback(userID, discussionID, message string) error {
accessToken, err := c.getAccessToken(userID)
if err != nil {
return err
}
err = c.feedback.Reply(accessToken, userID, discussionID, message)
if err != nil {
if isUnpairedError(err) {
c.handleUnpaired(userID)
}
return err
}
return nil
}
// ──────────────────────────────────────────────────────────
// Internal
// ──────────────────────────────────────────────────────────
// getAccessToken gets a valid access token for the user, auto-refreshing if needed.
func (c *Allow2Client) getAccessToken(userID string) (string, error) {
return c.oauth.GetAccessToken(userID)
}
// handleUnpaired clears tokens on unpaired error.
func (c *Allow2Client) handleUnpaired(userID string) {
_ = c.tokenStorage.Delete(userID)
}
// isUnpairedError checks if an error is an UnpairedError.
func isUnpairedError(err error) bool {
_, ok := err.(*UnpairedError)
return ok
}