|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +type SynapseConfig struct { |
| 12 | + ApiUrl string |
| 13 | + AccessToken string |
| 14 | + Domain string |
| 15 | +} |
| 16 | + |
| 17 | +type Synapse struct { |
| 18 | + client *http.Client |
| 19 | + config *SynapseConfig |
| 20 | +} |
| 21 | + |
| 22 | +func NewSynapse(cfg *SynapseConfig) *Synapse { |
| 23 | + client := &http.Client{} |
| 24 | + |
| 25 | + return &Synapse{ |
| 26 | + client: client, |
| 27 | + config: cfg, |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func (s *Synapse) DeprovisionUser(email string) error { |
| 32 | + // Extract the userId from the email |
| 33 | + userId := strings.Split(email, "@")[0] |
| 34 | + domain := strings.Split(email, "@")[1] |
| 35 | + |
| 36 | + if domain != s.config.Domain { |
| 37 | + return fmt.Errorf("domain not allowed: %s", domain) |
| 38 | + } |
| 39 | + |
| 40 | + body := map[string]any{ |
| 41 | + "erase": true, |
| 42 | + } |
| 43 | + jsonData, err := json.Marshal(body) |
| 44 | + if err != nil { |
| 45 | + return fmt.Errorf("failed to marshal request body: %v", err) |
| 46 | + } |
| 47 | + |
| 48 | + req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/deactivate/@%s:%s", s.config.ApiUrl, userId, domain), bytes.NewBuffer(jsonData)) |
| 49 | + if err != nil { |
| 50 | + return fmt.Errorf("failed to create request: %v", err) |
| 51 | + } |
| 52 | + |
| 53 | + s.prepareRequest(req) |
| 54 | + res, err := s.client.Do(req) |
| 55 | + if err != nil { |
| 56 | + return fmt.Errorf("failed to deprovision user: %v", err) |
| 57 | + } |
| 58 | + defer res.Body.Close() |
| 59 | + |
| 60 | + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNotFound { |
| 61 | + return fmt.Errorf("failed to deprovision user, status code: %d", res.StatusCode) |
| 62 | + } |
| 63 | + |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +func (s *Synapse) prepareRequest(req *http.Request) { |
| 68 | + req.Header.Set("Authorization", fmt.Sprintf("Bearer: %s", s.config.AccessToken)) |
| 69 | + req.Header.Set("Accept", "application/json") |
| 70 | + req.Header.Set("User-Agent", "UserliWebhookListener/1.0") |
| 71 | + req.Header.Set("ocs-apirequest", "true") |
| 72 | +} |
0 commit comments