示例#1
0
func Callback(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	//check state validity, see url := Config.AuthCodeURL(state) above
	state_check := r.FormValue("state")
	if State != state_check {
		http.Error(w, fmt.Sprintf("Wrong state string: Expected %s, got %s. Please, try again", State, state_check), http.StatusBadRequest)
		return
	}

	token, err := GetConfig().Exchange(oauth2.NoContext, r.FormValue("code"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	client := GetConfig().Client(oauth2.NoContext, token)
	service, err := goauth2.New(client)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	uService := goauth2.NewUserinfoService(service)
	gouser, err := uService.Get().Do()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	fmt.Fprintf(w, "Username: %s %s<br>ID: %s<br>Email: %s<br>Picture: %s<br>", gouser.GivenName, gouser.FamilyName, gouser.Id, gouser.Email, gouser.Picture)
}
示例#2
0
//GoogleCallback handles /google_callback route
func GoogleCallback(w http.ResponseWriter, r *http.Request) {
	tmpl := context.Get(r, "template").(*template.Template)
	session := context.Get(r, "session").(*sessions.Session)

	state := r.FormValue("state")
	if oauthState != state {
		err := fmt.Errorf("Wrong state string: Expected %s, got %s. Please, try again", oauthState, state)
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(400)
		tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err))
		return
	}

	token, err := goConfig().Exchange(oauth2.NoContext, r.FormValue("code"))
	if err != nil {
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(400)
		tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err))
		return
	}

	client := goConfig().Client(oauth2.NoContext, token)
	service, err := goauth2.New(client)
	if err != nil {
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(400)
		tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err))
		return
	}
	uService := goauth2.NewUserinfoService(service)
	gouser, err := uService.Get().Do()
	if err != nil {
		log.Printf("ERROR: %s\n", err)
		w.WriteHeader(400)
		tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err))
		return
	}

	redirectURL := session.Values["oauth_redirect"]
	delete(session.Values, "oauth_redirect")
	session.Values["oauth_email"] = gouser.Email
	session.Values["oauth_name"] = gouser.GivenName + " " + gouser.FamilyName
	session.Save(r, w)
	if url, ok := redirectURL.(string); ok {
		http.Redirect(w, r, url, 303)
	} else {
		http.Redirect(w, r, "/", 303)
	}
}