File: facebook.go

package info (click to toggle)
assetfinder 0.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 124 kB
  • sloc: sh: 55; makefile: 4
file content (100 lines) | stat: -rw-r--r-- 1,893 bytes parent folder | download
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
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"os"
)

func fetchFacebook(domain string) ([]string, error) {

	appId := os.Getenv("FB_APP_ID")
	appSecret := os.Getenv("FB_APP_SECRET")
	if appId == "" || appSecret == "" {
		// fail silently because it's reasonable not to have
		// the Facebook API creds
		return []string{}, nil
	}

	accessToken, err := facebookAuth(appId, appSecret)
	if err != nil {
		return []string{}, err
	}

	domains, err := getFacebookCerts(accessToken, domain)
	if err != nil {
		return []string{}, err
	}

	return domains, nil
}

func getFacebookCerts(accessToken, query string) ([]string, error) {
	out := make([]string, 0)
	fetchURL := fmt.Sprintf(
		"https://graph.facebook.com/certificates?fields=domains&access_token=%s&query=*.%s",
		accessToken, query,
	)

	for {

		wrapper := struct {
			Data []struct {
				Domains []string `json:"domains"`
			} `json:"data"`

			Paging struct {
				Next string `json:"next"`
			} `json:"paging"`
		}{}

		err := fetchJSON(fetchURL, &wrapper)
		if err != nil {
			return out, err
		}

		for _, data := range wrapper.Data {
			for _, d := range data.Domains {
				out = append(out, d)
			}
		}

		fetchURL = wrapper.Paging.Next
		if fetchURL == "" {
			break
		}
	}
	return out, nil
}

func facebookAuth(appId, appSecret string) (string, error) {
	authUrl := fmt.Sprintf(
		"https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=client_credentials",
		appId, appSecret,
	)

	resp, err := http.Get(authUrl)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)

	auth := struct {
		AccessToken string `json:"access_token"`
	}{}
	err = dec.Decode(&auth)
	if err != nil {
		return "", err
	}

	if auth.AccessToken == "" {
		return "", errors.New("no access token in Facebook API response")
	}

	return auth.AccessToken, nil
}