github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/settings/clients_usage.go (about) 1 package settings 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/cozy/cozy-stack/model/feature" 8 "github.com/cozy/cozy-stack/model/oauth" 9 "github.com/cozy/cozy-stack/model/permission" 10 "github.com/cozy/cozy-stack/pkg/consts" 11 "github.com/cozy/cozy-stack/pkg/couchdb" 12 "github.com/cozy/cozy-stack/pkg/jsonapi" 13 "github.com/cozy/cozy-stack/web/middlewares" 14 "github.com/labstack/echo/v4" 15 ) 16 17 type apiClientsUsage struct { 18 Limit *int `json:"limit,omitempty"` 19 Count int `json:"count"` 20 LimitReached bool `json:"limitReached"` 21 LimitExceeded bool `json:"limitExceeded"` 22 } 23 24 func (j *apiClientsUsage) ID() string { return consts.ClientsUsageID } 25 func (j *apiClientsUsage) Rev() string { return "" } 26 func (j *apiClientsUsage) DocType() string { return consts.Settings } 27 func (j *apiClientsUsage) Clone() couchdb.Doc { return j } 28 func (j *apiClientsUsage) SetID(_ string) {} 29 func (j *apiClientsUsage) SetRev(_ string) {} 30 func (j *apiClientsUsage) Relationships() jsonapi.RelationshipMap { return nil } 31 func (j *apiClientsUsage) Included() []jsonapi.Object { return nil } 32 func (j *apiClientsUsage) Links() *jsonapi.LinksList { 33 return &jsonapi.LinksList{Self: "/settings/clients-usage"} 34 } 35 36 // Settings objects permissions are only on ID 37 func (j *apiClientsUsage) Fetch(field string) []string { return nil } 38 39 func (h *HTTPHandler) clientsUsage(c echo.Context) error { 40 inst := middlewares.GetInstance(c) 41 var result apiClientsUsage 42 43 if err := middlewares.Allow(c, permission.GET, &result); err != nil { 44 return err 45 } 46 47 flags, err := feature.GetFlags(inst) 48 if err != nil { 49 return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("Could not get flags: %w", err)) 50 } 51 52 limit := -1 53 if clientsLimit, ok := flags.M["cozy.oauthclients.max"].(float64); ok && clientsLimit >= 0 { 54 limit = int(clientsLimit) 55 } 56 57 clients, _, err := oauth.GetConnectedUserClients(inst, 100, "") 58 if err != nil { 59 return fmt.Errorf("Could not get user OAuth clients: %w", err) 60 } 61 count := len(clients) 62 63 if limit != -1 { 64 result.Limit = &limit 65 66 if count >= limit { 67 result.LimitReached = true 68 } 69 if count > limit { 70 result.LimitExceeded = true 71 } 72 } 73 result.Count = count 74 return jsonapi.Data(c, http.StatusOK, &result, nil) 75 }