| 1 | package bitwarden |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // DirectOrganizationsService handles organization operations via the direct server API. |
| 11 | type DirectOrganizationsService struct { |
| 12 | dc *DirectClient |
| 13 | } |
| 14 | |
| 15 | func (s *DirectOrganizationsService) List(ctx context.Context, search string) ([]Organization, error) { |
| 16 | // Organizations come from the sync profile. |
| 17 | dc := s.dc |
| 18 | dc.mu.RLock() |
| 19 | profile := dc.profile |
| 20 | dc.mu.RUnlock() |
| 21 | |
| 22 | if profile == nil { |
| 23 | return nil, fmt.Errorf("no profile data; call Sync first") |
| 24 | } |
| 25 | |
| 26 | var orgs []Organization |
| 27 | for _, o := range profile.Organizations { |
| 28 | org := Organization{ |
| 29 | ID: o.ID, |
| 30 | Name: o.Name, |
| 31 | Status: o.Status, |
| 32 | Type: o.Type, |
| 33 | Enabled: o.Enabled, |
| 34 | } |
| 35 | if search == "" || strings.Contains(strings.ToLower(org.Name), strings.ToLower(search)) { |
| 36 | orgs = append(orgs, org) |
| 37 | } |
| 38 | } |
| 39 | return orgs, nil |
| 40 | } |
| 41 | |
| 42 | func (s *DirectOrganizationsService) Get(ctx context.Context, id string) (*Organization, error) { |
| 43 | orgs, err := s.List(ctx, "") |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | for _, o := range orgs { |
| 48 | if o.ID == id { |
| 49 | return &o, nil |
| 50 | } |
| 51 | } |
| 52 | return nil, &NotFoundError{Object: "organization", ID: id} |
| 53 | } |
| 54 | |
| 55 | // DirectOrgMembersService handles organization member operations. |
| 56 | type DirectOrgMembersService struct { |
| 57 | dc *DirectClient |
| 58 | } |
| 59 | |
| 60 | func (s *DirectOrgMembersService) List(ctx context.Context, organizationID string) ([]OrgMember, error) { |
| 61 | data, err := s.dc.transport.Get(ctx, "/api/organizations/"+organizationID+"/users", nil) |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | |
| 66 | var resp struct { |
| 67 | Data []OrgMember `json:"data"` |
| 68 | } |
| 69 | if err := json.Unmarshal(data, &resp); err != nil { |
| 70 | return nil, fmt.Errorf("parse org members: %w", err) |
| 71 | } |
| 72 | return resp.Data, nil |
| 73 | } |
| 74 | |
| 75 | func (s *DirectOrgMembersService) Confirm(ctx context.Context, id, organizationID string) error { |
| 76 | body := map[string]string{"organizationId": organizationID} |
| 77 | _, err := s.dc.transport.Post(ctx, "/api/organizations/"+organizationID+"/users/"+id+"/confirm", body) |
| 78 | return err |
| 79 | } |
| 80 | |