Skip to content

Instantly share code, notes, and snippets.

@anisbhsl
Created November 25, 2019 08:46
Show Gist options
  • Save anisbhsl/58f9e74cc94f64ba471abc2210c261ac to your computer and use it in GitHub Desktop.
Save anisbhsl/58f9e74cc94f64ba471abc2210c261ac to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"golang.org/x/oauth2"
"io/ioutil"
"log"
"net/http"
)
var config = &oauth2.Config{
ClientID: "YOUR CLIENT ID HERE",
ClientSecret: "CLIENT SECRET HERE",
Endpoint: oauth2.Endpoint{
AuthURL: "https://graph.facebook.com/oauth/authorize",
TokenURL: "https://graph.facebook.com/oauth/access_token",
},
RedirectURL: "http://localhost:8000/auth/facebook/callback",
Scopes: []string{"email","user_likes","user_birthday","user_gender"},
}
//OAuth handler for facebook OAuth
func facebookLoginHandler(w http.ResponseWriter, r *http.Request){
url:=config.AuthCodeURL("fileupload")
http.Redirect(w,r,url,http.StatusTemporaryRedirect)
}
//facebook auth callback
func facebookCallbackHandler(w http.ResponseWriter, r *http.Request){
state:=r.FormValue("state")
if state!="fileupload"{
fmt.Println("Invalid oauth state")
http.Redirect(w,r,"/",http.StatusTemporaryRedirect) //307
}
code:=r.FormValue("code")
token,err:=config.Exchange(oauth2.NoContext,r.URL.Query().Get("code"))
if err!=nil{
fmt.Println("Code exchange failed %s",err)
http.Redirect(w,r,"/",http.StatusTemporaryRedirect)
}
response,err:=http.Get("https://graph.facebook.com/me?fields=name,email,gender,user&access_token=" + token.AccessToken)
defer response.Body.Close()
var facebookResponse interface{}
contents,err:=ioutil.ReadAll(response.Body)
json.Unmarshal(contents,&facebookResponse)
w.Header().Add("Content-Type","application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(facebookResponse)
fmt.Println(facebookResponse)
}
func indexHandler(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w,"WELCOME TO FACEBOOK OAUTH APP")
}
func main(){
router:=mux.NewRouter()
router.HandleFunc("/", indexHandler)
//ouath using facebook
router.HandleFunc("/auth/facebook",facebookLoginHandler)
//callback handler
router.HandleFunc("/auth/facebook/callback",facebookCallbackHandler)
log.Fatal(http.ListenAndServe(":8000",router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment