|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | +) |
| 10 | + |
| 11 | +func fetchFacebook(domain string) ([]string, error) { |
| 12 | + |
| 13 | + appId := os.Getenv("FB_APP_ID") |
| 14 | + appSecret := os.Getenv("FB_APP_SECRET") |
| 15 | + if appId == "" || appSecret == "" { |
| 16 | + // fail silently because it's reasonable not to have |
| 17 | + // the Facebook API creds |
| 18 | + return []string{}, nil |
| 19 | + } |
| 20 | + |
| 21 | + accessToken, err := facebookAuth(appId, appSecret) |
| 22 | + if err != nil { |
| 23 | + return []string{}, err |
| 24 | + } |
| 25 | + |
| 26 | + domains, err := getFacebookCerts(accessToken, domain) |
| 27 | + if err != nil { |
| 28 | + return []string{}, err |
| 29 | + } |
| 30 | + |
| 31 | + return domains, nil |
| 32 | +} |
| 33 | + |
| 34 | +func getFacebookCerts(accessToken, query string) ([]string, error) { |
| 35 | + out := make([]string, 0) |
| 36 | + fetchURL := fmt.Sprintf( |
| 37 | + "https://graph.facebook.com/certificates?fields=domains&access_token=%s&query=*.%s", |
| 38 | + accessToken, query, |
| 39 | + ) |
| 40 | + |
| 41 | + for { |
| 42 | + |
| 43 | + wrapper := struct { |
| 44 | + Data []struct { |
| 45 | + Domains []string `json:"domains"` |
| 46 | + } `json:"data"` |
| 47 | + |
| 48 | + Paging struct { |
| 49 | + Next string `json:"next"` |
| 50 | + } `json:"paging"` |
| 51 | + }{} |
| 52 | + |
| 53 | + err := fetchJSON(fetchURL, &wrapper) |
| 54 | + if err != nil { |
| 55 | + return out, err |
| 56 | + } |
| 57 | + |
| 58 | + for _, data := range wrapper.Data { |
| 59 | + for _, d := range data.Domains { |
| 60 | + out = append(out, d) |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + fetchURL = wrapper.Paging.Next |
| 65 | + if fetchURL == "" { |
| 66 | + break |
| 67 | + } |
| 68 | + } |
| 69 | + return out, nil |
| 70 | +} |
| 71 | + |
| 72 | +func facebookAuth(appId, appSecret string) (string, error) { |
| 73 | + authUrl := fmt.Sprintf( |
| 74 | + "https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=client_credentials", |
| 75 | + appId, appSecret, |
| 76 | + ) |
| 77 | + |
| 78 | + resp, err := http.Get(authUrl) |
| 79 | + if err != nil { |
| 80 | + return "", err |
| 81 | + } |
| 82 | + |
| 83 | + defer resp.Body.Close() |
| 84 | + |
| 85 | + dec := json.NewDecoder(resp.Body) |
| 86 | + |
| 87 | + auth := struct { |
| 88 | + AccessToken string `json:"access_token"` |
| 89 | + }{} |
| 90 | + err = dec.Decode(&auth) |
| 91 | + if err != nil { |
| 92 | + return "", err |
| 93 | + } |
| 94 | + |
| 95 | + if auth.AccessToken == "" { |
| 96 | + return "", errors.New("no access token in Facebook API response") |
| 97 | + } |
| 98 | + |
| 99 | + return auth.AccessToken, nil |
| 100 | +} |
0 commit comments