func main() { access_token := flag.String("t", FB_VALID_ACCESS_TOKEN, "a valid access token") from := flag.Int("f", 0, "a valid access token") inputFile := flag.String("i", "default", "a path to read file") flag.Parse() if *inputFile == "default" { return } file, err := os.Open(*inputFile) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) // create a global App var to hold app id and secret. var globalApp = fb.New(FB_APP_ID, FB_APP_SECRET) // facebook asks for a valid redirect uri when parsing signed request. // it's a new enforced policy starting in late 2013. globalApp.RedirectUri = "https://www.facebook.com/connect/login_success.html" // if there is another way to get decoded access token, // creates a session directly with the token. session := globalApp.Session(*access_token) // validate access token. err is nil if token is valid. err = session.Validate() if err != nil { return } fmt.Println("objid,ownerid,name,imgurl") linenumber := 0 for scanner.Scan() { fb_obj_id := scanner.Text() log.Printf("%v %v\n", linenumber, fb_obj_id) if linenumber >= *from { get_source(session, fb_obj_id) time.Sleep(2000 * time.Millisecond) } linenumber += 1 } if err := scanner.Err(); err != nil { log.Fatal(err) } return }
/* DELETE: http://localhost:8080/ad/{id}/{token} { status: "OK" "data":"Deleted" } */ func DeleteAd(w http.ResponseWriter, r *http.Request) { var ad, token string s := strings.Split(r.URL.Path, "/") if len(s) >= 4 { ad, token = s[2], s[3] } else { w.Write(json.Message3("ERROR", nil, "Wrong URL")) return } // create a global App var to hold your app id and secret. var globalApp = fb.New("1454662381420609", "9a9d5fd67edc5245f366a1a0fb9bb9bf") // facebook asks for a valid redirect uri when parsing signed request. // it's a new enforced policy starting in late 2013. // it can be omitted in a mobile app server. //globalApp.RedirectUri = "" // here comes a client with a facebook signed request string in query string. // creates a new session with signed request. //session, _ := globalApp.SessionFromSignedRequest(signedRequest) // or, you just get a valid access token in other way. // creates a session directly. session := globalApp.Session(token) // use session to send api request with your access token. //res, _ := session.Get("/me/feed", nil) // validate access token. err is nil if token is valid. err := session.Validate() if err == nil { session, err := mgo.Dial(conf.Mongodb) if err != nil { log.Fatal("Unable to connect to DB ", err) } defer session.Close() session.SetMode(mgo.Monotonic, true) // Optional. Switch the session to a monotonic behavior. db := session.DB("sa") err = db.C("ad").Remove(bson.M{"_id": bson.ObjectIdHex(ad)}) if err != nil { w.Write(json.Message("ERROR", "Could not DELETE")) log.Printf("err = %s\n", err) } else { w.Write(json.Message("OK", "Deleted")) } } else { w.Write(json.Message("ERROR", "Not valid session")) } }
"strings" "time" _ "image/jpeg" _ "image/png" fb "github.com/huandu/facebook" "appengine" "appengine/datastore" "appengine/urlfetch" ) //var APPSECRET = os.Getenv("APPSECRET") var clientID = "526791527487217" var FbApp = fb.New(clientID, APPSECRET) var aboutParams = fb.Params{ "method": fb.GET, "relative_url": "me?fields=name,email,gender,age_range,address,location", } var photoParams = fb.Params{ "method": fb.GET, "relative_url": "me/picture?width=320&height=320&redirect=false", } func init() { http.HandleFunc("/static/", StaticHandler) http.HandleFunc("/", MainHandler) http.HandleFunc("/web/", WebHandler)
package main import ( "github.com/hashicorp/golang-lru" fb "github.com/huandu/facebook" ) type FacebookInfo struct { Id string Name string } var ( NameCache, _ = lru.New(256) GlobalApp = fb.New(ClientId, ApiSecret) ) func GetId(accessToken string) (string, error) { if val, ok := NameCache.Get(accessToken); ok { return val.(FacebookInfo).Id, nil } return exchangeAccessToken(accessToken) } func exchangeAccessToken(accessToken string) (string, error) { session := GlobalApp.Session(accessToken) err := session.Validate() if err != nil {
} type EventPlace struct { Name string `facebook:"name"` } var ( oauthConf = &oauth2.Config{ ClientID: conf.Config.FacebookID, ClientSecret: conf.Config.FacebookSecret, RedirectURL: conf.Config.BaseURL + "/facebook_callback", Scopes: []string{"user_events"}, Endpoint: facebookoauth.Endpoint, } oauthStateString = conf.Config.OAuthStateString fb = facebook.New(conf.Config.FacebookID, conf.Config.FacebookSecret) ) func main() { // Serve static files. staticDirs := []string{"bower_components", "res"} for _, d := range staticDirs { static := web.New() pattern, prefix := fmt.Sprintf("/%s/*", d), fmt.Sprintf("/%s/", d) static.Get(pattern, http.StripPrefix(prefix, http.FileServer(http.Dir(d)))) http.Handle(prefix, static) } goji.Use(applySessions) goji.Use(context.ClearHandler)
func main() { // TODO move to own handler // create a global App var to hold your app id and secret. globalApp := fb.New(os.Getenv("FACEBOOK_APP_ID"), os.Getenv("FACEBOOK_SECRET")) globalApp.RedirectUri = "http://localhost:3000/auth/facebook/callback" // TODO // https://developers.facebook.com/docs/graph-api/securing-requests globalApp.EnableAppsecretProof = true // instantiate Martini m := martini.Classic() m.Use(martini.Logger()) // setup database dbmap = initDb() defer dbmap.Db.Close() // CORS m.Use(cors.Allow(&cors.Options{ AllowOrigins: []string{"http://localhost:*"}, AllowMethods: []string{"GET", "POST"}, AllowHeaders: []string{"Origin", "Authorization", "Content-Type"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, })) // Authentication m.Use(func(c martini.Context, res http.ResponseWriter, req *http.Request) { accessToken := req.Header.Get("Authorization") // TODO expect "Bearer: {TOKEN}" format? session := globalApp.Session(accessToken) // TODO DELETE ME log.Printf("accessToken=%s", accessToken) // TODO make currentUser globally available // TODO add User struct and use res.Decode(&user) var user *User attrs, err := session.Get("/me", nil) if err != nil { // err can be an facebook API error. // if so, the Error struct contains error details. if e, ok := err.(*fb.Error); ok { log.Printf("Facebook error. [message:%v] [type:%v] [code:%v] [subcode:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode) } res.WriteHeader(http.StatusUnauthorized) } else { user = findOrCreateUser(attrs) c.Map(user) } if user != nil { log.Printf("Logged in as: %s %s", user.FirstName, user.LastName) } }) // Encoding m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) { // Use indentations. &pretty=1 pretty, _ := strconv.ParseBool(r.FormValue("pretty")) // Use null instead of empty object for json &null=1 null, _ := strconv.ParseBool(r.FormValue("null")) // JSON no matter what c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil)) w.Header().Set("Content-Type", "application/json; charset=utf-8") }) m.Get("/", func(user *User) string { // serve SPA ? return "Hello world" + user.FirstName }) m.Get("/tells", func(enc encoder.Encoder, user *User) (int, []byte) { // get all tells for user and render JSON array tells := user.getTells() return http.StatusOK, encoder.Must(enc.Encode(tells)) }) m.Post("/tells", binding.Bind(Tell{}), func(enc encoder.Encoder, user *User, tell Tell) (int, []byte) { // create new tell for user tell = user.Tell(tell) return http.StatusOK, encoder.Must(enc.Encode(tell)) }) m.Run() }
func facebookSession() *facebook.Session { app := facebook.New(os.Getenv("facebookApiID"), os.Getenv("facebookAppSecret")) app.RedirectUri = "http://syntropy.io" return app.Session(app.AppAccessToken()) }
// usage: go run demo.go OR go run demo.go <number> package main import ( "fmt" fb "github.com/huandu/facebook" "net/http" netUrl "net/url" "os" ) var globalApp = fb.New(clientId, os.Args[1]) var leToken = "" const clientId = "509571419145066" type Post struct { Id string `facebook:",required"` Message string CreatedTime string } type Paging struct { Previous, Next string } func processPosts(url string, total int) int { fmt.Println(url) res, err := fb.Get(url, fb.Params{ // "access_token": ACCESS_TOKEN,